text stringlengths 1 927k |
|---|
import sys
import mock
import unittest
from see import Hook
from see import context
from see.hooks import HookParameters
STATES = (context.NOSTATE, context.RUNNING, context.BLOCKED,
context.PAUSED, context.SHUTDOWN, context.SHUTOFF,
context.CRASHED, context.SUSPENDED)
class TestHook(Hook):
... |
import dataclasses
from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, Optional, Type, Union
from .class_validators import gather_validators
from .error_wrappers import ValidationError
from .errors import DataclassTypeError
from .fields import Required
from .main import create_model, validate_model
from ... |
from __future__ import unicode_literals
import importlib
from datetime import timedelta
import croniter
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.templatetags.tz import utc
from django.utils.translation import ugettext_lazy as _
impor... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import time
from concurrent import futures
import data_pb2
import data_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_HOST = '0.0.0.0'
_PORT = '8888'
class FormatData(data_pb2_grpc.FormatDataServicer):
def DoFormat(self, request, context):
str = re... |
#!/usr/bin/env python3
"""
MIT License
Copyright (c) 2020 Srevin Saju
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, mo... |
from . import relay
from .mutations import (
DeleteJSONWebTokenCookie, DeleteRefreshTokenCookie, JSONWebTokenMutation,
ObtainJSONWebToken, Refresh, Revoke, Verify,
)
__all__ = [
'relay',
'JSONWebTokenMutation',
'ObtainJSONWebToken',
'Verify',
'Refresh',
'Revoke',
'DeleteJSONWebToken... |
# ------ Python standard library imports ---------------------------------------
# ------ External imports ------------------------------------------------------
# ------ Imports from own package or module ------------------------------------
#----------------------------------------------------------------------------... |
# 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 may ... |
import unittest
import sccf
import cvxpy as cp
import numpy as np
class TestMinExpression(unittest.TestCase):
def test(self):
x = cp.Variable(10)
x.value = np.zeros(10)
expr = cp.sum_squares(x)
with self.assertRaises(AssertionError):
sccf.minimum(-expr, 1.0)
mi... |
from __future__ import unicode_literals
import json as jsonencode
from datetime import datetime
import pytz
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def abs... |
# stdlib
import base64
import json
import logging
import uuid
# third party
import jwt
import requests
# grid relative
from ...codes import CYCLE
from ...codes import MODEL_CENTRIC_FL_EVENTS
from ...codes import MSG_FIELD
from ...codes import RESPONSE_MSG
from ..processes import process_manager
def verify_token(aut... |
#-*- coding: utf-8 -*-
from bson import ObjectId as _ObjectId
from datetime import datetime
__all__ = ['ObjectId', 'String', 'Integer', 'Float', 'Long', 'List', 'Boolean', 'DateTime']
class TypeMixin(object):
def is_valid(self, value):
raise NotImplementedError
def to_value(self):
raise No... |
__author__ = 'patras'
from domain_springDoor import *
from timer import DURATION
from state import state
DURATION.TIME = {
'unlatch1': 5,
'unlatch2': 5,
'holdDoor': 2,
'passDoor': 3,
'releaseDoor': 2,
'closeDoors': 3,
'move': 10,
'take': 2,
'put': 2,
}
DURATION.COUNTER = {
'un... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0028_resourcebase_is_approved'),
]
operations = [
migrations.AlterField(
model_name='resourcebase',
name='language',
),
... |
# -*- coding: utf-8 -*-
import numpy as np
import pytest
import pandas.compat as compat
import pandas as pd
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
import pandas.util.testing as tm
# TODO: more freq variants
@pytest.fixture(params=['D', 'B', 'W', 'M', 'Q', 'Y'])
def period_index(re... |
import torch.nn as nn
from utils.builder import get_builder
from args import args
from collections import OrderedDict
# Binary activation function with gradient estimator
import torch
class F_BinAct(torch.autograd.Function):
@staticmethod
def forward(ctx, inp):
# Save input for backward
ctx.save_for_bac... |
# Generated by Django 2.2.7 on 2021-02-23 18:48
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('exam', '0020_auto_20210223_1915'),
]
operations = [
migrations.AddField(
model_name='exam',
... |
# -*- coding: utf-8 -*-
import asyncio
import socket
import struct
from .errors import (
SocksConnectionError, InvalidServerReply, SocksError,
InvalidServerVersion, NoAcceptableAuthMethods,
LoginAuthenticationFailed, UnknownAuthMethod
)
RSV = NULL = 0x00
SOCKS_VER4 = 0x04
SOCKS_VER5 = 0x05
SOCKS_CMD_CONN... |
# -*- coding: utf-8 -*-
from ogs5py import OGS
model = OGS(
task_root='1D_TPF_resS_trans_root',
task_id='1D_TPF_resS_trans',
output_dir='out',
)
model.msh.read_file('1D_TPF_resS_trans.msh')
model.gli.read_file('1D_TPF_resS_trans.gli')
model.pcs.add_block(
main_key='PROCESS',
PCS_TYPE='PS_GLOBAL',
... |
"""
LC 697
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: nums = [1,2,2,3,1]
Out... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2017 nicolas <nicolas@laptop>
#
# Distributed under terms of the MIT license.
"""
In this model it seek to predict the flower specie given measures of the petal and sepal.
It uses the iris dataset, which one it is build a linear model to predict the species ... |
import os
def load(name):
"""
This method creates and loads a new journal.
:param name: The base name of the journal to load.
:return: A new journal data structure populated with the file data.
"""
data = []
filename = get_full_pathname(name)
if os.path.exists(filename):
with... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Bai Web and Mobile Lab and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestReplenishmentRule(unittest.TestCase):
pass |
'''
Created on 17.03.2015
@author: vvladych
'''
from forecastmgmt.dao.db_connection import get_db_connection
import psycopg2.extras
from MDO import MDO
class FCTextModel(MDO):
sql_dict={"get_all":"SELECT sid, textmodel_date, textmodel_uuid, forecast_sid FROM fc_textmodel",
"delete":"DELET... |
print('''Condições de pagamento:
1- À vista e/ou cheque com 10% de desconto;
2- À vista no cartão com 5% de desconto;
3- Em 2x sem juros no cartão;
4- A partir de 3x no cartão com 20% de juros;''')
print('')
opcao = int(input('Selecione a opão desejada e aperte enter: '))
preco = float(input('Digite o valor a... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Test to check assessment import with mapped regulation."""
from collections import OrderedDict
from mock import patch
from integration.ggrc import TestCase, read_imported_file
from integration.ggrc.api_... |
from __future__ import unicode_literals
from operator import attrgetter
from django.apps import apps
from django.core import checks
from django.db import connection, connections, router, transaction
from django.db.backends import utils
from django.db.models import signals, Q
from django.db.models.deletion import SET_... |
# Lint as: python3
# 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 ... |
import logging
from collections import defaultdict
import numpy as np
import scipy.spatial as spatial
from opensfm import bow, context, feature_loader, vlad
from opensfm.dataset import DataSetBase
logger = logging.getLogger(__name__)
def has_gps_info(exif):
return (
exif
and "gps" in exif
... |
# Generated by Django 3.1.2 on 2020-11-04 15:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
... |
"""
Nick Kaparinos
Dogs vs. Cats
Kaggle Competition
Grid Search using pytorch
"""
import pandas as pd
from random import seed
from utilities import *
from torch.utils.data import DataLoader
from torchvision.models import vgg16
from torch.utils.tensorboard import SummaryWriter
import torch
import time
# Options
pd.set... |
#!/usr/bin/env python3
"""
Script to automatically send e-mails if a new file was found on the scanner's sdcard
"""
import os
import magic
import re
from collections import namedtuple
from datetime import datetime
import logging
from apscheduler.schedulers.background import BlockingScheduler
import smtplib
from email.... |
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2014-2015 The Dash developers
# Copyright (c) 2018 The Blocknode developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Helpful routines for regression te... |
# 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 use ... |
##################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2020 #
######################################################################################
# One-Shot Neural Architecture Search via Self-Evaluated Template Network, ICCV 2019 #
############################################... |
# 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 may ... |
"""
This file offers the methods to automatically retrieve the graph halfb.
The graph is automatically retrieved from the NetworkRepository repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-06... |
import os
import requests
import time
import json
import urllib.parse
import logging
from typing import Dict, Callable, Union
from instauto.api.structs import DeviceProfile, IGProfile, State, Method
from instauto.api.constants import API_BASE_URL
from instauto.api.exceptions import WrongMethodException, IncorrectLog... |
"""Base generator file"""
import abc
import os
import sys
from .helpers import write_license_file
class BaseGenerator: # pylint: disable=too-few-public-methods
"""Base generator class"""
def __init__(self, project_name):
self.project_name = project_name
@abc.abstractmethod
def create(self):... |
# 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... |
"""General-purpose test script for image-to-image translation.
Once you have trained your model with train.py, you can use this script to test the model.
It will load a saved model from --checkpoints_dir and save the results to --results_dir.
It first creates model and dataset given the option. It will hard-code some... |
from __future__ import absolute_import, division, print_function
# note: py.io capture tests where copied from
# pylib 1.4.20.dev2 (rev 13d9af95547e)
from __future__ import with_statement
import pickle
import os
import sys
from io import UnsupportedOperation
import _pytest._code
import py
import pytest
import contextl... |
"""Python interface to Swiss snow conditions websites"""
__version__ = "0.1.0"
__author__ = "Sebastien Tr"
from .Resorts import Resorts |
"""
Apple Push Notification Service
Documentation is available on the iOS Developer Library:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
"""
import time
from apns2 import client as apns2_client
from apns2 import credentials as apns2_c... |
from openpyxl import load_workbook
#enter the source filename for the Excel worksheet in this variable
filename = 'aalh_iit_vanderlipcollection.xlsx'
wb = load_workbook(filename)
ws = wb['Metadata Template']
#variables define the array of rows and columns
minimumcol = 2
maximumcol = 2
minimumrow = 494
maximumrow = 89... |
#!/usr/bin/env python3
# Copyright (c) 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
G... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/melodic/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, ... |
#
# The Python Imaging Library
# $Id: image2py.py 2134 2004-10-06 08:55:20Z fredrik $
#
# convert an image to a Python module
#
# to use the module, import it and access the "IMAGE" variable
#
# import img1
# im = img1.IMAGE
#
# the variable name can be changed with the -n option
#
# note that the applicati... |
# coding: utf-8
import sys
from collections import Counter
import gc
import numpy as np
import tensorflow.contrib.keras as kr
import jieba
import pandas as pd
import re
if sys.version_info[0] > 2:
is_py3 = True
else:
#reload(sys)
sys.setdefaultencoding("utf-8")
is_py3 = False
def native_word(word, enco... |
import pyapr
import numpy as np
from time import time
def main():
"""
This demo implements a piecewise constant reconstruction using the wrapped PyLinearIterator. The Python reconstruction
is timed and compared to the internal C++ version.
Note: The current Python reconstruction is very slow and need... |
# -*- coding: utf-8 -*-
"""Stdout, stderr and argv support for unicode."""
#
# (C) David-Sarah Hopwood, 2010
# (C) Pywikibot team, 2012-2015
#
##############################################
# Support for unicode in windows cmd.exe
# Posted on Stack Overflow [1], available under CC-BY-SA 3.0 [2]
#
# Question: "Windows c... |
from datetime import datetime
import requests
class Charges:
"""
The system tracks usage of paid service on an hourly basis.
It doesn't track how much to charge for any particular product, but it will report for each instance,
IP address and snapshot the amount of hours it's in use for.
"""
... |
from picamera import PiCamera
from time import sleep
camera = PiCamera()
#camera.capture('image-test.jpg')
camera.start_preview()
while True:
sleep(1)
#camera.close() |
import cv2
img = cv2.imread('data/image10.jpg')
print(img.shape)
img_cropped = img[0:200, 200:500] # Height comes first then the width
cv2.imshow("Cropped image", img_cropped)
cv2.imshow("Original image", img)
cv2.waitKey(0) |
from logging import getLogger
from src import settings
from src.utils import (
fetch_html,
get_latest_year_term,
get_year_terms,
insert_year_term,
is_new_term,
)
# __name__では__main__になるので、直接srcを指定する。
logger = getLogger("src")
def main():
try:
html = fetch_html(settings.HOKUDAI_GRADE_... |
from dumb_switcher import DuMBSwitcher as ds
import pytest
import os
from PIL import Image
import unittest
from unittest import mock
from dumb_switcher import controller
TEST_IMAGE_NUM = 0
def test_parse_screen_properties_to_resolution_and_position():
"""
Test cases for parsing the resolution from xrandr
... |
import sst
# Define SST core options
sst.setProgramOption("stopAtCycle", "10us")
# Set up senders using user subcomponents
loader0 = sst.Component("Loader0", "simpleElementExample.SubComponentLoader")
loader0.addParam("clock", "1.5GHz")
loader0.enableAllStatistics()
sub0_0 = loader0.setSubComponent("mySubComp", "sim... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
class TemplateHandler(object):
def __init__(self):
aPath = os.path.realpath(__file__)
aPath = os.path.dirname(aPath)
aPath = os.path.join(aPath, "..")
aPath = os.path.normpath(aPath)
self.templatePath = os.path.join(aPath, "templates")
self.loadTe... |
import math
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.contrib import slim
from tensorflow.contrib import layers as tflayers
@slim.add_arg_scope
def conv2d_transpose(
inputs,
out_shape,
kernel_size=(5, 5),
stride=(1, 1),
... |
import ast
class KernelSimplicityASTChecker(ast.NodeVisitor):
class ScopeGuard:
def __init__(self, checker):
self.c = checker
self._allows_for_loop = True
self._allows_more_stmt = True
@property
def allows_for_loop(self):
return self._allows_for_loop
@property
def allow... |
from .base_provider import BaseBackupProvider
from .mongo_provider import MongoBackupProvider
from .provider_manager import BackupProviderManager |
from match import find_match |
"""
A TestRunner for use with the Python unit testing framework. It
generates a HTML report to show the result at a glance.
The simplest way to use this is to invoke its main method. E.g.
import unittest
import HTMLTestRunner
... define your tests ...
if __name__ == '__main__':
HTMLTestRunne... |
#!/usr/bin/env python
"""
LUFA Library
Copyright (C) Dean Camera, 2019.
dean [at] fourwalledcubicle [dot] com
www.lufa-lib.org
"""
"""
Front-end configuration app for the TempDataLogger project. This script
configures the logger to the current system time and date, with a user
... |
#!/usr/bin/env python2
import argparse
import sys
from openravepy import Environment, RaveDestroy
from stripstream.algorithms.focused.simple_focused import simple_focused
from stripstream.algorithms.search.fast_downward import get_fast_downward
from robotics.openrave.utils import open_gripper, \
Conf, initialize_o... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Custom Resource for Relationship that creates Snapshots when needed.
When Audit-Snapshottable Relationship is POSTed, a Snapshot should be created
instead.
"""
from werkzeug.exceptions import MethodNotA... |
# Model Params
model = 'robnet_large_v2'
model_param = dict(C=64,
num_classes=10,
layers=33,
steps=4,
multiplier=4,
stem_multiplier=3,
share=True,
AdPoolSize=1)
# Dataset Params
dataset ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
"""Эффект исчезновения фотографии
Кликая на области на фотографии запускаются процессы плавного увеличения
прозрачности пикселей, эффект как круги воды, будут расходиться пока не
закончатся непрозрачные пиксели"""
import sys
import traceback
... |
#!/usr/bin/env python
# Lint as: python3
# -*- encoding: utf-8 -*-
"""Tests for export converters."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import binascii
import os
import socket
from absl import app
from absl.testing import absltest
from grr_... |
import pandas as pd
import numpy as np
from sklearn.svm import SVC, SVR
from sklearn.model_selection import cross_validate
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import confusion_matrix
from sklearn.metrics import make_scorer
def cf_matrix_00(y_true, y_pred):
cf_matr = co... |
"""
test_group_wb
----------------------------------
Tests for the `kifield.group_wb` function
"""
import unittest
import openpyxl as pyxl
import hypothesis
import hypothesis.strategies as st
from kifield import kifield
class TestGroupWb(unittest.TestCase):
def test_groups(self):
wb = pyxl.Workbook()
... |
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk import pos_tag
import string
import re
import langid
# Convert to float format
def string_to_float(x):
return float(x)
# Use langid module to classify the language to make sure we are applying the correct cleanup actions f... |
import math
import os
import re
import sys
exec(open(sys.argv[1], "r").read())
def gen_gnuplot(exp_name, exp_type):
f = open("tmp_" + exp_name + "_" + exp_type + ".gnuplot", "w")
print("set terminal postscript eps enhanced color size " + plot_config_exp[exp_name]["size"] + " font '" + plot_config_misc["font"]... |
######################################################################
#
# File: b2sdk/transfer/emerge/planner/planner.py
#
# Copyright 2020 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
import hashl... |
@abstract
class Abstract:
some_property: int
@require(lambda some_property: some_property > 0)
def __init__(self, some_property: int) -> None:
self.some_property = some_property
def some_func(self) -> None:
pass
__book_url__ = "dummy"
__book_version__ = "dummy" |
from io import StringIO
import matplotlib.pyplot as p
import numpy as np
import pandas as pd
import seaborn as s
import mplcursors
import matplotlib.collections
from mpld3 import plugins
# %matplotlib widget
f = StringIO()
# pip install matplotlib seaborn
def beeplot():
# dataset
# iris2 = pd.DataFrame(np.... |
import py_pjsua
status = py_pjsua.create()
print "py status " + `status`
#
# Create configuration objects
#
ua_cfg = py_pjsua.config_default()
log_cfg = py_pjsua.logging_config_default()
media_cfg = py_pjsua.media_config_default()
#
# Logging callback.
#
def logging_cb1(level, str, len):
print str,
#
# Config... |
"""Crypto Technical Analysis Controller Module"""
__docformat__ = "numpy"
# pylint:disable=too-many-lines
import argparse
import difflib
from typing import List, Union
from datetime import datetime
from colorama import Style
import pandas as pd
from prompt_toolkit.completion import NestedCompleter
from gamestonk_ter... |
"""Helper functions for the 'type' argument of argparse's add_argument method."""
import argparse
import pytimeparse.timeparse
import os.path
class IntCmp(object):
"""Check that arg is an integer satisfying a condition"""
def __init__(self, val, description):
super(IntCmp, self).__init__()
sel... |
#
# This file is part of LiteX.
#
# Copyright (c) 2020 Pepijn de Vos <pepijndevos@gmail.com>
# Copyright (c) 2015-2018 Florent Kermarrec <florent@enjoy-digital.fr>
# SPDX-License-Identifier: BSD-2-Clause
import os
import sys
import math
import subprocess
from shutil import which, copyfile
from migen.fhdl.structure im... |
import numpy as np
import networkit as nk
from collections import defaultdict
from typing import Dict
import pytest
from cortex_model import cortex_model
def default_params() -> Dict[str, any]:
size = 4
graph = nk.graph.Graph(size, directed=True)
graph.addEdge(0, 1)
graph.addEdge(0, 2)
graph.addE... |
import subprocess
import os
import io
import json
import sys
import urllib
import pytest
# https://docs.pytest.org/en/latest/assert.html#assert-details
pytest.register_assert_rewrite("tests.assertions")
def make_dsn(httpserver, auth="uiaeosnrtdy", id=123456):
url = urllib.parse.urlsplit(httpserver.url_for("/{}"... |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# pylint: disable=duplicate-code
# pylint: disable=li... |
import numpy as np
import pytest
import pandas as pd
from pandas import (
Series,
date_range,
)
import pandas._testing as tm
from pandas.core.arrays import PeriodArray
class TestSeriesIsIn:
def test_isin(self):
s = Series(["A", "B", "C", "a", "B", "B", "A", "C"])
result = s.isin(["A", "C... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/bio_engineer/dna_template/shared_dna_template_angler.iff"
... |
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.parameter import Parameter
AdaptiveAvgPool2d = nn.AdaptiveAvgPool2d
class AdaptiveConcatPool2d(nn.Module):
def __init__(self, sz=None):
super().__init__()
sz = sz or (1, 1)
self.ap = nn.AdaptiveAvgPool2d(... |
import pytest
import astroid
import pylint.testutils
import pylint_protobuf
class TestNestedScopes(pylint.testutils.CheckerTestCase):
CHECKER_CLASS = pylint_protobuf.ProtobufDescriptorChecker
@pytest.mark.xfail(reason='scope and modules overwrite so last wins')
def test_many_imports_no_aliasing(self):
... |
import os, glob, cv2
import numpy
import pylab
path = '/home/faedrus/Documents/au_trap/20141027/'
listing = os.listdir(path)
listing = sorted (listing)
count = 0
img = 0
amount = 0
for im_file in listing:
new = cv2.imread(path+im_file)
img = cv2.add(new, img)
count += 1
if count > 9:
amount... |
# Generated by Django 3.1.6 on 2021-04-04 14:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('donor', '0016_auto_20210403_1440'),
]
operations = [
migrations.CreateModel(
name='NewDonor',
fields=[
... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 6
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_1_1
from i... |
"""This module contains the general information for CloudDeviceConnectorEp ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class CloudDeviceConnectorEpConsts:
CLAIM_STATE_CLAIMED = "claimed"
CLAIM_STATE_NONE = "none"
... |
## coding: utf-8
import pandas as pd
import numpy as np
import time
import math
from tqdm import tqdm
import matplotlib.pyplot as plt
from package.utils import KPIPoint
from package.utils import KPISet
from package.utils import Transformer
from package.HotSpot import HotSpot
def valid():
#### 加载数据集
# kSet_pre... |
from abc import abstractmethod
from sparkdq.repairs.transformers.Transformer import Transformer
class ComplexRepairer(Transformer):
@abstractmethod
def transform(self, data, state_provider=None, check=True):
pass |
import torch
import torch.nn.functional as F
from nemo.backends.pytorch.nm import LossNM
from nemo.core.neural_types import *
from nemo.utils.decorators import add_port_docs
class OnlineTripletLoss(LossNM):
"""
Online Triplet loss
Takes a batch of embeddings and corresponding labels.
Triplets are gene... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from __future__ import absolute_import, unicode_literals
from ctypes import byref, POINTER, c_char, c_uint32, c_float, c_int
from numpy import fromstring, ndarray
from threading import Thread, Lock, Condition
from Queue import Queue
from .core im... |
# coding=utf-8
# Copyright 2020 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... |
import blobconverter
import cv2
import depthai as dai
import numpy as np
class HostSync:
def __init__(self):
self.arrays = {}
def add_msg(self, name, msg):
if not name in self.arrays:
self.arrays[name] = []
self.arrays[name].append(msg)
def get_msgs(self, seq):
r... |
#-----Main Model File----#
class Model:
def __init__(self, data):
self.data = data
def preprocess(self):
self.data['License_Class'] = self.data['License_Class'].astype('category').cat.codes
train = self.data[self.data['year'] != 2021]
test = self.data[self.data['year'] == 20... |
# coding: utf-8
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environmen... |
#!/usr/bin/env python
#
# Quick and dirty script to convert a .kwlist.xml file to lowercase
# and hescii encode.
#
# Usage: hescii-downcase-kwlist.py infile.kwlist.xml > outfile.kwlist.xml
#
# Changes:
#
# March 12, 2013 Adam Janin
# Hyphens in keywords are not hesciied
import sys
import xml.etree.ElementTree as ET
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.