text stringlengths 1 927k |
|---|
import string
from enum import Enum, auto
from itertools import combinations
from string import ascii_lowercase, digits
from typing import Union
# Formula Grammar
###########################################################
# F = V | (L)
# V = aV' | bV' | ... | zV' | 0V' | 1V' | ... | 9V'
# V' = aV' | bV' | ... | zV' ... |
#
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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, pu... |
"""
This file offers the methods to automatically retrieve the graph Thermus aquaticus.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-0... |
import unittest
import hcl2
from checkov.terraform.checks.resource.linode.user_username_set import check
from checkov.common.models.enums import CheckResult
class Testuser_username_set(unittest.TestCase):
def test_success(self):
hcl_res = hcl2.loads("""
resource "linode_user" "test" {
us... |
from pathlib import Path
from typing import Dict
import click
from flora.util.config import load_config, save_config, str2bool
from flora.util.default_root import DEFAULT_ROOT_PATH
def configure(
root_path: Path,
set_farmer_peer: str,
set_node_introducer: str,
set_fullnode_port: str,
set_log_lev... |
from .random_word import RandomWords
__name__ = "Random Word"
__author__ = "Vaibhav Singh <hi@vaibhavsingh97.com>"
__version__ = "1.0.7" |
# pylint: disable=g-bad-file-header
# Copyright 2016 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/LICENS... |
import argparse, json, pickle
from abc import ABC, abstractmethod
from typing import Sequence
from dataclasses import dataclass, asdict
from ..constants import *
def intlt(bounds):
start, end = bounds if type(bounds) is tuple else (0, bounds)
def fntr(x):
x = int(x)
if x < start or x >= end: r... |
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
# -*- coding: utf-8 -*-
import tensorflow as tf
from utils.ops import BLSTM, Conv1D, Reshape, Normalize, f_props, scope, log10
from models.network import Separator
class L41ModelV2(Separator):
def __init__(self, graph=None, **kwargs):
kwargs['mask_a'] = 1.0
kwargs['mask_b'] = -1.0
super(L41ModelV2, self).__in... |
# PyAlgoTrade
#
# Copyright 2011-2015 Gabriel Martin Becedillas Ruiz
#
# 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 ap... |
from django.conf import settings
MODELS_TO_SYNC = getattr(settings, "MODELS_TO_SYNC")
CLIENT_SECRET_JSON_FILEPATH = getattr(settings, "CLIENT_SECRET_JSON_FILEPATH")
DELEGATED_CREDENTIALS = getattr(settings, "DELEGATED_CREDENTIALS", "")
DATETIME_FIELDS = getattr(settings, "DATETIME_FIELDS", (
"DateField", "Datetim... |
#!/usr/bin/env python
# coding: utf-8
"""
DriveFirmwareApi.py
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the foll... |
#
# The Python Imaging Library
# Pillow fork
#
# Python implementation of the PixelAccess Object
#
# Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
# Copyright (c) 1995-2009 by Fredrik Lundh.
# Copyright (c) 2013 Eric Soroos
#
# See the README file for information on usage and redistribution
#
# Note... |
# coding: utf-8
import pprint
import re
import six
class MqsForwarding:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is j... |
import os
from unittest import mock
def delete_file(filename):
while os.path.exists(filename):
os.unlink(filename)
@mock.patch('os.path.exists', side_effect=(True, False, False))
@mock.patch('os.unlink')
def test_delete_file(mock_exists, mock_unlink):
# first try:
delete_file('some non-existing ... |
import unittest
import os
from . import DEFAULT_CONFIG
from wpwatcher.config import Config
class T(unittest.TestCase):
def test_init_config_from_string(self):
# Test minimal config
config_dict=Config.fromstring(DEFAULT_CONFIG)
self.assertEqual(config_dict['email_to'], ["test@mail.com"... |
# 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... |
#!/usr/bin/env python
import os
import sys
from setuptools import setup
from distutils.core import Extension
from distutils.ccompiler import new_compiler
f = open('README.md')
long_description = f.read()
HOMEPAGE = "https://github.com/sumerc/yappi"
NAME = "yappi"
VERSION = "0.99"
_DEBUG = False # compile/link code f... |
from .anchor3d_head import Anchor3DHead
from .anchor_free_mono3d_head import AnchorFreeMono3DHead
from .base_conv_bbox_head import BaseConvBboxHead
from .base_mono3d_dense_head import BaseMono3DDenseHead
from .centerpoint_head import CenterHead
from .fcos_mono3d_head import FCOSMono3DHead
from .free_anchor3d_head impor... |
from django.db import models
from django.forms import ModelForm
from django.contrib.auth import get_user_model
# Create your models here.
# Get the user model
User = get_user_model()
class BillingAddress(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
address = models.CharField(max_length=1... |
from collections import namedtuple
import numpy as np
import talib
from numba import njit
from jesse.helpers import get_candle_source
from jesse.helpers import slice_candles
DamianiVolatmeter = namedtuple('DamianiVolatmeter', ['vol', 'anti'])
def damiani_volatmeter(candles: np.ndarray, vis_atr: int = 13, vis_std: ... |
import cv2
import os
import numpy as np
import argparse
import uuid
import sys
import scipy.spatial
import matplotlib.pyplot as plt
model_path = str(sys.argv[1])
ROADMASKDIR = model_path + "/RoadMask/"
MINUTEMASKDIR = model_path + "/MinuteMask/"
#INPUTVIDEOPATH = os.environ['AICITYVIDEOPATH'] + "/test-data/"
INPUTVID... |
# Copyright (C) 2011-2012 Canonical Services Ltd
#
# 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, ... |
import ast
import tokenize
from io import StringIO
import pytest
from pandas_dev_flaker.__main__ import run
def results(s):
return {
"{}:{}: {}".format(*r)
for r in run(
ast.parse(s),
list(tokenize.generate_tokens(StringIO(s).readline)),
)
}
@pytest.mark.par... |
__docformat__ = "restructuredtext en"
__all__ = ['logspace', 'linspace',
'select', 'piecewise', 'trim_zeros',
'copy', 'iterable',
'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp',
'unique', 'extract', 'place', 'nansum', 'nanmax', 'nanargmax',
'nanargmi... |
from driver.interface_wheels_driver import IWheelsDriver
class DummyWheelsDriver(IWheelsDriver):
def set_velocity(self, left_wheel, right_wheel):
print('setting velocity to %.2f, %.2f' % (left_wheel, right_wheel))
def stop_wheels(self):
self.set_velocity(0, 0)
def stop_driver(self):
... |
import os
def initialize():
if os.name == 'nt':
from clipmanager.hotkey.win32 import GlobalHotkeyManagerWin
return GlobalHotkeyManagerWin()
elif os.name == 'posix':
from clipmanager.hotkey.x11 import GlobalHotkeyManagerX11
return GlobalHotkeyManagerX11() |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Fraunhofer FKIE/US, Alexander Tiderko
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code mus... |
from typing import Optional
from dataclasses import dataclass
from hikaru.meta import HikaruDocumentBase
from ...core.reporting import Finding
from ...core.model.k8s_operation_type import K8sOperationType
from ...core.model.events import ExecutionBaseEvent
@dataclass
class K8sBaseChangeEvent(ExecutionBaseEvent):
... |
import re
import gzip
from Bcfg2.Server.Plugins.Packages.Collection import Collection
from Bcfg2.Server.Plugins.Packages.Source import Source
from Bcfg2.Bcfg2Py3k import cPickle, file
class AptCollection(Collection):
def get_group(self, group):
self.logger.warning("Packages: Package groups are not supporte... |
try:
from tkinter.messagebox import *
except ImportError:
from tkMessageBox import * |
import logging
import asyncio
from datetime import datetime
from concurrent.futures import Future
from rx.disposable import Disposable
from rx.core import typing
from rx.disposable import SingleAssignmentDisposable, CompositeDisposable
from rx.concurrency.schedulerbase import SchedulerBase
log = logging.getLogger("Rx... |
import copy
valid_ip_response = {
"ip": "71.6.135.131", # NOSONAR
"seen": True,
"classification": "malicious",
"first_seen": "2019-04-04",
"last_seen": "2019-08-21",
"actor": "unknown",
"tags": [
"MSSQL Bruteforcer",
"MSSQL Scanner",
"RDP Scanner"
],
"vpn": ... |
# Copyright 2019, The TensorFlow Federated 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 o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the file-like object implementation using pyfsntfs."""
from __future__ import unicode_literals
import os
import unittest
from dfvfs.file_io import ntfs_file_io
from dfvfs.lib import errors
from dfvfs.path import ntfs_path_spec
from dfvfs.path import os_path_... |
"""empty message
Revision ID: 9e4bb9179aca
Revises:
Create Date: 2020-10-08 00:14:42.284775
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9e4bb9179aca'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
# _____ ______ _____
# / ____/ /\ | ____ | __ \
# | | / \ | |__ | |__) | Caer - Modern Computer Vision
# | | / /\ \ | __| | _ / Languages: Python, C, C++
# | |___ / ____ \ | |____ | | \ \ http://github.com/jasmcaus/caer
# \_____\/_/ \_ \______ |_| \_\
# Licensed ... |
# -*- coding: utf-8 -*-
import re
from inmembrane.helpers import run, parse_fasta_header, dict_get
citation = {'ref': u"Agnieszka S. Juncker, Hanni Willenbrock, "
u"Gunnar Von Heijne, Søren Brunak, Henrik Nielsen, "
u"And Anders Krogh. (2003) Prediction of lipoprotein "
... |
from dataiku.customrecipe import get_input_names_for_role, get_output_names_for_role
import dataiku
from dku_config import DkuConfig
class DkuFileManager(DkuConfig):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def add_file(self, side, type_, role, **kwargs):
file = DkuFileManager... |
import datetime
from dataclasses import dataclass
from logging import Logger
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple
import imageio
import numpy as np
import torch
from audio_utils import get_duration_s, normalize_wav
from audio_utils.audio import concatenate_audios
from audio... |
import _plotly_utils.basevalidators
class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self,
plotly_name="tickvals",
parent_name="histogram2dcontour.colorbar",
**kwargs,
):
super(TickvalsValidator, self).__init__(
plotly_... |
import networkx as nx
from host import host
from ryu.topology.switches import Switch
from ryu.topology.switches import Port
class netmap:
def __init__(self):
self.dDummy = "Disconnected"
self.networkMap = nx.Graph()
self.networkMap.add_node(self.dDummy)
def getAllSwitches(self):
... |
#
# multibytecodec_support.py
# Common Unittest Routines for CJK codecs
#
import codecs
import os
import re
import sys
import unittest
from http.client import HTTPException
from test import support
from io import BytesIO
class TestBase:
encoding = '' # codec name
codec = None # codec tupl... |
from operator import mul
numstr = '73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
622298934233803081353362... |
from time import sleep
from gpiozero import LED
from hm_pyhelper.hardware_definitions import is_rockpi, is_raspberry_pi
from gatewayconfig.gatewayconfig_shared_state import GatewayconfigSharedState
from gatewayconfig.logger import get_logger
LOGGER = get_logger(__name__)
LED_REFRESH_SECONDS = 2
class LEDProcessor:
... |
# -----------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -----------------------------------------------------------------------------
""... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... |
from abc import ABC, abstractmethod
from typing import Any
import numpy as np
import pandas as pd
from sklearn.model_selection import GridSearchCV
from skopt import BayesSearchCV
from skopt.space import Real, Integer, Categorical
from resources.backend_scripts.switcher import Switch
NpArray = np.ndarray
DataFrame = ... |
from .. import NetQuery
import dns.resolver
import logging
import re
class DNSQuery(NetQuery):
"""Query configured or default DNS servers for a particular record."""
def __init__(self, cfg):
super(DNSQuery, self).__init__(cfg)
self.__logger = logging.getLogger('pircons.NetQuery.DNSQuery')
query, nameservers = ... |
import os
from waterbutler.core import metadata
class S3Metadata(metadata.BaseMetadata):
@property
def provider(self):
return 's3'
@property
def name(self):
return os.path.split(self.path)[1]
class S3FileMetadataHeaders(S3Metadata, metadata.BaseFileMetadata):
def __init__(sel... |
# coding: utf-8
import os
import re
import zipfile
import tempfile
import subprocess
from os import path
from io import BytesIO
from shutil import get_terminal_size
import rarfile
from guessit import guessit
from getsub.constants import SUB_FORMATS, ARCHIVE_TYPES, VIDEO_FORMATS
class ProgressBar:
def __init__(... |
from django.contrib.auth import get_user_model, authenticate
from django.utils.translation import gettext as _
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the user objects"""
class Meta:
model = get_user_model()
fields = ('email... |
"""
Django Linked Items Models
"""
from django.db import models
from ..tools import relations
#pylint: disable=no-member
class Item(models.Model):
"The base item to be linked."
name = models.CharField(max_length=128)
def get_linked(self, upwards=False):
"Return relations."
# The return com... |
from enum import IntEnum
from fattie.belly.fluffyvariable import FluffyVariable
match_operators = {
"+": "PLUS",
"-": "MINUS",
"*": "TIMES",
"/": "DIVIDE",
"equals": "EQUALS",
"less": "LESS",
"greater": "GREATER",
"notequal": "NOTEQUAL",
"return": "RETURN"
}
class Operator(IntEnum... |
# Copyright (c) ZenML GmbH 2021. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
"""ms.dbkeeper Form definitions """
from django import forms
from django.core.validators import RegexValidator
import operator
from .models import Organization, Team
from .team_code import TeamPassCode
#----------------------------------------------------------------------------
class FilteredFileField(forms.FileFie... |
import math
import os
import random
import re
import sys
# Complete the checkMagazine function below.
def checkMagazine(magazine, note):
res = 'Yes'
start = 0
end = len(note)-1
while start<=end:
if start==end:
if note[start] not in magazine:
res ='No'
... |
import os
from torch.utils import data
import librosa
from util.utils import sample_fixed_length_data_aligned
class Dataset(data.Dataset):
def __init__(self, dataset, limit=None, offset=0, sample_length=16384, mode="train"):
"""
构建训练数据集
Args:
dataset (str): 语音数据集的路径,拓展名为 txt,见 ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2012 Christopher D. Lasher
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.
"""Generates a random sequence with CpG islands.
This script produces three outfiles:
* a FASTA format sequence file
* a file containi... |
"""
generate ASCII STL for a rectangular surface with heights spaced over a grid.
todo
facet direction is correct but that's not obvious from the code -needs clarification
Chris Wallace kitwallace.co.uk
March 2014
"""
from numpy import *
def vertex (p) :
return "vertex " + s... |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import unittest
from pathlib import Path
import os
import numpy as np
from pymatgen.core.operations import SymmOp
from pymatgen.core.sites import PeriodicSite
from pymatgen.core.structure import Molecule, Str... |
"""
This file offers the methods to automatically retrieve the graph Spiroplasma mirum.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-0... |
# Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http... |
import cv2
import numpy as np
from PIL import Image
import random
import string
import os
class ImageUtils(object):
@staticmethod
def read_image_for_bokeh(image_path, resize_height=None):
# Open image, and make sure it's RGB*A*
image = Image.open(image_path).convert('RGBA')
print("image... |
import numpy as np
#############################################
# variable #
#############################################
val = False
x = 0
y = 0
#############################################
# function #
############################################... |
from mindware.components.feature_engineering.transformations import _bal_balancer, _preprocessor, _rescaler, \
_image_preprocessor, _text_preprocessor, _bal_addons, _imb_balancer, _gen_addons, _res_addons, _sel_addons
from mindware.components.utils.class_loader import get_combined_fe_candidtates
from mindware.compo... |
from enum import IntEnum
class Component(IntEnum):
'''Seismic record geographical components (R T Z).
'''
Z = 0
R = 1
T = 2
@staticmethod
def parse_component(str):
'''Parse component from a str.
Args:
str (str): str representation of a component
... |
"""
This module provides the building blocks for Hamiltonians, and
defines their built-in behavior and operations.
"""
import numpy as np
from . import config, validate, msc_tools
from .computations import evolve, eigsolve
from .subspaces import Full
from .states import State
class Operator:
"""
A class repr... |
from sklearn.cluster import AgglomerativeClustering
import pandas as pd
import numpy as np
from zoobot import label_metadata, schemas
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support
from scipy.optimize import linear_sum_assignment as linear_assignment
import time
def findChoice(frac):
... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... |
import argparse
import os
import time
import tinynn as tn
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class Dense(nn.Module):
def __init__(self):
super(Dense, self).__init__()
self.fc1 = nn.Linear(784, 200)
self.fc2 = nn.Linear(200, 100... |
# -*- coding: utf-8 -*-
# @Author: ronanjs
# @Date: 2020-01-19 22:23:54
# @Last Modified by: ronanjs
# @Last Modified time: 2020-07-02 10:52:19
class DRV:
def __init__(self, objects, rest):
self.objects = objects
self.rest = rest
def subscribe(self):
drvHandles = self.objects.ha... |
# -*- coding: utf-8 -*-
from pyparsing import Optional, Group, Literal, CaselessKeyword, And, OneOrMore
from .primitives import SimpleWord, Field, PartialString, QuotedString, Integer, IntegerRange, concatenate
class TermFactory(object):
@staticmethod
def build_term(field, values, parse_method=None):
... |
from __future__ import absolute_import, division, unicode_literals
import os
import sys
import traceback as tb
from collections import OrderedDict, defaultdict
import param
from .layout import Row, Column, HSpacer, VSpacer
from .pane import HoloViews, Pane, Markdown
from .widgets import Button, Select
from .param i... |
a = {
"name": "None.Reporter",
"app": None,
"table": "re_port_er",
"abstract": False,
"description": "Whom is assigned as the reporter ",
"docstring": "Whom is assigned as the reporter ",
"unique_together": [],
"pk_field": {
"name": "id",
"field_type": "IntField",
... |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
"""
Tutorial: File upload and download
Uploads
-------
When a client uploads a file to a CherryPy application, it's placed
on disk immediately. CherryPy will pass it to your exposed method
as an argument (see "myFile" below); that arg will have a "file"
attribute, which is a handle to the temporary uploaded file.
If... |
import math
import scene
class Calculator:
def __init__(self):
self.scene = scene.Scene()
def calculate(self, feathers, pictures_count, cutter_angle):
self.scene.set(feathers, cutter_angle)
self.pictures_count = pictures_count
self.angle = math.radians(360) / self.pictures_c... |
# Copyright Amazon.com Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompany... |
#-------------------------------------------------------------------------------
# Name: forward_process.py
# Purpose: To provide set of functions which serve as discretization of an
# area as well as used in retrieval process.
#------------------------------------------------------------------... |
import itertools
import math
from copy import copy
from django.core.exceptions import EmptyResultSet
from django.db.models.expressions import Exists, Func, RawSQL, Value
from django.db.models.fields import DateTimeField, Field, IntegerField
from django.db.models.query_utils import RegisterLookupMixin
from django.utils... |
import os
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2018, 11, 2),
'email': ['airflow@example.com'],
'email_on_failure': False,
'e... |
# -*- coding: utf-8 -*-
from itertools import chain
import application.models as Models
from application.cel import celery
@celery.task
def update_user_stats(user_id):
stat, created = Models.OrderStat.objects.get_or_create(user_id=user_id)
all_orders = Models.Order.objects(customer_id=user_id)
stat.num_... |
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is... |
# Copyright (C) 2001-2010 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Miscellaneous utilities."""
__all__ = [
'collapse_rfc2231_value',
'decode_params',
'decode_rfc2231',
'encode_rfc2231',
'formataddr',
'formatdate',
'format_datetime',
'getaddre... |
from __future__ import absolute_import
import six
from sentry.utils.compat import map
version = (0, 7, 28)
__version__ = ".".join(map(six.text_type, version)) |
import torch
import torch.nn as nn
import torch.nn.functional as F
import hdvw.models.layers as layers
import hdvw.models.gates as gates
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_channels, channels,
stride=1, groups=1, width_per_group=64, rate=0.3, sd=0.0,
... |
import math
def truncate(number, digits) -> float:
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper |
# global
import torch
from typing import Union, Optional, Tuple, List
def roll(x: torch.Tensor, shift: Union[int, Tuple[int]], axis: Union[int, Tuple[int]]=None)\
-> torch.Tensor:
return torch.roll(x, shift, axis)
# noinspection PyShadowingBuiltins
def flip(x: torch.Tensor,
axis: Optional[Union[i... |
import json
import os
import tempfile
from os.path import dirname
from pathlib import Path
from unittest import TestCase
import src.superannotate as sa
class TestCocoSplit(TestCase):
TEST_FOLDER_PATH = "data_set/converter_test/COCO/input/toSuperAnnotate"
TEST_BASE_FOLDER_PATH = "data_set/converter_test"
... |
import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.functional as F
import scipy.io as sio
import numpy as np
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Define Basic reconstruct block
class BasicBlock(torc... |
# -*- coding: utf-8 -*-
#from collections import OrderedDict
from gluon import current#, URL
from gluon.storage import Storage
def config(settings):
"""
Settings for Bhutan's extensions to the core SaFiRe template.
"""
T = current.T
settings.base.system_name = T("Disaster Management Informa... |
# testing Fiona's RFC 3339 support, to be called by nosetests
import logging
import re
import sys
import unittest
from fiona.rfc3339 import parse_date, parse_datetime, parse_time
from fiona.rfc3339 import group_accessor, pattern_date
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
class DateParseTest(un... |
#!/usr/bin/env python3
import os
import sys
import argparse
import logging
from time import sleep
from urllib3 import disable_warnings
from .config import load_config, ConfigError
from .mqtt2influxdb import Mqtt2InfluxDB
from . import __version__
LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
def main():
... |
# -*- coding: UTF-8 -*-
"""
Main module of preprocessor package. Can be executed by `python -m preprocessor`.
"""
import os
import pickle
from random import shuffle
import numpy as np
from chicksexer.constant import POSITIVE_CLASS, NEGATIVE_CLASS, NEUTRAL_CLASS, CLASS2DEFAULT_CUTOFF
from chicksexer.util import get_lo... |
from collections import ChainMap
import yaml
import torch
import fairseq_mod
import sys
sys.path.append("../..")
from wav2vec2_inference_pipeline import inference_pipeline
from data_loader import LibriSpeechDataLoader
from knowledge_distillation.kd_training import KnowledgeDistillationTraining
from fairseq_mod.model... |
from django.contrib.admin import ModelAdmin
from django.conf import settings
from garb.config import default_config, get_config
from garb.tests.mixins import UserTestCaseMixin
from garb.tests.models import *
class ConfigTestCase(UserTestCaseMixin):
def test_garb_config_when_not_defined(self):
try:
... |
r"""
A cumulative distribution function of an independent multivariate random
variable can be made dependent through a copula as follows:
.. math::
F_{Q_0,\dots,Q_{D-1}} (q_0,\dots,q_{D-1}) =
C(F_{Q_0}(q_0), \dots, F_{Q_{D-1}}(q_{D-1}))
where :math:`C` is the copula function, and :math:`F_{Q_i}` are marginal
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.