text stringlengths 2 999k |
|---|
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved.
# 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, co... |
# Importing essential libraries
from flask import Flask, render_template, request, redirect, url_for, flash
import pickle
import numpy as np
import joblib
from tensorflow.keras.models import load_model
from PIL import Image
import tensorflow as tf
app = Flask(__name__)
app.secret_key = 'O.\x89\xcc\xa0>\x96\xf7\x871\x... |
from django.test import TestCase
from django.db import models
from .models import Neighbourhood, Profile, Business, Post
from django.contrib.auth.models import User
class ProfileTestClass(TestCase):
# Set up method
def setUp(self):
self.user = User(username="Dorothy", password="password123")
se... |
# -*- coding: utf-8 -*-
from ctypes import (POINTER, cast, c_char, c_char_p, c_int, c_size_t, c_uint,
c_void_p, pointer)
import numpy as np
from pyfr.ctypesutil import LibWrapper
# Possible CUDA exception types
class CUDAError(Exception): pass
class CUDAInvalidValue(CUDAError): pass
class CUDAO... |
# -*- coding: utf-8 -*-
"""
Sequential Gaussian Simulation
Created on Sun Dec 4 2016
"""
from __future__ import absolute_import, division, print_function
__author__ = "yuhao"
import json
import os
import time
from collections import namedtuple
from itertools import product
import matplotlib.pyplot as plt
import num... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
#
# Collective Knowledge: CK-powered Caffe crowdbenchmarking (very early prototyping)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
cfg={} # Will be updated by CK (meta description of this module... |
"""
Module for storing & accessing symmetry group information, including
- Group class
- Wyckoff_Position class.
- Hall class
"""
# Imports ------------------------------
# Standard Libraries
import numpy as np
from pkg_resources import resource_filename as rf
from copy import deepcopy
import random
import ... |
import pytest
from starlette.routing import Route, WebSocketRoute
from starlette.endpoints import HTTPEndpoint, WebSocketEndpoint
from starlette.responses import PlainTextResponse
from starlette.testclient import TestClient
from lagom import injectable
from lagom.integrations.starlette import StarletteIntegration
c... |
#
# This is an example "pure python" uvicorn app.
#
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
await send({
'typ... |
# Copyright (c) 2021 MobileCoin. All rights reserved.
import logging
from timeit import default_timer
class TimerFactory(object):
def __init__(self, klass: str, logger: logging.Logger):
self.logger = logger
self.klass = klass
def get_timer(factory, name):
class Timer:
def... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import py... |
import argparse
import logging
import cv2 as cv
import librosa
import matplotlib.pylab as plt
import numpy as np
import torch
from config import sampling_rate
def clip_gradient(optimizer, grad_clip):
"""
Clips gradients computed during backpropagation to avoid explosion of gradients.
:param optimizer: o... |
##
## YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
##
## Copyright (C) 2002-2010 Aleph One Ltd.
## for Toby Churchill Ltd and Brightstar Engineering
##
## Created by Charles Manning <charles@aleph1.co.uk>
##
## This program is free software; you can redistribute it and/or modify
## it unde... |
#author : Simardeep Kaur
#date : 25 January, 2020
""" Runs classification model on the cleaned data to get the accuarcy on the test results
Usage: src/model.py --train_file=<train_file> --test_file=<test_file>
"""
import pandas as pd
import numpy as np
import altair as alt
from sklearn.ensemble import RandomForest... |
#!/usr/bin/env python
import argparse, struct, random
# Header format for use in struct
HEADER = '!16s16sII'
HEADER_SIZE = struct.calcsize(HEADER)
# Magic string to store in the header
MAGIC_STR = 'EnCrYpTRomFIle\x00\x00'
def main():
parser = argparse.ArgumentParser(description='Decrypt and encrypt setting ba... |
"""
An entity tracker
"""
from spockbot.mcdata.utils import Info
from spockbot.plugins.base import PluginBase, pl_announce
class MCEntity(Info):
eid = 0
status = 0
nbt = None
metadata = None
class MovementEntity(MCEntity):
x = 0
y = 0
z = 0
yaw = 0
pitch = 0
on_ground = True
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.utils.rnn import pad_sequence
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.layers import smooth_l1_loss, kl_div_loss, entropy_loss, La... |
'''
字典是一个非常有用的内置数据类型
列表是有序的,字典是无序的对象集合。区别:字典当中的元素是通过键存取,而不是通过下标存取
字典是一种映射类型,用 {} 标识, 它是一个无序的键值对集合
键必须使用不可变类型、在同一个字典中,键必须是唯一的。
字典有一些内置的功能函数,如:clear()、keys()、values() 等
注意:
1. 字典是一种映射类型,它的元素是键值对。
2. 创建空字典使用 {}
举例:
stu={'name':'jack', 'age': 20, 'sex': 'man'}
type(stu) # <class 'dict'>
print(stu['name']) # jack
stu['ph... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: modules/map/relative_map/proto/relative_map_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from ... |
#
# File : vsc.py
# This file is part of RT-Thread RTOS
# COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 ... |
"""Test util functions."""
import unittest
import os
from pywal import util
# Import colors.
COLORS = util.read_file_json("tests/test_files/test_file.json")
class TestUtil(unittest.TestCase):
"""Test the util functions."""
def test_read_file(self):
"""> Read colors from a file."""
result =... |
import unittest
class TfDictOp(object):
def __init__(self, ops_dict):
'''
ops_dict should be dict from strings to tensorflow ops
'''
self.indices = [name for name in ops_dict]
self.ops = [ops_dict[name] for name in self.indices]
'''
creates list of tensorflow operat... |
# 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 ... |
# Copyright 2021 The Funnel Rocket Maintainers
#
# 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... |
import os
from ddapp.consoleapp import ConsoleApp
from ddapp import ioUtils
from ddapp import segmentation
from ddapp import segmentationroutines
from ddapp import applogic
from ddapp import visualization as vis
#from ddapp import roboturdf
app = ConsoleApp()
# create a view
view = app.createView()
segmentation._d... |
# -*- coding: utf-8 -*-
"""Implementation of the ``wgs_mei_filtration`` step
This step takes annotated SVs as the input from ``wgs_mei_annotation`` and performs post-filtration
operations.
1. apply quality filter sets,
2. apply filters on the mode of inheritance, and
3. filter down the variants to specific regions.
... |
import numpy
import scipy.optimize as optim
import matplotlib.pyplot as plt
import pyolin.utils as utils
from math import log10 as log
from math import log as ln
from math import exp
class Gate:
def __init__(self, name, iptg, rpu_in, rpu_out):
self.iptg = iptg
self.rpu_in = rpu_in
self.r... |
from logging import Logger
from time import sleep
from os.path import exists
from os import remove
from invmonInfra.domain.loggerInterface import LoggerInterface
class DriverBase():
_logger: LoggerInterface
def __init__(self) -> None:
self.uri: str = ''
def driverGetContent(self) -> str:
... |
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import JsonResponse
from django.shortcuts import HttpResponse, HttpResponseRedirect, render
from django.urls import reverse
from django.... |
#!/usr/bin/env python
import rospy
import numpy
from geometry_msgs.msg import *
from mavros_msgs.srv import CommandBool
from mavros_msgs.srv import SetMode
from mavros_msgs.msg import State
current_state = State()
pose = PoseStamped()
vel = TwistStamped()
vel.twist.linear.x = 0
vel.twist.linear.y = 00
vel.twist.linea... |
from flask import current_app
from app import db
def mark_scan_dispatched(rescan):
rescan.dispatchTask()
db.session.add(rescan)
db.session.commit()
current_app.ScopeManager.updatePendingRescans()
current_app.ScopeManager.updateDispatchedRescans()
return
def mark_scan_completed(ip, scan_id):
dispatched = curr... |
#!/usr/bin/env python
import sys
import re
import requests
import os.path
from subprocess import check_call
try:
import hashlib
sha256 = hashlib.sha256
except ImportError: # Python < 2.5
# FIXME this is totally broken bec. I don't want to support legacy Python
# Maybe throw an error?
import sha
... |
from abc import ABC, abstractmethod
import torch
import scipy
import numpy as np
import librosa
windows = {'hamming': scipy.signal.hamming, 'hann': scipy.signal.hann, 'blackman': scipy.signal.blackman,
'bartlett': scipy.signal.bartlett}
class AudioParser(ABC):
"""
Abstract class for AudioParsers... |
from . import Field
from .compatibility import merge_validator
from ..validators import Type
class Object(Field):
"""Field used for nested objects.
It uses a mapping in order to know what class to load and the schema
used for the JSON representation.
"""
def __init__(self, schema, *args, **kwargs... |
# -*- coding: utf-8 -*-
'''
© 2012-2013 eBay Software Foundation
Authored by: Tim Keefer
Licensed under CDDL 1.0
'''
import platform
import logging
__version__ = '2.1.5'
Version = __version__ # for backward compatibility
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Han... |
import unittest
import json
import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
from Neo4jConnection import Neo4jConnection
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../../") # code directory
from RTXConfiguration import RTXConfigu... |
#!/usr/bin/env python3
import os
import kopf
import lib
import lib.pgbouncer
@kopf.on.startup()
async def startup(**_):
con = lib.connect_to_postgres()
con.close()
if lib.pgbouncer.enabled():
con = lib.pgbouncer.connect_to_postgres()
lib.pgbouncer.create_database(con)
con.close()
... |
# Generated by Django 4.0.2 on 2022-03-09 11:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('main', '0036_alter_materialcustomcurve_x_axis_type'),
]
operations = [
migrations.CreateModel(
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ideas', '0004_idea_category'),
]
operations = [
migrations.AddField(
model_name='idea',
name='status... |
import os
os.chdir("src")
try:
SAGE_SHARE = os.environ['SAGE_SHARE']
except KeyError:
raise RuntimeError("SAGE_SHARE undefined, maybe run `sage -sh`?")
def safe_makedirs(dir):
try:
os.makedirs(dir)
except OSError:
if not os.path.isdir(dir):
raise
def install_cremona():
... |
#!/usr/bin/env python3
import json
import mysql.connector
from flask import Flask,render_template
with open("config",'r') as file:
CONFIG = json.load(file)
app = Flask(__name__)
def hidefew(orig):
tot=[]
for i in range(len(orig)):
a=[]
for j in range(len(orig[i])):
if(j!=2):
... |
# coding: utf-8
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
:mod:`gfm` -- Base module for GitHub-Flavored Markdown
===============================... |
from functools import reduce
from rnnr import Event
from rnnr.attachments import LambdaReducer
def test_ok(runner):
outputs = [4, 2, 1, 5, 6]
batches = range(len(outputs))
@runner.on(Event.BATCH)
def on_batch(state):
state["output"] = outputs[state["batch"]]
r = LambdaReducer("product",... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from itertools import product, count
from matplotlib.colors import LinearSegmentedColormap
# it produce more vectors pointing diagonally than vectors pointing along
# an axis
# # generate uniform unit vectors
# def generate_unit_vectors(n)... |
"""
Genetic Algorithms for Digital Signal Processing
Created on Mon Oct 05 20:01:05 2020
Last Edited on Mon Oct 12 2020 by Luke Trenberth
"""
import numpy as np
from scipy import signal
from scipy.fftpack import fft
import matplotlib.pyplot as plt
import DSP_GA as ga
class DSP_Signal():
def __init__(s... |
import numpy as np
import libvictor as lv
from tqdm import tqdm_notebook
from tqdm import tqdm as tqdm_text
import pandas as pd
from collections import defaultdict
def make_pbar(verbose, notebook):
def dummy(x, **kwargs):
return x
if verbose: return tqdm_notebook if notebook else tqdm_text
return d... |
# Copyright 2020-present the HuggingFace Inc. team.
# Copyright (c) 2022 PaddlePaddle 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.o... |
from setuptools import setup, find_packages
with open('requirements.txt') as f:
requirements = f.read().splitlines()
with open("README.md", "r") as fh:
long_description = fh.read()
with open('.version') as f:
version = f.read()
setup(
name='fastai_audio',
author="Harry Coultas Blum",
autho... |
class Solution:
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
#初始化时, 使数组中预估数量都比最终数额大一, 也就是一个超过可能情况最大值的一个数量, 这样可以再无法组合的情况时用于判断返回-1
ret = [amount+1 for i in range(0, amount+1)]
for i in range(0... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 13:52:52 2021
@title: Random Walk With Noise
@author: Philip Bretz
"""
'''
The code below simulates a random walk with
noise. The Kalman filter is then applied to
the simulated data.
'''
import numpy as np
import example_models as ex
import kalman... |
import datetime
from dateutil.relativedelta import relativedelta
import urllib
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse, reverse_lazy
from django.db import ... |
"""Computation of the dissimilarity representation of a set of objects
(streamlines) from a set of prototypes (streamlines) given a distance
function. Some prototype selection algorithms are available.
See Olivetti E., Nguyen T.B., Garyfallidis, E., The Approximation of
the Dissimilarity Projection, http://dx.doi.org/... |
"""This module contains the general information for FabricFcEstcEpOperationFsm ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class FabricFcEstcEpOperationFsmConsts():
COMPLETION_TIM... |
""" 'editor' hooks for common editors that work well with ipython
They should honor the line number argument, at least.
Contributions are *very* welcome.
"""
from __future__ import print_function
import os
import pipes
import shlex
import subprocess
import sys
from IPython import get_ipython
from IPy... |
#!/usr/bin/env python
#coding=utf8
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")
import time
from .sample_common import MNSSampleCommon
from toralimns.account import Account
from toralimns.queue import *
#从sample.cfg中读取基本配置信息
## WARNING: Please do not hard code your acce... |
# Authors: Tom Lambert (lambertt) and Yuuma Odaka-Falush (odafaluy)
from __future__ import print_function
from pprint import pprint
from fraction_tests import test_fraction
from prime_tests import test_prime
from fraction import Fraction
import user
class Bruch(Fraction):
"""A derivative of the Fraction-class... |
from base64 import b64encode
from datetime import datetime, timezone, timedelta
from decimal import Decimal
from typing import Optional, Dict, List
import requests
from django import forms
from django.utils.translation import gettext as _
from rest_framework.request import Request
from stellar_sdk import Keypair
from... |
import argparse
import numpy as np
savepath = './save/'+ 'MyNet' + '.pt'
savepathPre = './save/' + 'MyNetPre' + '.pt'
def args():
parser = argparse.ArgumentParser(description='Train a GRU network.')
parser.add_argument('--T_min', default=10.0/1.0e3, type=float, help='Minimum allowed period of... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 20, ar_order = 12); |
"""PAYDUNYA DirectPay"""
from . import Payment
class DirectPay(Payment):
"""Directpay processing class
Receipient account_info format:
'{
"account_alias" : "774563209",
"amount" : 215000
}'
"""
def __init__(self, account_alias=None, amount=None):
self.transaction = {
... |
from datetime import datetime
from os.path import dirname, join
import pytest # noqa
from city_scrapers_core.constants import COMMITTEE, PASSED
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from city_scrapers.spiders.cle_transit import CleTransitSpider
test_response = file_res... |
"""
A tool for inspecting Python pickles
AUTHORS:
- Carl Witty (2009-03)
The explain_pickle function takes a pickle and produces Sage code that
will evaluate to the contents of the pickle. Ideally, the combination
of explain_pickle to produce Sage code and sage_eval to evaluate the code
would be a 100% compatible i... |
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division,
)
str = type('')
import os
os.environ['GPIOZERO_PIN_FACTORY'] = 'mock'
|
# Lint as: python3
# Copyright 2018, 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 ... |
from twosum import Solution
import unittest
class TestTwoSum(unittest.TestCase):
def setUp(self):
self.ts = Solution()
def test_small(self):
small = list(range(20))
target = 17 + 19
self.assertListEqual([17, 19], self.ts.twoSum(small, target))
def test_no_exist(self... |
import torch, torchvision
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import Bottleneck
import torch.backends.cudnn as cudnn
import torch.utils.model_zoo as model_zoo
from typing import List
from collections import defaultdict
import os
from backbone import construct_backbone
fr... |
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from .rbm import RBM
from .util import sample_bernoulli, sample_gaussian
tfd = tfp.distributions
dist = tfd.Normal(loc=0., scale=1.)
class RegRBM(RBM):
def __init__(self, n_visible, n_hidden, t=1e-3, lam=1e-3, sample_visible=False,... |
import pandas as pd
import numpy as np
import unittest
from unittest.mock import patch
from src.data.preprocessing import DataPreprocessor
class TestDataPreprocessor(unittest.TestCase):
def setUp(self):
self.dp = DataPreprocessor('extreme')
def test_read_data(self):
X, y = self.dp.read_data("... |
from .config import (
get_init_data,
get_default_config_file,
get_default_db_file,
get_default_local_dir,
update_config_file_location,
update_init_config,
update_config,
set_config,
get_config,
print_config,
make_file_dir,
)
__all__ = [
"get_init_data",
"get_default... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation
#
# 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 r... |
#!/usr/bin/env python3
# Copyright (c) 2017-2019 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 that the wallet can send and receive using all combinations of address types.
There are 5 nodes-u... |
from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired
from werkzeug import secure_filename
from fantacalcio.user.models import User
from flask_wtf.file import FileField
class LoginForm(Form):
username = TextField('Username', validators=[DataRequired()]... |
import nose
import sys
import os
import warnings
import tempfile
from contextlib import contextmanager
import datetime
import numpy as np
import pandas
import pandas as pd
from pandas import (Series, DataFrame, Panel, MultiIndex, Int64Index,
RangeIndex, Categorical, bdate_range,
... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012-today OpenERP SA (<http://openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... |
#Exercise 6-6 Polling
people = [
'claudia',
'vinicius',
'michel',
'valdson',
'ozzy'
]
polling = {
'claudia': 'python',
'vinicius': 'qlik sense',
'valdson': 'python'
}
print(
'-' * 10,
'POLLING',
'-' * 10
)
for person in people:
if person in polling:
print(
... |
#! /usr/bin/env python
import json
import os
import requests
import sys
from operator import itemgetter, attrgetter
REST_API="http://alpha.opencloud.us:8000/xos/"
NODES_API = REST_API + "nodes/"
SLICES_API = REST_API + "slices/"
SLIVERS_API = REST_API + "slivers/"
NETWORKSLIVERS_API = REST_API + "networkslivers/"
... |
# encoding=utf-8
__author__ = 'wdx'
import os
print os.path.dirname(__file__)
from celery import Celery
from msg_handler import MsgHandler
from core.processor_watcher import ProcessorWatcher
from watchdog.observers import Observer
from threading import Thread
app = Celery('tasks',backend='amqp', broker='amqp://')
ms... |
"""╭∩╮ʕ•ᴥ•ʔ╭∩╮."""
|
from scrapy.cmdline import execute
def run():
execute(["scrapy", "crawl", "stock", "-o", "items.json"])
if __name__ == "__main__":
run()
|
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COP... |
# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
#
# 说明:解集不能包含重复的子集。
#
# 示例:
#
# 输入: nums = [1,2,3]
# 输出:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/subsets
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import List
class... |
from unittest.mock import MagicMock, patch, call
import pytest
import numpy as np
import chainer
from chainer import Variable
from deep_sentinel.models.dnn.model import loss_calculator
chainer.global_config.train = False
chainer.global_config.enable_backprop = False
def to_variable(arr, astype=np.float32):
re... |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... |
import pandas as pd
import numpy as np
from scipy.stats import mode, gaussian_kde
from scipy.optimize import minimize, shgo
from sklearn.metrics import mean_squared_error as mse
from sklearn.metrics import mean_absolute_error as mae
from sklearn.model_selection import KFold,StratifiedKFold
from sklearn.metrics i... |
#
# RawIO
# Copyright (c) 2021 Yusuf Olokoba.
#
from PIL import Image
from pytest import fixture, mark
from rawio.align import align_level
IMAGE_PATHS = [
"test/media/level/3.jpg",
"test/media/level/9.jpg",
"test/media/level/16.jpg",
"test/media/level/53.jpg",
"test/media/level/69.jpg",
... |
# coding=utf-8
# Copyright 2019 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... |
# -*- coding: utf-8 -*-
'''
Setup of Python virtualenv sandboxes.
.. versionadded:: 0.17.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
# Import Salt libs
import salt.version
import salt.utils.functools
import salt.utils.platform
import sa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-10-24 17:59
from __future__ import unicode_literals
import django.core.files.storage
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operati... |
import unittest
import tests.lei.test_cons as test_cons
from lei.src.read_lei.read_transform_files import ParserJSON
class TestTakePath(unittest.TestCase):
def setup(self):
mock_dict = test_cons.lei_test
other_ent_names_tuple = (4,
[['001GPB6A9XPE8XJICC14', 'Jenni... |
from conans import ConanFile
class ArgsConan(ConanFile):
name = "args"
version = "6.2.0"
url = "https://github.com/Taywee/args"
description = "A simple header-only C++ argument parser library."
license = "MIT"
exports = ["LICENSE"]
exports_sources = "args.hxx"
def package(self):
... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import sys
from multiprocessing import Process, Value, Lock
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5;
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6... |
import numpy as np
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import UniformFloatHyperparameter, \
UniformIntegerHyperparameter
from autodc.components.models.base_model import BaseRegressionModel
from autodc.components.utils.constants import DENSE, SPARSE, UNSIG... |
#
# script.py
#
# This file is modified from python-bitcoinlib.
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Scripts
Functionality to build scripts, as well as SignatureHash().
"""
from __future__ import absolute_i... |
import envi
import envi.bits as e_bits
import struct
from disasm import H8ImmOper, H8RegDirOper, H8RegIndirOper, H8AbsAddrOper, H8PcOffsetOper, H8RegMultiOper, H8MemIndirOper
from regs import *
from const import *
bcc = [
('bra', envi.IF_NOFALL | envi.IF_BRANCH),
('brn', envi.IF_BRANCH | envi.IF_COND)... |
#!/usr/bin/env python
#
# aws_utils documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# 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.
#
# A... |
# Copyright (c) 2019, NVIDIA 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... |
# Copyright 2002 by Jeffrey Chang.
# Copyright 2016, 2019 by Markus Piotrowski.
# All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as par... |
from copy import copy
data = [
{
'id': 1,
'title': u'Discuss report with John',
'done': False
},
{
'id': 2,
'title': u'Get a haircut',
'done': True
},
{
'id': 3,
'title': u'Pay electricity bill',
'done': True
},
{
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.