content stringlengths 5 1.05M |
|---|
import json
import pandas as pd
from os import path
import pickle
from collections import defaultdict
def load_json(file):
with open(file, "r") as f:
output = json.load(f)
return output
def load_pickle(file):
with open(file, "rb") as f:
output = pickle.load(f)
return output
class T... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
class Nudity:
def __init__(self):
base_path = os.path.dirname(os.path.abspath(__file__))
model... |
from . import question
from flask import jsonify, request
import json
import pymongo
from bson import BSON, json_util
dept_data = [
{
'name': '部门1',
'id': 12345
},
{
'name': '部门2',
'id': 12346
}
]
MONGO_URI = 'localhost'
MONGO_DATABASE = 'zhihu'
client = pymongo.MongoC... |
# /usr/bin/env python
# -*- coding: utf-8 -*-
from loguru import logger
import pytest
import os.path as op
import discon
import discon.discon_tools
path_to_script = op.dirname(op.abspath(__file__))
def test_noarch_from_text():
assert discon.discon_tools.check_meta_yaml_for_noarch(None, "adfadf\n noarch: pytho... |
import os
from collections import namedtuple
from box import Box
import yaml
from termcolor import colored
from cerberus import Validator
from sgains.configuration.schema import sgains_schema
def _dict_to_namedtuple(input_dict, dict_name="root"):
CONFIG_TUPLE = namedtuple(dict_name, input_dict.keys())
for... |
import html
from pprint import pprint
from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils import translation
from django.utils.translation import gettext_lazy as _
from allauth.account.utils import send_email_confirmation
from n... |
from json import JSONDecodeError
from django.http import JsonResponse
from requests.exceptions import InvalidSchema
from rest_framework import viewsets, status
from rest_framework.response import Response
from opendp_apps.dataverses.dataverse_client import DataverseClient
from opendp_apps.dataverses.dv_user_handler ... |
#!/usr/bin/python
from distsys.services import services
s = services() |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# vim:ts=4:sw=4:expandtab
import pygame
import pprint
from cb import *
from timer import *
from textobj import *
from wiimote import *
from questions import *
from view_question import *
from pygame.locals import *
STATE_IDLE = 0
STATE_PLAYER1 = 1
STATE_PLAYER2 = 2
STATE_P... |
import plotly.graph_objects as go
import plotly
import sys
import common
import table_single_provers
import figure_createall
def plot(prover_dict):
systems = ["D","T","S4","S5"]
quants = ["const","cumul","vary"]
configurations = [(a,b) for a in systems for b in quants]
fig = plotly.subplots.make_subpl... |
#!/usr/bin/python3
# This will prompt for the desktop type and launch the desktop of your choice in the TTY
from os import ttyname, listdir, system
from sys import stdout, stdin
from re import search
from io import open
from subprocess import getstatusoutput
# Make sure requirements are meet
# Have sx installed
if g... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import glob
import os
import re
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Get new version.
with open(os.path.join(root, "pyro", "__init__.py")) as f:
for line in f:
if line.startswith("version_p... |
import tensorflow as tf
import sys
sys.path.append("../tf")
from backend.op import conv_bn, conv_dw, basic_rfb, separable_conv
def basic_conv(x, out_ch, kernel_size, stride=(1, 1), padding=0, dilation=1, relu=True,
bn=True, prefix='basic_conv'):
if 0 < padding:
out = tf.keras.layers.ZeroPad... |
#!/usr/bin/env python
import hail
from hail.expr import TStruct
from pprint import pprint
def flatten_struct(struct, root='', leaf_only=True):
result = {}
for f in struct.fields:
path = '%s.%s' % (root, f.name)
if isinstance(f.typ, TStruct):
result.update(flatten_struct(f.typ, path... |
from itertools import groupby
from pprint import pformat
def name_stack_repr(name_stack):
segments = []
for name, group in groupby(name_stack):
group_len = len([*group])
segments.append(group_len > 1 and f"{name}x{group_len}" or name)
return segments[::-1]
class CellDSLError(Exception):
... |
import unittest
import pso
class initPopulationTest(unittest.TestCase):
def test_initializePopulation(self):
pop = pso.initPopulation(10, {})
self.assertTrue(len(pop) == 10)
if __name__ == "__main__":
unittest.main() |
#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2015, Fabian Girrbach, Social Robotics Lab, University of Freiburg
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions ar... |
from __future__ import print_function
# bustersAgents.py
# ----------------
from builtins import str
from builtins import range
from builtins import object
import util
from game import Agent
from game import Directions
from keyboardAgents import KeyboardAgent
import inference
import busters
class NullGraphics(object)... |
import FWCore.ParameterSet.Config as cms
hltPhase2L3MuonPSetPvClusterComparerForIT = cms.PSet(
track_chi2_max = cms.double(20.0),
track_prob_min = cms.double(-1.0),
track_pt_max = cms.double(100.0),
track_pt_min = cms.double(1.0)
)
|
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import hubitatmaker as hm
def test_normal_lock_codes(mocker) -> None:
hub = mocker.MagicMock()
device = mocker.MagicMock()
device.attributes = {
hm.ATTR_LOCK_CODES: hm.Attribute(
{
"name": hm.ATTR_LOCK_CODES,
"currentValue": '{"1":{"name":"Test","code":"... |
# encoding: utf-8
from tkinter.messagebox import askquestion
import logging_helper
from uiutil.window.dynamic import DynamicRootWindow
from configurationutil import Configuration, cfg_params
from uiutil._metadata import __version__, __authorshort__, __module_name__
from uiutil.resources import templates
from uiutil.f... |
class Node:
def __init__(self, element):
self.item = element
self.next_link = None
class StackLL:
def __init__(self):
self.head = None
def is_empty(self):
if self.head is None:
print("Error! The list is empty!")
return True
else:
... |
import json
from collections import defaultdict
from datetime import datetime
from pathlib import Path
import click
from cumulusci.core.exceptions import FlowNotFoundError
from cumulusci.core.utils import format_duration
from cumulusci.utils import document_flow, flow_ref_title_and_intro
from cumulusci.utils.yaml.saf... |
import unittest
import unittest.mock
import edifice._component as component
import edifice.engine as engine
import edifice.base_components as base_components
from edifice.qt import QT_VERSION
if QT_VERSION == "PyQt5":
from PyQt5 import QtWidgets
else:
from PySide2 import QtWidgets
if QtWidgets.QApplication.in... |
# Generated by Django 3.0.6 on 2021-02-20 09:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('security', '0012_auto_20210202_1002'),
]
operations = [
migrations.CreateModel(
name='CveList',
fields=[
... |
# Django
from django.contrib import admin
# Register your models here.
from .models import NewCommunity, JoinUser
admin.site.register(NewCommunity)
admin.site.register(JoinUser)
|
# Copyright 2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# import
## batteries
import os
import sys
import shutil
import tempfile
import pytest
## 3rd party
import pandas as pd
## package
from pyTecanFluent import Fluent
from pyTecanFluent import Map2Robot
from pyTecanFluent import Utils
# data dir
test_dir = os.path.join(os.p... |
import unittest
import torch
from leanai.core.indexed_tensor_helpers import *
class TestIndexedTensorHelpers(unittest.TestCase):
def setUp(self) -> None:
pass
def test_map_per_batch(self):
values = torch.tensor([1, 2, 3, 4, 5])
indices = torch.tensor([0, 0, 1, 1, 2])
def fun(s... |
from abc import ABC, abstractmethod
import os.path
from typing import Iterable, List, NamedTuple, Optional, Tuple
import numpy as np
import tensorflow as tf
from tensorflow.data import Dataset
from clfw.util import save_results
Array = np.ndarray
class Task(NamedTuple):
train: Dataset
valid: Optional[Datas... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ErrorBatch'
db.create_table('djangodblog_errorbatch', (
('status', self.gf... |
import sys
class Queue(object):
"""Abstract class for creating backend-specific queue implementations.
Your implementation should override all private methods and alter any
class attributes (e.g. FIFO) that do not apply to your backend."""
FIFO = True
SUPPORTS_DELAY = True
RECLAIMS_TO_BACK_OF_... |
from strava_client import StravaClient
strava_client = StravaClient()
strava_client.sync(direction="forward")
|
import matplotlib.pyplot as plt
import numpy as np
#import dnpdata
from .dnpData import dnpdata
figure = plt.figure
legend = plt.legend
xlim = plt.xlim
ylim = plt.ylim
gca = plt.gca
dark_green = '#46812B'
light_green = '#67AE3E'
dark_grey = '#4D4D4F'
light_grey = '#A7A9AC'
orange = '#F37021'
plt.rcParams['lines.lin... |
import numpy as np
import ctypes
import click
import logging
import os
import sys
sys.path.append('src/')
from frequentDirections import FrequentDirections
from randomProjections import RandomProjections
from randomSums import RandomSums
from rowSampler import RowSampler
from svdEmbedding import SVDEmbedding
from log... |
#!/usr/bin/env python
import gdb
class SkiplistPrintCommand(gdb.Command):
"""Iterate and print a list.
skip <EXPR> [MAX]
Given a list EXPR, iterate though the list nodes' ->next pointers, printing
each node iterated. We will iterate thorugh MAX list nodes, to prevent
infinite loops with corrupt lists. If MAX is... |
from lib.die import Die
import pygal
''' Vamos cria um histograma que é um gráfico de barras quem mostra a frequência da ocorrência
de determinados resultados. '''
# Cria um D6 e um D10.
die_1 = Die(8) # Cria uma instância de Die passando como argumento oito lados.
die_2 = Die(8) # Cria uma instância de Die passan... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import sys
sys.path.insert(1,"../../../") # allow us to run this standalone
import numpy as np
import h2o
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
fro... |
import atexit
import random
import signal
import sys
from typing import Any, List, Optional
from ape.api import ReceiptAPI, TestProviderAPI, TransactionAPI, UpstreamProvider, Web3Provider
from ape.api.config import ConfigItem
from ape.exceptions import ContractLogicError, OutOfGasError, TransactionError, VirtualMachin... |
import numpy as np
import tensorflow as tf
import torch
tf.compat.v1.enable_eager_execution()
### Model
def check_model():
from run_nerf_helpers import init_nerf_model
model = init_nerf_model(use_viewdirs=True)
print(model.summary())
print("--- Pytorch ---")
from run_nerf_helpers_torch import ... |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2014 the Critic contributors, Opera Software ASA
#
# 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/LI... |
#
# Copyright (C) 2018 The Android Open Source Project
# Copyright (c) 2020 Samsung Electronics Co., Ltd. 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://w... |
import pytest
import pytz
from django import forms
from timezone_field import TimeZoneFormField
@pytest.fixture
def Form():
class _Form(forms.Form):
tz = TimeZoneFormField()
tz_opt = TimeZoneFormField(required=False)
yield _Form
@pytest.fixture
def FormInvalidChoice(invalid_tz):
class ... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import yaml
import os
import webbrowser
from robot.server import HTTPFrontend
from robot.mxnet_robot import MXNetRobot
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost', help='host to listen to')
parser.add... |
import pygame
from Data.scripts.Entity import *
from Data.scripts.Animation import *
from Data.scripts.coreFunctions import *
class Player(entity):
def __init__(self,x,y,startTexture):
super().__init__(x,y,startTexture)
animationList={"Idle":loadAnimationFromFolder("data/res/Player/Idle",frameTi... |
__all__ = [
'AddCellConnToPoints',
'PointsToTube',
'LonLatToUTM',
'RotatePoints',
'ExtractPoints',
'RotationTool',
'ExtractCellCenters',
'AppendCellCenters',
'IterateOverPoints',
'ConvertUnits',
'BuildSurfaceFromPoints',
]
__displayname__ = 'Point/Line Sets'
from datetime i... |
def contributors():
"""
Add your name in the list below, in the same PR as the signed CLA.
If your contribution is sponsored by an organization, you can also add the following entry:
"organization=[YOUR ORG]".
"""
return {
"1": ["name=Mihai Bojin", "email=mihai.bojin@gmail.com"],
}... |
#-*-coding:utf-8-*-
"""
@FileName:
base_communication.py
@Description:
base communication class for behavior-driven simulation
@Authors:
Hanbo Sun(sun-hb17@mails.tsinghua.edu.cn)
@CreateTime:
2022/05/07 17:38
"""
from mnsim_noc.utils.component import Component
from mnsim_noc.Tile import BaseTile
from mn... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
""" Calculation OBO score
This module calculate obo score and rank.
Return score ranking as below.
"""
class Calculation(object):
def __init__(self, contest_no):
self.contest_no = contest_no
def calculate(self, scores):
s = {}
tec = ... |
from django import template
from ..models import Category
from django.template import RequestContext
register = template.Library()
@register.inclusion_tag("inc/category_navbar.html", takes_context=True)
def category_navbar(context):
request = context['request']
return {
"categories": Category.objects.... |
from random import random
class LogicBase:
def __init__(self, pop):
self.pop = pop
@property
def can_work(self):
return True
def has_good(self, good, amount):
"Returns True if the Pop has a particular Good in their inventory"
inv = self.pop.inventory.get(good)
... |
from gym_snake.envs.constants import GridType
from gym_snake.envs.snake_env import SnakeEnv
class Snake_4x4_DeadApple(SnakeEnv):
def __init__(self):
super().__init__(grid_size=4, initial_snake_size=2, done_apple=True)
class Snake_8x8_DeadApple(SnakeEnv):
def __init__(self):
super().__init__(g... |
from colossalai.nn.optimizer import HybridAdam
from colossalai.zero.shard_utils import (BucketTensorShardStrategy,
TensorShardStrategy)
from model import GPT2_small_pipeline_hybrid
BATCH_SIZE = 8
NUM_EPOCHS = 60
SEQ_LEN = 1024
NUM_MICRO_BATCHES = 4
HIDDEN_SIZE = 768
TENSOR_SHAP... |
from .. import BaseTest
from sentry import app
from sentry.client import ClientProxy
from sentry.client.logging import LoggingSentryClient
class ClientTest(BaseTest):
def test_client_proxy(self):
proxy = ClientProxy(app)
app.config['CLIENT'] = 'sentry.client.logging.LoggingSentryClient'
... |
"""Реализация базовых команд для асинхронного запроса к базе
данных Postgres через Django ORM.
"""
import os
import sys
from pathlib import Path
from typing import List, Optional, Union
from asgiref.sync import sync_to_async
ROOT_DIR = Path(__file__).parents[3]
MODEL_PATH = os.path.join(ROOT_DIR, "django_project")
s... |
class Animal:
def __init__(self):
print("================= Animal ctor")
def eat(self):
print("Animal eat meat")
class Cat(Animal):
def __init__(self):
#######################################
# Third __init__ method to call base eat.
# It is a preferred way to us... |
import os
import hashlib
import functools
from wpull.database.sqltable import SQLiteURLTable
from wpull.document.html import HTMLReader
from wpull.processor.rule import ProcessingRule
from libgrabsite import dupespotter
from libgrabsite.dupes import DupesOnDisk
def response_body_size(response) -> int:
try:
retur... |
import numpy as np
# import os
from PIL import Image
import matplotlib.pyplot as plt
import sklearn.metrics as sm
import csv
def compute_precision_recall(score_A_np):
array_5 = np.where(score_A_np[:, 1] == 5.0)
array_7 = np.where(score_A_np[:, 1] == 7.0)
print("len(array_5), ", len(array_5))
print("le... |
"""
Description: pytests for transform.py
"""
from pathlib import Path
import fiona
import geopandas as gpd
import pytest
from geotrans import transform
from geotrans.transform import (
FILEGEODATABASE_DRIVER,
GEOPACKAGE_DRIVER,
SHAPEFILE_DRIVER,
)
from tests import Helpers
def test_check_file():
""... |
# Generated by Django 3.2.5 on 2021-07-10 08:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('budget', '0001_initial'),
migrations.swappable_dependency(setti... |
from user.common import constants as const
class UserException(Exception):
user_default_status_code = const.DEFAULT_STATUS_CODE
def __init__(self, message, status_code=None):
Exception.__init__(self)
if status_code is None:
status_code = self.user_default_status_code
self.m... |
#!/usr/bin/env python
# Skupina C
class Zviratko:
def __init__(self, jmeno, vek, vaha):
self.jmeno = jmeno
self.vek = vek
self.vaha = vaha
self.cisloChlivku = None
def __str__(self):
return "Jsem {}, mám {} roky a vážím {} kg.".format(self.jmeno, self.vek, self.vaha)
... |
import re
def replace_colons(text: str, strip: bool=False) -> str:
"""Parses a string with colon encoded emoji and renders found emoji.
Unknown emoji are left as is unless `strip` is set to `True`
:param text: String of text to parse and replace
:param strip: Whether to strip unknown codes or to leav... |
class CalculatedDay:
"""Base class for calculated days
@actualDate - date of the day
@weekday - name of the day
@availableHours - number of hours available for occupation
@occupiedHours - number of hours occupied
@availableLecturers - dictionary of lecturers available this day with possible "p... |
#!/usr/bin/env python
import os
import re
import subprocess
import sys
EDIT_FILE = '/tmp/todo.txt'
# EDITOR = os.environ.get('EDITOR','vim')
EDITOR = 'vim'
query = " | ".join(sys.argv[1:])
# execute taskmaster task
def exec_task(ids, *cmd):
args = ["tm", "tk"] + list(cmd) + ids
print(args)
sp = subproce... |
from functools import wraps
from typing import Any, Callable
import torch
import torch.nn as nn
from torch import Tensor
from .quant_functions import Round_STE, IntervalQuantizeIntO, IntervalQuantize
round_STE = Round_STE.apply
interval_quantize_int_o = IntervalQuantizeIntO.apply
interval_quantize = IntervalQuantize.... |
magos = ["Dynamo", "Enmascarado", "Chris Angel", "Mago De Oz"]
def show_magicians(lista):
for mago in lista:
print(mago)
print("\n")
show_magicians(magos)
def make_great(lista):
for mago in lista:
presentacion = "The Great " + mago.title()
print(presentacion)
print("\n")
ma... |
#!/usr/bin/env python
import rospy
import roslib
from fiducial_msgs.msg import FiducialTransformArray
import tf
from tf import transformations as t
import numpy as np
import numpy.matlib as npm
import tf2_ros
import geometry_msgs.msg
# https://answers.ros.org/question/322317/combine-two-parent-child-transformations-f... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
sys.path.insert(0, '.')
import argparse
from PIL import Image
import matplotlib.pyplot as plt
# utils
from utils.inference import inference
def main(args):
i2t_results, t2i_results = inference(args.cfg_file, args.checkpoint_dir)
if args.que... |
'''
https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/
562. Longest Line of Consecutive One in Matrix
Given an m x n binary matrix mat, return the length of the longest line of consecutive one in the matrix.
The line could be horizontal, vertical, diagonal, or anti-diagonal.
'''... |
import de_core_news_sm
#import de_core_news_md
import networkx as nx
import matplotlib.pyplot as plt
text1 = u'''Wie gehe ich mit einem Demenzkranken bei Tod der Mutter um?'''
text2 = u'''Ausnutzung der Demenz zur finanziellen Bereicherung'''
text3 = u'''Wie könnte ich anders auf die immer gleiche Frage reagieren?''... |
import argparse
import ROOT
from simplot.rootplot import drawtools, rootio, drawoptions, style
###############################################################################
_out = rootio.CanvasWriter("plots")
###############################################################################
# def loadgenie():
# ... |
datalake_attribute_descriptions = {
"total": {
"description": "{metric}__!{source}",
"notes": "{notes}"
},
"by_post": {
"description": "{metric}__{source}__!{post_id}",
"notes": "{notes} post id: {post_id}"
}
}
datalake_attributes = {
"fan_count": {
"dimensions": {
... |
#Practical 31: Patterns in python
def triangle(_depth, _type):
k = 2 * _depth - 2
for i in range(0, _depth):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print(_type, end=" ")
print("\r")
def righ... |
import sbol3
# ----------------------------------------------------------------------
# COMBINE 2020 SBOL 3 Tutorial
# October, 2020
#
# This tutorial code goes with the slides at:
#
# https://github.com/SynBioDex/Community-Media/blob/master/2020/COMBINE20/SBOL3-COMBINE-2020.pptx
# ------------------------------------... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2022- John Muradeli
#
# Distributed under the terms of the MIT License
# (see wavespin/__init__.py for details)
# -----------------------------------------------------------------------------
"""Conve... |
"""
Neuronal Network of C. Elegans implemented in Python with the LIF-Model
(by JW)
New Circuit Edition (SIM-CE)
Version: I don't know - Still in work!
"""
# Some dependencies
import numpy as np
import matplotlib.pyplot as plt
import gym
from lif import I_syn_calc, I_gap_calc, U_neuron_calc
"""
Parameters for the ... |
from allauth.account.app_settings import EMAIL_CONFIRMATION_EXPIRE_DAYS
from allauth.account.models import EmailAddress
from django.core import signing
from django.conf import settings
from django.shortcuts import redirect
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import common_pb2 as common__pb2
import functional_api_pb2 as functional__api__pb2
class FunctionalServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Construct... |
from datetime import datetime
from typing import List
import requests
from .constants import GAME_TYPES
from .exceptions import (
APIException,
ClientException,
GameNotFoundException,
LoginError,
PaymentRequiredException,
PlayerNotFoundException,
TooManyRequestsException,
TeamNotFoundE... |
import os.path as osp
import numpy as np
import mmcv
from viseval import eval_det
from .custom import CustomDataset
from .builder import DATASETS
@DATASETS.register_module()
class VisDroneDataset(CustomDataset):
CLASSES = ('pedestrian', 'person', 'bicycle', 'car', 'van',
'truck', 'tricycle', 'aw... |
TP = True
FP = False
class Records:
"""Save prediction records during update.
Attributes:
iou_threshold (float): iou threshold
pred_infos (list): save the results (TP/FP)
Args:
iou_threshold (float): iou threshold (default: 0.5)
"""
def __init__(self, iou_threshold=0.5):
... |
"""
Exceptions for the DB API 2.0 implementation.
"""
__all__ = [
"Warning",
"Error",
"InterfaceError",
"DatabaseError",
"DataError",
"OperationalError",
"IntegrityError",
"InternalError",
"ProgrammingError",
"NotSupportedError",
]
class Warning(Exception): # pylint: disable=... |
from pysubs2 import SSAStyle
from pysubs2.substation import parse_tags
def test_no_tags():
text = "Hello, world!"
assert parse_tags(text) == [(text, SSAStyle())]
def test_i_tag():
text = "Hello, {\\i1}world{\\i0}!"
assert parse_tags(text) == [("Hello, ", SSAStyle()),
("... |
import json
from flask import request
from functools import wraps
from jose import jwt
from urllib.request import urlopen
AUTH0_DOMAIN = "mothership-v2.us.auth0.com"
ALGORITHMS = ["RS256"]
class AuthError(Exception):
"""AuthError Exception
A standardized way to communicate auth failure modes
"""
de... |
import unittest
from application.calculators.tcid50.tcid50_calculator import TCID50Calculator
from application.models.tcid50.dilution import Dilution
from application.models.tcid50.tcid50_input_data_set import TCID50InputDataSet
from application.models.tcid50.tcid50_calculated_data_set import TCID50CalculatedDataSet
f... |
from miRNASNP3 import app as application
|
# https://leetcode.com/problems/range-sum-query-2d-immutable
from typing import List
from itertools import accumulate
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
self.R = len(matrix)
self.C = len(matrix[0])
self.sum_matrix = []
for r in range(self.R):
... |
from __future__ import absolute_import
from .mf_main import mf_main
from ._version import __version__
|
# Copyright 2017 Mabry Cervin and all contributers listed in 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... |
import argparse
import os
from tqdm import tqdm
import numpy as np
import torch
from scipy.io.wavfile import read
from training.tacotron2_model.stft import TacotronSTFT
max_wav_value = 32768.0
sampling_rate = 22050
filter_length = 1024
hop_length = 256
win_length = 1024
n_mel_channels = 80
mel_fmin = 0.0
mel_fmax = 8... |
from pathlib import Path
from setuptools import find_packages, setup
project_root = Path(__file__).parent
install_requires = (project_root / 'requirements.txt').read_text().splitlines()
extras_require = {'test': ['pytest']}
extras_require['dev'] = extras_require['test']
setup(
name='speechcolab',
version='0... |
resposta = ''
vezes = 0
while resposta != 'M' and resposta != 'F':
if vezes > 0:
print('\n\033[31mResposta Inválida. Tente novamente.\033[m\n')
resposta = str(input('Responda:\n\nM - Para masculino\nF - Para feminino\n\n').upper())
vezes = 1
print('\033[32mObrigado! Tenha um bom dia.')
|
from config_handler import handle_config
from datetime import datetime,timezone
import glob
import logging
import multiprocessing
from os import system, path, chmod, rename
import pysolar.solar as ps
import socket
import ssl
import sys
from threading import Event, Thread
import time
import traceback
import urllib.reque... |
# coding=utf-8
import requests
from bs4 import BeautifulSoup
import json
from janome.tokenizer import Tokenizer
import json
from requests_oauthlib import OAuth1Session
from summpy.lexrank import summarize
# twitterAPI
oath_key_dict = {
"consumer_key": "2qimKikZwCOJXG0wxJ0lzkcM6",
"consumer_secret... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file is part of the complex_terrain algorithm
M. Lamare, M. Dumont, G. Picard (IGE, CEN).
"""
import numpy as np
import Py6S as ps
class rtmodel(object):
"""
"""
def __init__(self):
self.outputs = None
def run(self, sza, saa, vza, vaa, w... |
"""
Everything to do with cleaning up experimental data
"""
from copy import deepcopy
import numpy as np
from tracklib import Trajectory, TaggedSet
def split_trajectory_at_big_steps(traj, threshold):
"""
Removes suspected mislinkages.
Exception: two consecutive big steps such that the overall displaceme... |
def matrix_multiply(A,B):
result = []
for i in range(len(B[0])):
result.append([0]*len(A))
if len(A[0]) != len(B):
return -1
else:
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(A[0])):
result[i][j] =... |
from tradssat.genotype.vars_._cropgro import cropgro_cul_vars, cropgro_eco_vars
cul_vars_PPGRO = cropgro_cul_vars('VAR-NAME')
eco_vars_PPGRO = cropgro_eco_vars()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.