filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_7137 | # -*- coding: utf-8 -*-
import os
import sys
import argparse
from evaluate import evaluate_beam_search
import logging
import numpy as np
import config
import utils
import torch
import torch.nn as nn
from torch import cuda
from beam_search import SequenceGenerator
from train import load_data_vocab, init_model, init_o... |
the-stack_0_7140 | import logging
import re
import feedparser
from requests.auth import AuthBase
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.cached_input import cached
from flexget.utils.requests import RequestException
log = logging.getLogger('apple_trailers')
class ... |
the-stack_0_7142 | import os
import torch
import faiss
from argparse import ArgumentParser
from tqdm import tqdm
from typing import List
from collections import defaultdict
def load_rerank_f(fname):
if not fname:
return None
f = open(fname)
ret = defaultdict(set)
for line in f:
line = line.strip().split(... |
the-stack_0_7144 | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weight_reduce_loss
def cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=N... |
the-stack_0_7145 | import shapely.geometry
import numpy as np
import fiona.crs
import pyproj
from shapely.geometry.point import Point
UTM_ZONE30 = pyproj.Proj(
proj='utm',
zone=30,
datum='WGS84',
units='m',
errcheck=True)
schema = {'geometry': 'LineString', 'properties': {'PhysID': 'int'}}
crs = fiona.crs.from_string... |
the-stack_0_7146 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
the-stack_0_7147 | from voximplant.apiclient import VoximplantAPI, VoximplantException
if __name__ == "__main__":
voxapi = VoximplantAPI("credentials.json")
# Delete the application 1 and 3.
APPLICATION_ID = [1, 3]
try:
res = voxapi.del_application(application_id=APPLICATION_ID)
print(res)
... |
the-stack_0_7149 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: possibility.py
# Purpose: music21 class to define rule checking methods for a possibility
# represented as a tuple.
# Authors: Jose Cabal-Ugaz
#
# Copyright: Copyright © 2... |
the-stack_0_7150 | #!/usr/bin/env python
import pygame # pylint: disable=import-error
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
# This is a simple class that will help us print to the screen
# It has nothing to do with the joysticks, just outputting the
# information.
class TextPrint:
def __init_... |
the-stack_0_7153 | import math
from config.config import config
class Plot:
@staticmethod
def line(prices, size=(100, 100), position=(0, 0), draw=None, fill=None):
assert draw
max_price = max(prices)
min_price = min(prices)
normalised_prices = [(price - min_price) / (max_price - min_price) for pri... |
the-stack_0_7154 | """
Explores the kbase draft to see if any metabolic genes are present which are not present in iSG3
"""
import os
from settings import INTERMEDIATE_MODEL_ROOT
import pandas as pd
import re
import cobra as cb
df = pd.read_excel(os.path.join(INTERMEDIATE_MODEL_ROOT,'kbase-draft', 'draft_dsm.xls'),
... |
the-stack_0_7155 | """xception in pytorch
[1] François Chollet
Xception: Deep Learning with Depthwise Separable Convolutions
https://arxiv.org/abs/1610.02357
"""
import torch
import torch.nn as nn
__all__ = ['xception']
class SeperableConv2d(nn.Module):
#***Figure 4. An “extreme” version of our Inception module,
#w... |
the-stack_0_7156 | import unittest
import numpy as np
import openmdao.api as om
import numpy.testing as npt
import wisdem.commonse.wind_wave_drag as wwd
from openmdao.utils.assert_utils import assert_check_partials
npts = 100
myones = np.ones((npts,))
class TestDrag(unittest.TestCase):
def setUp(self):
self.params = {}
... |
the-stack_0_7158 | import sys
import pickle
import numpy as np
from scipy.stats import bernoulli
sys.path.append('./../')
sys.path.append('./../../')
from src.FullModel.model import Model as parent_model
from src.LocalGlobalAttentionModel.model import Model as super_model
from .vel_param import VelParam as vel_param
from src.HMC.hmc im... |
the-stack_0_7164 | #!/usr/bin/env python3
import functools
import os.path
import numpy as np
class CExample(object):
def __init__(self, x, y, w, z=1):
self.x = x
self.y = y
self.w = w
self.z = z
def copy(self):
return CExample(self.x, self.y, self.w, self.z)
class CDataSet(object):
... |
the-stack_0_7168 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
import django.db.models.deletion
import utils.time
class Migration(migrations.Migration):
dependencies = [
('events', '0037_merge'),
migrations.swappable_depe... |
the-stack_0_7169 | #!/usr/bin/env python
"""This module serializes AFF4 objects in various ways."""
import yaml
from grr.lib import aff4
from grr.lib import rdfvalue
def YamlDumper(aff4object):
"""Dumps the given aff4object into a yaml representation."""
aff4object.Flush()
result = {}
for attribute, values in aff4object.sync... |
the-stack_0_7170 | import streamlit as st
import pandas as pd
import pickle
import numpy as np
st.write("""
## Forest Fires
""")
st.sidebar.header('User Input')
st.sidebar.subheader('Please enter your data:')
# -- Define function to display widgets and store data
def get_input():
# Display widgets and store th... |
the-stack_0_7172 | """Tests downloading and reading of the GO annotation file from NCBI Gene.
python test_NCBI_Entrez_annotations.py
"""
__copyright__ = "Copyright (C) 2016, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
import sys
from goatools.associations import get_assoc_ncbi_taxids
from coll... |
the-stack_0_7173 | # -*- coding: utf-8 -*-
# Copyright 2020 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... |
the-stack_0_7174 | # ==============================================================================
# Copyright 2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... |
the-stack_0_7177 | from collections import namedtuple
from itertools import chain
from django.conf.urls import url
from django.contrib.auth.models import User
from django.forms import ValidationError
from django.http import Http404, HttpResponse, HttpResponseNotFound
from django.urls import reverse
from django.utils.translation import u... |
the-stack_0_7178 | from shared import readAssets
def doExtract(args):
print("Larkstongue v0.0.1-alpha")
def readGfx():
readLine = line.strip("\n")
if len(readLine) > 0:
areaGfx.append(readLine)
def readGff():
readLine = line.strip("\n")
if len(readLine) > 0:
... |
the-stack_0_7179 | import logging
import pandas as pd
from bots import imps
from openbb_terminal.decorators import log_start_end
from openbb_terminal.economy import wsj_model
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
def futures_coms_command():
"""Futures and commodities overview [Wall St. Journal]"""
... |
the-stack_0_7180 | """Support for Tasmota lights."""
from hatasmota.light import (
LIGHT_TYPE_COLDWARM,
LIGHT_TYPE_NONE,
LIGHT_TYPE_RGB,
LIGHT_TYPE_RGBCW,
LIGHT_TYPE_RGBW,
)
from homeassistant.components import light
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_EFFEC... |
the-stack_0_7181 | #!/usr/bin/env python
# This is a helper used by `update-pdfjs` to update the Mustache template for
# serving PDFs with PDFJS with the local dev server.
import os
import sys
# Header to insert at the top of the generated PDF.js viewer template
FILE_HEADER = """
<!-- AUTO-GENERATED BY {}. DO NOT EDIT. -->
""".format(... |
the-stack_0_7182 | """ Simple Python class to access the JLR Remote Car API
https://github.com/ardevd/jlrpy
"""
from urllib.request import Request, build_opener
import json
import datetime
import calendar
import uuid
import time
class Connection(object):
"""Connection to the JLR Remote Car API"""
def __init__(self,
... |
the-stack_0_7183 | # coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
the-stack_0_7184 | # Copyright (c) 2013 Tencent Inc.
# All rights reserved.
#
# Author: LI Yi <sincereli@tencent.com>
# Created: September 27, 2013
"""
This module defines cu_library, cu_binary and cu_test rules
for cuda development.
"""
from __future__ import absolute_import
import os
from blade import build_manager
from blade i... |
the-stack_0_7186 | # Working test of textblob
# https://www.geeksforgeeks.org/spelling-checker-in-python/
from textblob import TextBlob
message = "Hello confsion houes"
print("entered: "+str(message))
corrected = TextBlob(message)
# prints the corrected spelling
print("corrected: "+str(corrected.correct()))
|
the-stack_0_7187 | import argparse
import os
import random
import shutil
import time
import warnings
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.dat... |
the-stack_0_7188 | #!/usr/bin/env python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... |
the-stack_0_7189 | # Copyright 2018 The Exoplanet ML 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 t... |
the-stack_0_7191 | # 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.
from fairseq_mod.data.encoders import register_tokenizer
@register_tokenizer('moses')
class MosesTokenizer(object):
@staticmethod
d... |
the-stack_0_7193 | """
Default exit plugin
"""
import shutil
import logging
import os
class ExitPlugin(object):
""" Removes temporary files and exits the program """
def __init__(self, skye):
self.skye = skye
def close_program(self):
""" Closes the program """
self.skye.speak("Goodbye")
... |
the-stack_0_7194 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
from seq2seq.models.decoder import Classifier
class Stage3(torch.nn.Module):
def __init__(self):
super(Stage3, self).__init__()
self.layer5 = torch.nn.LSTM(2048, 1024)
self.layer8 = Classifier(1... |
the-stack_0_7196 | #chainer good bc of ACER
#https://github.com/chainer/chainerrl
import numpy as np
import gym
import h4rm0ny
import chainer
import chainer.functions as F
import chainer.links as L
import chainerrl
from chainerrl.action_value import DiscreteActionValue
from chainerrl import links
from chainerrl.agents import acer
fro... |
the-stack_0_7198 |
import logging, itertools, os
from datetime import date
import astropy.io.ascii as at
import matplotlib.pyplot as plt
from k2spin.config import *
from k2spin import plot
today = date.today().isoformat()
def plot_list(results_list):
"""
"""
res = at.read(base_path+"tables/"+results_list)
f = open("... |
the-stack_0_7200 | # -*- coding: utf-8 -*-
import pickle
from os import path
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
comment = []
with open('quan.txt', mode = 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
arr = line.split(',')
if len(a... |
the-stack_0_7201 | from setuptools import find_packages, setup
def readme():
with open("README.md") as f:
return f.read()
# read version file
exec(open("alibi_detect/version.py").read())
extras_require = {"examples": ["seaborn>=0.9.0", "tqdm>=4.28.1", "nlp>=0.3.0"],
"prophet": ["fbprophet>=0.5, <0.7", "... |
the-stack_0_7202 | from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as np
import cv2
import os
prototxtPath = os.path.sep.join(["Res10Face_Detector", "deploy.prototxt"])
weightsPath = os.path.s... |
the-stack_0_7203 | import sys
import numpy as np
def coadd_cameras(flux_cam, wave_cam, ivar_cam, mask_cam=None):
"""Adds spectra from the three cameras as long as they have the same number of wavelength bins.
This is not a replacement for desispec.coaddition.coadd_cameras,
but a simpler (versatile and faster) implementatio... |
the-stack_0_7204 | #!/usr/bin/env python3
"""Make rhyming words"""
import argparse
import re
import string
# --------------------------------------------------
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Make rhyming "words"',
formatter_class=argparse.Argumen... |
the-stack_0_7205 | from sys import argv
from Bio import SeqIO, Seq, AlignIO
import pandas as pd
# user input:
aligned_fasta_path = argv[1]
outfile_path = argv[2]
regions_table_path = argv[3] # tables of regions of the genome, to determine translation reading frame in translation.
excel_mutations_table_path = argv[4] # TODO: pipeline -... |
the-stack_0_7206 | # -*- coding: utf-8 -*-
import pandas as pd
import os
file_path = os.path.dirname(os.path.realpath(__file__))
# File uploads - Extended Data Figure 5
other = pd.read_excel(file_path + "/../../data/other_category.xlsx")
# Plot colors
c = ['#725843', '#9f7f65', '#7c7b78', '#bbbbbb', '#90b493']
... |
the-stack_0_7208 | import math
'''
isReceiving returns true if a transaction was a return
Integer transactionAmount
'''
def isReceiving(transactionAmount):
if transactionAmount == 0:
return None # should not happen
else:
return transactionAmount > 0
'''
isPaying returns true is a transaction was a payment
Integer tr... |
the-stack_0_7209 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from h._compat import xrange
from unittest.mock import Mock
import datetime
import pytest
from h.activity import bucketing
from tests.common import factories
UTCNOW = datetime.datetime(year=1970, month=2, day=21, hour=19, minute=30)
FIVE_MINS_AGO = ... |
the-stack_0_7210 | from django import forms
class SearchForm(forms.Form):
CHOICES = [
(u'ISBN', u'ISBN'),
(u'书名', u'书名'),
(u'作者', u'作者')
]
search_by = forms.ChoiceField(
label='',
choices=CHOICES,
widget=forms.RadioSelect(),
ini... |
the-stack_0_7212 | """
(C) IBM Corporation 2021
Description:
Creates new config files within the default config file dir.
Uses both user input and authentification file for auth informations.
Repository:
https://github.com/IBM/spectrum-protect-sppmon
Author:
Niels Korschinsky
"""
import argparse
import json
import logging... |
the-stack_0_7213 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016, Anaconda, Inc. All rights reserved.
#
# Licensed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------... |
the-stack_0_7214 | # clone
import os
import repo
# フォルダを削除
def rmtree(top):
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
filename = os.path.join(root, name)
os.chmod(filename, 0o777)
os.remove(filename)
for name in dirs:
os.rmdir(os.path.jo... |
the-stack_0_7215 | from django.contrib import admin
from blogs.models import Post, Category_post, Comment
from django_summernote.admin import SummernoteModelAdmin
# Register your models here.
class PostAdmin(SummernoteModelAdmin):
summernote_fields = ('content',)
list_display = ('title', 'slug', 'short_desciption', 'status','crea... |
the-stack_0_7216 | from scipy.spatial import ConvexHull, Delaunay
import numpy as np
class WeightedDelaunay:
def __init__(self, points, weights):
self.points = points
self.weights = weights
self.complete = False
self.tri = None
def triangulation(self):
if not self.complete:
n... |
the-stack_0_7218 | # coding=utf-8
import tensorflow as tf
import tensorflow_compression as tfc
import os
import sys
import math
import numpy as np
# tf.enable_eager_execution()
from collections import namedtuple
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = '/home/wenxuanzheng/pc_compression/pc_compression'... |
the-stack_0_7221 | # -*- coding: utf-8 -*-
#
# Dataverse Documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 16 09:34:18 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
# autogenerated file.
#
#... |
the-stack_0_7222 | #!/usr/bin/env python
#
# Copyright 2014 Facebook
#
# 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_0_7223 | import os
import paddle
import math
from paddle.optimizer.optimizer import Optimizer
from collections import defaultdict
from paddle.fluid import core
from paddle.fluid import framework
from paddle.fluid.framework import Variable
from paddle.fluid import layers
from paddle.fluid import unique_name
from paddle.fluid.fra... |
the-stack_0_7225 | from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score, balanced_accuracy_score
def get_commonscores(y_true, y_pred):
"""
Calculate the precision, recall, f1, accuracy, balanced_accuracy scores
Args:
y_true (pd.Series): y_true (with limited set of index)
y_pred... |
the-stack_0_7228 | from opytimizer.spaces import HyperComplexSpace
# Defines the number of agents, decision variables,
# and search space dimensions
n_agents = 2
n_variables = 5
n_dimensions = 4
# Creates the HyperComplexSpace
s = HyperComplexSpace(n_agents=n_agents, n_variables=n_variables, n_dimensions=n_dimensions)
# Prints out som... |
the-stack_0_7229 | #!/usr/bin/env python2
from Tkinter import *
import Tkinter as tk
import ttk
import tkFileDialog
import tkMessageBox
from tkFileDialog import askdirectory
import six
from pkg_resources import resource_stream
import os
from os import listdir
from os.path import isfile, join
from os import walk
from subprocess import Po... |
the-stack_0_7230 | import random
import httpx
from utils.log import logger
'''
api返回格式为
字段名 数据类型 说明
pid int 作品 pid
p int 作品所在页
uid int 作者 uid
title string 作品标题
author string 作者名(入库时,并过滤掉 @ 及其后内容)
r18 boolean 是否 R18(在库中的分类,不等同于作品本身的 R18 标识)
width int 原图宽度 px
height int 原图高度 px
tags string[] 作品标签,包含标签的中文翻译(有的话)
ext string 图片扩展名
uploadDa... |
the-stack_0_7231 | import random
import string
from django.db import transaction
from django.db.models import fields
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from vbb_backend.users.models import Teacher, User, UserTypeEnum
def random_char(y):
return "".join(random.choice(string.... |
the-stack_0_7232 | import math, logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from ..tokenization import WordTokenizer
class GRUEncoder(nn.Module):
def __init__(self,
token2id,
max_length=128,
hidden_size=230,
... |
the-stack_0_7233 | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import datetime
import faulthandler
import logging
import os
import signal
import sys
import threading
import traceback
from contextlib import contextmanager
from typing import Callable, I... |
the-stack_0_7234 | import pytest
from world.layer import Layer
from data import TileType
@pytest.fixture(name="tilemap")
def _tilemap(origin, a, b):
layer = Layer()
layer[origin] = TileType.GROUND
layer[a] = TileType.SPACE
layer[b] = TileType.WATER
return layer
def test_serializable(tilemap, origin, a, b):
d... |
the-stack_0_7236 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import time
import urlparse
from telemetry.core import exceptions
from telemetry.internal.actions.drag import DragAction
from telemetry.inter... |
the-stack_0_7237 | import hassapi as hass # pylint: disable=import-error
class cover_tag_scanned(hass.Hass):
""" Opens or closes a cover based on an nfc_tag being scanned """
def initialize(self):
self.listen_event(
self.door_tag_scanned,
"tag_scanned",
tag_id=self.args["tag_id"],
... |
the-stack_0_7238 | import json
import time
class Vehicle:
ip = None
brand = None
model = None
vrn = None
rotates = None
gear = None
direction = None
directionAsText = None
speed = None
action = None
actionAsText = None
_lastUpdateAt = None
def update(self, ip, brand, mo... |
the-stack_0_7240 | #############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFT... |
the-stack_0_7241 | # -*- coding: utf-8 -*-
"""Defining functions and classes for arrhythmia detection through ECG signals.
The contents of this module define functions and classes for analyzing,
visualizing, and making predictions based on data from the
MIT-BIH Arrhythmia Database.
Explore this repository at:
https://github.com/cha... |
the-stack_0_7242 | import json
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST
from requests import RequestException
from rootnroll import RootnRollClient
from rootnroll.constants import ServerStatus
from games.mod... |
the-stack_0_7243 | import random
import numpy as np
#import matplotlib.pyplot as plt
# parameters
N = 100 # No. of training points
D = 2 # 2-dimension
# area between f & g
area = 0
cnt0 = 0
for irun in range(1000):
# training data
x1, x2 = np.zeros((N, 1)), np.zeros((N, 1))
for iN in range(N):
x1[iN] = random.uniform(-1, 1)
... |
the-stack_0_7244 | # -*- coding: utf-8 -*-
# Copyright 2020 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... |
the-stack_0_7245 | #!/bin/python3
import os
import sys
from subprocess import call, run, PIPE
from getFiles import get_files, get_main
from colorama import Fore, Style
answ_linestart = 'Answer: '
def compile_java(task, output_path='.', source_path=''):
cmd = ['javac', '-d', output_path]
cmd.extend(get_files(task, source_path))... |
the-stack_0_7247 | # Copyright 2021 Alexey Tochin
#
# 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_0_7248 | # pylint: disable=g-bad-file-header
# Copyright 2020 DeepMind Technologies Limited. 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/... |
the-stack_0_7249 | import torch
import torch.nn as nn
def dice_loss(input, target):
input = torch.sigmoid(input)
smooth = 1e-5
iflat = input.view(-1)
tflat = target.view(-1)
intersection = (iflat * tflat).sum()
return 1 - ((2. * intersection + smooth) /
(iflat.sum() + tflat.sum() + smooth))
def focal_loss(... |
the-stack_0_7250 | # Princeton University licenses this file to You 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 writin... |
the-stack_0_7251 | # -*- coding: utf8 -*-
import sys
import os
import unittest
import platform
from pygame.tests.test_utils import example_path, AssertRaisesRegexMixin
import pygame
from pygame import mixer
from pygame.compat import unicode_, as_bytes, bytes_
IS_PYPY = "PyPy" == platform.python_implementation()
####################... |
the-stack_0_7252 | # coding=utf-8
__author__ = 'lxn3032'
import os
import requests
import time
import warnings
import threading
import atexit
from airtest.core.api import connect_device, device as current_device
from airtest.core.android.ime import YosemiteIme
from hrpc.client import RpcClient
from hrpc.transport.http import HttpTran... |
the-stack_0_7253 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Copyright (c) 2017-2020 The Raven Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the RBF code."""
from test_framework.test_fr... |
the-stack_0_7254 | """Setup script for shreddit.
"""
from setuptools import setup
from codecs import open
from os import path
VERSION = "6.1.0"
DESCRIPTION = " Remove your comment history on Reddit as deleting an account does not do so."
here = path.abspath(path.dirname(__file__))
with open(path.join(here, "README.md"), encoding='utf-... |
the-stack_0_7256 | import json
import math
import os.path
from src.cleaning.clean_drinks_4 import main as clean_drinks
from pathlib import Path
# clean_json_5.py
def main():
print("Cleaning json from cleaned Drink Data")
if not os.path.isfile(Path("../Savefiles/drinks_C2.txt")):
print("Cleaned Drinks Savefiles not found... |
the-stack_0_7259 | import io
from setuptools import setup
NAME = 'plex-lastfm-scrobbler'
VERSION = '4.1.1'
description = 'Scrobble audio tracks played via Plex Media Center'
try:
with io.open('README.rst', encoding="utf-8") as fh:
long_description = fh.read()
except IOError:
long_description = description
setup(
... |
the-stack_0_7260 | '''
MIT License
Copyright (c) 2021 Chen Guojun
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, d... |
the-stack_0_7261 | import numpy as np
import matplotlib.pyplot as plt
# set width of bar
barWidth = 0.25
# fig = plt.subplots(figsize =(12, 8))
# set height of bar
PDR=[0.633136094675,0.7,0.846153846154,0.990990990991,0.021822849807445]
Filter=[0.723032069970845,0.71,0.88,0.976909413854352,0.217672413793103]
# Set position of... |
the-stack_0_7263 | #!/usr/bin/env python3
import os
import random # Discuss: random module
import sys
# Constants
# Discuss: set data structure
NSFW = {'bong', 'sodomized', 'kiss', 'head-in', 'telebears'}
# Main Execution
def main():
characters = []... |
the-stack_0_7266 | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import numpy as np
from coremltools.converters.mil.mil import types
from coremltools.converters.mil.m... |
the-stack_0_7267 | import sqlite3
from abc import abstractmethod
from ipaddress import IPv4Address
from ipaddress import IPv6Address as IPv6AddressPython
from typing import (Callable, FrozenSet, Generic, Optional, Set, Sized,
TypeVar, Union)
from .blockchain import Miner, Node, Version
from .db import Cursor, Databas... |
the-stack_0_7268 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
import numpy as np
from scipy.constants import mu_0, pi, epsilon_0
from scipy.special import erf
from SimPEG import Utils
def Qfun(R, L, f, alpha=None):
if alpha is ... |
the-stack_0_7269 | import inspect
class ProblemSizeCounter:
def __init__ (self, J, F, L, M, P):
self._initNumberOfVariables(J, F, L, M, P)
self._initNumberOfConstraints(J, F, L, M, P)
def _initNumberOfVariables(self, J, F, L, M, P):
self.numberOfVariablesX = P * L * F
self.numberOfVariablesY = ... |
the-stack_0_7271 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class JeuxVideoIE(InfoExtractor):
_VALID_URL = r'https?://.*?\.jeuxvideo\.com/.*/(.*?)\.htm'
_TESTS = [{
'url': 'http://www.jeuxvideo.com/reportages-videos-jeux/0004/00046170/tearaway-playstation-vi... |
the-stack_0_7272 | class ConfigStruct(object):
def __init__(self):
# Location of the star catalog
self.CAL_DIR = '../data/'
self.CAL_NAME = 'gaia_dr2_mag_11.5.npy'
# Location of the MPC data
self.OURS_DIR = '../data/'
self.OURS_NAME = 'mpc_data.txt'
# Location of finder data
self.FINDER_DIR = '../data/'
self.FINDE... |
the-stack_0_7275 | import secrets
def _get_header(token):
return f'''
rule encoding_geary_{token}:'''
def _get_benchmark(benchmark_out):
return f'''
benchmark:
"{benchmark_out}"'''
def _get_main(fasta_in, classes_in, length_in, geary_out):
return f'''
input:
fasta_in="{fasta_in}",
class... |
the-stack_0_7276 | from copy import deepcopy
import setpath
import vtbase
import functions
import heapq
### Classic stream iterator
registered=True
class StreamIntersect(vtbase.VT):
def BestIndex(self, constraints, orderbys):
return (None, 0, None, True, 1000)
def VTiter(self, *parsedArgs,**envars):
largs, dict... |
the-stack_0_7279 | from sympy import (
Rational, Symbol, N, I, Abs, sqrt, exp, Float, sin,
cos, symbols)
from sympy.matrices import eye, Matrix
from sympy.matrices.matrices import MatrixEigen
from sympy.matrices.common import _MinimalMatrix, _CastableMatrix
from sympy.core.singleton import S
from sympy.testing.pytest import raise... |
the-stack_0_7280 | #!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
from __future__ import print_function, absolute_import
import os
import glob
import sys
import platform
import subprocess
impo... |
the-stack_0_7282 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 3 14:11:25 2017
@author: juan
"""
#This program implements the clamped cubic spline with zero derivative at the
#endpoints
import numpy as np
def deltaGrid(grid):
deltas = ()
for i in range(1, len(grid)):
deltas += (grid[i] - gr... |
the-stack_0_7284 | # Copyright 2021 Dakewe Biotech Corporation. 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... |
the-stack_0_7285 | # qubit number=4
# total number=33
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += CNOT(0,3) # number=10
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.