content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
# Copyright 2020 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | examples/python/helloworld/async_greeter_server.py | 1,745 | The Python AsyncIO implementation of the GRPC helloworld.Greeter server.
Copyright 2020 gRPC 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 ... | 805 | en | 0.85179 |
import scipy.sparse as sp
import numpy as np
import torch
import time
import os
from configparser import ConfigParser
import sys
sys.path.append('/home/shiyan/project/gcn_for_prediction_of_protein_interactions/')
from src.util.load_data import load_data, sparse_to_tuple, mask_test_edges, preprocess_graph
from src.uti... | src/graph_nheads_att_gan/train.py | 9,490 | load config file data catalog path train file path model save/load path model param config 加载相关数据 去除对角线元素 下边的右部分为:返回adj_orig的对角元素(一维),并增加一维,抽出adj_orig的对角元素并构建只有这些对角元素的对角矩阵 返回D^{-0.5}SD^{-0.5}的coords, data, shape,其中S=A+I adj_label = sparse_to_tuple(adj_label) create model define optimizer 稀疏张量被表示为一对致密张量:一维张量和二维张量的索引。可以通... | 448 | zh | 0.654981 |
# Copyright 2019 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/LICENSE-2.0
#
# Unless required by applica... | tensorboard/plugins/hparams/backend_context_test.py | 14,082 | Sorts the repeated fields of an Experiment message.
Tests for backend_context.
Copyright 2019 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:/... | 942 | en | 0.76985 |
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
# Creat... | qa/rpc-tests/fundrawtransaction.py | 24,465 | !/usr/bin/env python2 Copyright (c) 2014-2015 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Create one-input, one-output, no-fee transaction: This test is not meant to test fee estimation and we'd like to ... | 2,671 | en | 0.800652 |
# Copyright (c) 2017, John Skinner
import unittest
import numpy as np
import arvet.database.tests.database_connection as dbconn
from arvet.config.path_manager import PathManager
import arvet.batch_analysis.task as task
class MockTask(task.Task):
def run_task(self, path_manager: PathManager):
pass
def... | arvet/batch_analysis/tests/test_task.py | 10,096 | Copyright (c) 2017, John Skinner Remove the collection as the start of the test, so that we're sure it's empty Clean up after ourselves by dropping the collection for this model Load all the entities Load all the entities Make sure that the node id and job id match the state | 275 | en | 0.922688 |
# coding: utf-8
"""
vautoscaling
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from ncloud_vautoscaling.model.process import Process # noqa: F401,E501
class ResumeProcessesResponse(object):
"""NOTE: This class is auto gene... | lib/services/vautoscaling/ncloud_vautoscaling/model/resume_processes_response.py | 6,146 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Returns true if both objects are equal
ResumeProcessesResponse - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the process_list of this ResumeProcessesResponse... | 2,047 | en | 0.548821 |
#!/usr/bin/env python3
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from . import css_checker
from os import path as os_path
import re
from sys import path as sys_path
import unittest
_HERE = os_path.d... | tools/web_dev_style/css_checker_test.py | 18,203 | !/usr/bin/env python3 Copyright 2015 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. | 177 | en | 0.867449 |
from typing import Dict, List, Optional
from db.sql.dal.general import sanitize
from db.sql.utils import query_to_dicts
class Region:
admin: str
admin_id: str
region_type: str
country: str
country_id: str
admin1: Optional[str]
admin1_id: Optional[str]
admin2: Optional[str]
admin2_i... | db/sql/dal/regions.py | 14,135 | Returns a list of admin1s. If country or country_id is specified, return the admin1s only of that country.
If admin1s or admin1_ids are provided, only those admins are returned.
If all arguments are empty, all admin1s in the system are returned.
Returns a list of admin2s. If admin1 or admin1_id is specified, return the... | 1,409 | en | 0.821192 |
# -*- coding: utf-8 -*-
import json
import csv
import scrapy
import re
from locations.items import GeojsonPointItem
COOKIES = {
"bm_sz": "04B124C1C96D68082A9F61BAAAF0B6D5~YAAQdjsvF22E8Xl6AQAACr1VfAxPEt+enarZyrOZrBaNvyuX71lK5QPuDR/FgDEWBZVMRhjiIf000W7Z1PiAjxobrz2Y5LcYMH3CvUNvpdS3MjVLUMGwMEBCf9L5nD5Gs9ho2YL8T7Tz7lY... | locations/spiders/aldi_uk.py | 3,783 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#!/usr/bin/env python
# vim: set sts=4 sw=4 et:
import time
import xmlrpc.client
from . import players
from . import rpc
from .common import GameState, CardSet, GameError, RuleError, ProtocolError, simple_decorator
from .events import EventList, CardPlayedEvent, MessageEvent, TrickPlayedEvent, TurnEvent, StateChangedE... | tupelo/xmlrpc.py | 4,427 | XML-RPC command line interface human player.
Client-side proxy object for the server/GameController.
Catch known exceptions and translate them to
XML-RPC faults.
Catch known XML-RPC faults and translate them to
custom exceptions.
Wait for this player's turn.
!/usr/bin/env python vim: set sts=4 sw=4 et: | 304 | en | 0.737045 |
import time
import numpy as np
import tensorflow as tf
import layers as L
import vat
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('device', '/gpu:0', "device")
tf.app.flags.DEFINE_string('dataset', 'cifar10', "{cifar10, svhn}")
tf.app.flags.DEFINE_string('log_dir', "", "log_dir")
tf.app.flags.DEFINE_inte... | train_semisup.py | 12,518 | at_loss = vat.adversarial_loss(x, y, nll_loss, is_training=False) losses['AT_loss'] = at_loss ul_u = random_sphere(ul_images.shape) ul_u_eval_train = random_sphere(ul_images_eval_train.shape) ul_u_eval_test = random_sphere(images_eval_test.shape) Build training graph Build eval graph np.random.choice(len(ul_images_np),... | 549 | en | 0.370548 |
"""
File: Milestone1.py
Name: 黃科諺
-----------------------
This file tests the milestone 1 for
our babyname.py project
"""
import sys
def add_data_for_name(name_data, year, rank, name):
name_info = {year: rank}
if name in name_data:
if year in name_data[name]:
exist_rank = int(name_data[na... | stanCode_projects/name_searching_system/milestone1.py | 2,448 | File: Milestone1.py
Name: 黃科諺
-----------------------
This file tests the milestone 1 for
our babyname.py project
------------- DO NOT EDIT THE CODE BELOW THIS LINE ---------------- | 183 | en | 0.511303 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from compas.utilities import await_callback
from compas_fab.backends.interfaces import AddCollisionMesh
from compas_fab.backends.ros.messages import ApplyPlanningSceneRequest
from compas_fab.backends.ros.messa... | src/compas_fab/backends/ros/backend_features/move_it_add_collision_mesh.py | 2,225 | Callable to add a collision mesh to the planning scene.
Add a collision mesh to the planning scene.
Parameters
----------
collision_mesh : :class:`compas_fab.robots.CollisionMesh`
Object containing the collision mesh to be added.
options : dict, optional
Unused parameter.
Returns
-------
``None`` | 307 | en | 0.356548 |
"""
libquantum example 3: 03_sweep_linear.py
Construct classic linear chirp and illustrate CWT and STFT TRFs.
"""
import os
from pathlib import Path
import numpy as np
import scipy.io.wavfile
import matplotlib.pyplot as plt
from libquantum import atoms, entropy, scales, spectra, utils, synthetics
import libquantum.plo... | examples/03_sweep_linear.py | 6,664 | libquantum example 3: 03_sweep_linear.py
Construct classic linear chirp and illustrate CWT and STFT TRFs.
Do you want to export a wav file? True or False If True, saves to home directory Or can specify a preferred wav file directory home_dir: str = "/Users/mgarces/Documents/DATA_API_M/synthetics" Chirp type sig_wf_sa... | 817 | en | 0.679039 |
# -*- coding: utf-8 -*-
from app.libs.utils import data_decode
import socket, socketserver, threading
import traceback
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
ip = ""
port = 0
timeOut = 100
def __init__(self, request, client_address, server):
from app.service.device i... | app/service/socketservice.py | 3,147 | -*- coding: utf-8 -*- time.sleep(1) server_thread.join() | 56 | en | 0.592302 |
from django.conf.urls import patterns, url
from django.contrib.contenttypes.models import ContentType
from kitsune.questions.feeds import (
QuestionsFeed, AnswersFeed, TaggedQuestionsFeed)
from kitsune.questions.models import Question, Answer
from kitsune.flagit import views as flagit_views
urlpatterns = pattern... | kitsune/questions/urls.py | 5,173 | AAQ AAQ flow for Marketplace TODO: Factor out `/(?P<question_id>\d+)` below Feeds Note: this needs to be above questions.list because "feed" matches the product slug regex. Mark as spam Question lists Flag content ("Report this post") Subcribe by email | 252 | en | 0.861757 |
# -*- coding: utf-8 -*-
# -*- coding: utf8 -*-
"""Autogenerated file - DO NOT EDIT
If you spot a bug, please report it on the mailing list and/or change the generator."""
from nipype.interfaces.base import (
CommandLine,
CommandLineInputSpec,
SEMLikeCommandLine,
TraitedSpec,
File,
Directory,
... | nipype/interfaces/slicer/filtering/extractskeleton.py | 2,515 | title: Extract Skeleton
category: Filtering
description: Extract the skeleton of a binary object. The skeleton can be limited to being a 1D curve or allowed to be a full 2D manifold. The branches of the skeleton can be pruned so that only the maximal center skeleton is returned.
version: 0.1.0.$Revision: 2104 $(al... | 1,006 | en | 0.777514 |
class Solution:
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
# max value taken as amount+1 because in worst case, it can be amount - when denoms of only 1
res = [amount+1]*(amount+1)
res[0] = 0
... | Session1_2018/coinChange.py | 572 | :type coins: List[int]
:type amount: int
:rtype: int
max value taken as amount+1 because in worst case, it can be amount - when denoms of only 1 | 154 | en | 0.789975 |
from interpolate import interpolate_doc
foo = """
hello
world
"""
bar = "foo bar\nbaz"
class Foo:
# cf matplotlib's kwdoc.
__kw__ = "the kw of foo"
@interpolate_doc
def func():
"""
this is a docstring
{interpolate_example.foo}
{bar}
{Foo!K}
"""
try:
@interpolat... | interpolate_example.py | 472 | fields {must} be preceded by whitespace
this is a docstring
{interpolate_example.foo}
{bar}
{Foo!K}
cf matplotlib's kwdoc. | 131 | en | 0.337323 |
import discord
from discord.ext import commands
# Set slash commands=True when constructing your bot to enable all slash commands
# if your bot is only for a couple of servers, you can use the parameter
# `slash_command_guilds=[list, of, guild, ids]` to specify this,
# then the commands will be much faster to upload.
... | examples/slash_commands.py | 1,343 | Set slash commands=True when constructing your bot to enable all slash commands if your bot is only for a couple of servers, you can use the parameter `slash_command_guilds=[list, of, guild, ids]` to specify this, then the commands will be much faster to upload. You can use commands.Option to define descriptions for yo... | 528 | en | 0.75143 |
#Python program to get the size of an object in bytes
import sys
Object = input("Enter any object: ")
print(f'The size of the object {Object} is {sys.getsizeof(Object)} bytes')
| GodwillOnyewuchi/Phase 1/Python Basic 2/day 9 task/task 9.py | 178 | Python program to get the size of an object in bytes | 52 | en | 0.871528 |
from importlib import import_module, reload
import pytest
import sys
from unittest.mock import patch
from rest_framework import status
from django.contrib.auth.models import Permission, Group
from django.conf import settings
from django.urls import clear_url_caches
from django.urls import reverse
from .factories imp... | tests/users/test_views.py | 15,847 | Test that URLs and redirects are in place.
We'll add the user to a group, as well as changing their details The user's details should have changed to reflect the posted values And they should have been added to a group Set this flag to True and repeat previous test Post changes to the view The users details should re... | 2,082 | en | 0.937307 |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
File Name: DbClient.py
Description : DB工厂类
Author : JHao
date: 2016/12/2
-------------------------------------------------
Change Activity:
2016/12/02: DB工厂类
... | db/dbClient.py | 3,708 | DbClient DB工厂类 提供get/put/update/pop/delete/exists/getAll/clean/getCount/changeTable方法
抽象方法定义:
get(): 随机返回一个proxy;
put(proxy): 存入一个proxy;
pop(): 顺序返回并删除一个proxy;
update(proxy): 更新指定proxy信息;
delete(proxy): 删除指定proxy;
exists(proxy): 判断指定proxy是否存在;
getAll(): 返回所有代理;
clean(): 清除所有proxy信息;
... | 933 | zh | 0.281846 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... | kubernetes/test/test_v1alpha1_priority_class.py | 1,002 | V1alpha1PriorityClass unit test stubs
Test V1alpha1PriorityClass
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
coding: utf-8 FIXME: construct object wit... | 442 | en | 0.550875 |
"""Forms related to import operations."""
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy
class ImportDataForm(forms.Form):
"""Base form to import objects."""
sourcefile = forms.FileField(label=ugettext_lazy("Select a file"))
sepchar ... | modoboa/admin/forms/import_.py | 1,358 | Base form to import objects.
A form to import identities.
Forms related to import operations. | 93 | en | 0.863236 |
from fork.util.ints import uint64
from .constants import ConsensusConstants
testnet_kwargs = {
"SLOT_BLOCKS_TARGET": 32,
"MIN_BLOCKS_PER_CHALLENGE_BLOCK": 16, # Must be less than half of SLOT_BLOCKS_TARGET
"MAX_SUB_SLOT_BLOCKS": 128, # Must be less than half of SUB_EPOCH_BLOCKS
"NUM_SPS_SUB_SLOT": 6... | fork/consensus/default_constants.py | 3,594 | Must be less than half of SLOT_BLOCKS_TARGET Must be less than half of SUB_EPOCH_BLOCKS Must be a power of 2 DIFFICULTY_STARTING is the starting difficulty for the first epoch, which is then further multiplied by another factor of DIFFICULTY_CONSTANT_FACTOR, to be used in the VDF iter calculation formula. The next diff... | 1,668 | en | 0.870912 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
import os.path
import sys
import io
import logging
import datetime
from pprint import pprint
import yaml
import tzlocal
class ConfigFileNotFound(Exception):
pass
def _set_default_config():
conf... | simiki/config.py | 2,349 | !/usr/bin/env python -*- coding: utf-8 -*- pylint: disable=pointless-string-statement | 85 | en | 0.470682 |
# Copyright 2018 The TensorFlow Probability 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... | tensorflow_probability/python/distributions/zipf_test.py | 16,076 | Copyright 2018 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri... | 1,198 | en | 0.806693 |
"""
Tensorflow implementation of DeepFM
"""
import numpy as np
import tensorflow as tf
import tensorflow.compat.v1 as tf1
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score
from time import time
from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm... | zzh/mllib/model/_deep_fm.py | 28,639 | :param Xi: list of list of feature indices of each sample in the dataset
:param Xv: list of list of feature values of each sample in the dataset
:param y: label of each sample in the dataset
:return: metric of the evaluation
:param Xi_train: [[ind1_1, ind1_2, ...], [ind2_1, ind2_2, ...], ..., [indi_1, indi_2, ..., indi... | 4,387 | en | 0.41271 |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
def create_user(**params):
return get_user_model(... | app/user/tests/test_user_api.py | 3,382 | The the user API (public)
Test that a token is created for a user
Test that token is not created if invalid credentials are given
Test that token is not created if email/password not given
Test that token is not created if user does not exist
Test creating user with valid payload is successful
tests that the password m... | 349 | en | 0.944946 |
# Copyright 2019 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
# Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
import subprocess
import re
import os
import glob
from utils.fileutils import FileUtils
from utils.ziputils import ZipUtils
from functools import w... | lib/command/PythonScripts/prebuild_lib.py | 7,094 | Copyright 2019 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file PREBUILD POD LIBS FLOW Normal build, it automatically: 1. Fetch binary cache from separated repo and unzip it to pod-binary folder. 2. pod-binary hook p... | 678 | en | 0.841177 |
#!/usr/bin/python
#
# Copyright (C) 2012 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of... | test/py/ganeti.tools.prepare_node_join_unittest.py | 8,681 | Script for testing ganeti.tools.prepare_node_join
!/usr/bin/python Copyright (C) 2012 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above c... | 1,352 | en | 0.863294 |
from ewah.hooks.base import EWAHBaseHook
import requests
import time
class EWAHAircallHook(EWAHBaseHook):
_ATTR_RELABEL = {
"api_id": "login",
"api_token": "password",
}
conn_name_attr = "ewah_aircall_conn_id"
default_conn_name = "ewah_aircall_default"
conn_type = "ewah_aircall"... | ewah/hooks/aircall.py | 2,250 | maximum page size is 50 | 23 | en | 0.781628 |
# python 3.7
"""Utility functions to invert a given image back to a latent code."""
from tqdm import tqdm
import cv2
import numpy as np
import torch
from models.stylegan_generator import StyleGANGenerator
from models.stylegan_encoder import StyleGANEncoder
from models.perceptual_model import PerceptualModel
__all__... | utils/inverter.py | 12,351 | Defines the class for StyleGAN inversion.
Even having the encoder, the output latent code is not good enough to recover
the target image satisfyingly. To this end, this class optimize the latent
code based on gradient descent algorithm. In the optimization process,
following loss functions will be considered:
(1) Pix... | 4,279 | en | 0.834534 |
"""
Copyright (c) 2017 Robbin Bouwmeester
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, di... | src/lpb.py | 12,476 | Copyright (c) 2017 Robbin Bouwmeester
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, ... | 1,597 | en | 0.877775 |
"""
Support for MQTT discovery.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/#discovery
"""
import asyncio
import json
import logging
import re
from homeassistant.components import mqtt
from homeassistant.components.mqtt import CONF_STATE_TOPIC,... | homeassistant/components/mqtt/discovery.py | 10,359 | Support for MQTT discovery.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/#discovery
If present, the node_id will be included in the discovered object id Dispatch update Add component | 258 | en | 0.845899 |
#!/usr/bin/python
import os
import json
def get_db_config():
# read config file and return data
data = {}
with open('config.json', 'r') as infile:
data = json.loads(infile.read())
return data
| Config.py | 217 | !/usr/bin/python read config file and return data | 49 | en | 0.496209 |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import re
from datetime import datetime
from uuid import uuid4
from .utils import normalize_package_name
from ..utils import (
create_file,
dir_exists,
ensure_parent_dir_exists,
path_joi... | datadog_checks_dev/datadog_checks/dev/tooling/create.py | 4,270 | (C) Datadog, Inc. 2018 All rights reserved Licensed under a 3-clause BSD style license (see LICENSE) | 100 | en | 0.846124 |
import numpy as np
import math
from chefboost.training import Training
#from training import Training
def processContinuousFeatures(algorithm, df, column_name, entropy, config):
#if True:
if df[column_name].nunique() <= 20:
unique_values = sorted(df[column_name].unique())
else:
unique_values = ... | chefboost/training/Preprocess.py | 5,212 | from training import Trainingif True:print(column_name,"->",unique_values)subset1_rows+subset2_rowsC4.5 also need gain in the block above. That's why, instead of else if we used direct if condition heresubset1 = high, subset2 = normalYes, No2Yes, Nodecision = Yeshigh, yesnormal, yes-------------------------------------... | 549 | en | 0.773259 |
import math
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
kaiming_init)
from mmcv.runner import load_checkpoint
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.utils import get_root_log... | detection/scrfd/mmdet/models/backbones/res2net.py | 12,675 | Res2Layer to build Res2Net style backbone.
Args:
block (nn.Module): block used to build ResLayer.
inplanes (int): inplanes of block.
planes (int): planes of block.
num_blocks (int): number of blocks.
stride (int): stride of the first block. Default: 1
avg_down (bool): Use AvgPool instead of str... | 3,313 | en | 0.652693 |
"""
eveparser.parsers.assets
~~~~~~~~~~~~~~~~~~~~~~~
Parse eve online asset lists. This also invludes inventory listings.
"""
import re
from eveparser.utils import regex_match_lines, f_int
ASSET_LIST_RE = re.compile(r"""^([\S ]*) # name
\t([\d,'\.]*) ... | eveparser/parsers/assets.py | 1,732 | Parse asset list
:param string paste_string: An asset list string
eveparser.parsers.assets
~~~~~~~~~~~~~~~~~~~~~~~
Parse eve online asset lists. This also invludes inventory listings. | 184 | en | 0.185505 |
import os
import platform
import threading
from asyncio import current_task, iscoroutinefunction
from collections.abc import Coroutine
from contextlib import AsyncExitStack
from datetime import datetime, timezone
from functools import partial
from logging import Logger, getLogger
from traceback import format_exc
from t... | apscheduler/workers/async_.py | 6,082 | Runs jobs locally in a task group.
Initialize the data store Start the actual worker Check if the job started before the deadline Set the job as running and publish a job update event | 185 | en | 0.883136 |
#!/usr/bin/env python3
import json
import os, sys, os.path
import string
from configparser import ConfigParser
J2_CONF_PATH='autobuild/configs/'
def write_file(filename, data):
with open(filename, "w") as fname:
json.dump(data, fname, indent = 4)
return
def get_wallet_conf(path):
wallet_conf_pars... | autobuild/create-j2-confs.py | 4,637 | !/usr/bin/env python3 get latest version get first of versions list of chain | 76 | en | 0.534959 |
"""
interface.py
DNAC parsers for the following show commands:
* /dna/intent/api/v1/interface
"""
import os
import logging
import pprint
import re
import unittest
from genie import parsergen
from collections import defaultdict
from ats.log.utils import banner
from genie.metaparser import MetaParser
from... | src/genie/libs/parser/dnac/interface.py | 3,509 | parser for /dna/intent/api/v1/interface, /dna/intent/api/v1/interface/{interface}
schema for /dna/intent/api/v1/interface, /dna/intent/api/v1/interface/{interface}
interface.py
DNAC parsers for the following show commands:
* /dna/intent/api/v1/interface
import parser utils ===========================================... | 559 | en | 0.306227 |
###############################################################################
# Name: __init__.py #
# Purpose: Import the required base modules needed for launching Editra into #
# into the namespace. #
... | dependencies/panda/Panda3D-1.10.0-x64/python/Lib/site-packages/wx-3.0-msw/wx/tools/Editra/src/__init__.py | 817 | Main package module
Name: __init__.py Purpose: Import the required base modules needed for launching Editra into into the namespace. Author: Cody Precord <cprecord@editra.org> ... | 433 | en | 0.597438 |
import pytest
from temp import (download_to_file, ensure_datafile, records_from_lines, make_record, make_value, min_spread_record,
min_spread_day_num, parse_header)
def test_download_to_file(tmpdir):
file = tmpdir.join('test.txt')
download_to_file(file.strpath, 'https://httpbin.org/get?testP... | python/kata04/test_temp.py | 2,014 | this one should be returned | 27 | en | 0.945119 |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy_splash import SplashRequest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import sys
from ..utils import extract_CN_from_content
from .... | spiders/a55_crawl.py | 4,343 | -*- coding: utf-8 -*- start_urls = ['http://fsx.sxxz.gov.cn/fsxzw/zwgk/xxgkzn/'] start_urls = ['http://fsx.sxxz.gov.cn/fsxzw/zwgk/jgsz_6342/'] def start_requests(self): for url in self.start_urls: yield scrapy.Request(url) if not isinstance(response, HtmlResponse): return | 288 | en | 0.403012 |
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class SpmHistoryEndHostHistoryGridRemote(RemoteModel):
"""
This table lists the end host history within the user specified period of time for a given end host.
| ``id:`` The internal NetMRI identifier of... | infoblox_netmri/api/remote/models/spm_history_end_host_history_grid_remote.py | 3,672 | This table lists the end host history within the user specified period of time for a given end host.
| ``id:`` The internal NetMRI identifier of the grid entry.
| ``attribute type:`` number
| ``FirstSeen:`` The timestamp of when NetMRI first discovered this end host.
| ``attribute type:`` datetime
| ``LastSeen... | 2,461 | en | 0.591793 |
# -*- Python -*-
import os
import platform
import re
import lit.formats
# Get shlex.quote if available (added in 3.3), and fall back to pipes.quote if
# it's not available.
try:
import shlex
sh_quote = shlex.quote
except:
import pipes
sh_quote = pipes.quote
def get_required_attr(config, attr_name):
attr_v... | compiler-rt/test/memprof/lit.cfg.py | 4,020 | -*- Python -*- Get shlex.quote if available (added in 3.3), and fall back to pipes.quote if it's not available. Setup config name. Platform-specific default MEMPROF_OPTIONS for lit tests. Setup source root. Setup default compiler flags used with -fmemory-profile option. FIXME: Review the set of required flags and check... | 535 | en | 0.75205 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2017-2020 Rhilip <rhilipruan@gmail.com>
import re
import time
from flask import Blueprint, request, jsonify
from app import mysql, app, cache
from pymysql import escape_string
ptboard_blueprint = Blueprint('ptboard', __name__)
search_default = app.config.get... | modules/ptboard/__init__.py | 4,958 | !/usr/bin/python3 -*- coding: utf-8 -*- Copyright (c) 2017-2020 Rhilip <rhilipruan@gmail.com> 1. Get user requests 2. Clean user requests Remove those too short letter 3. Get response data from Database 4. Sort Response data | 224 | en | 0.667763 |
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. 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 requir... | gcloud/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/zone_utils.py | 4,488 | A (small) collection of utils for working with zones.
Fetches zone resources.
Warns the user if a zone has upcoming deprecation.
Instantiate ZoneResourceFetcher and embed all required data into it.
ZoneResourceFetcher is a class depending on "base_classes"
class layout (properties side-derived from one of base_class c... | 1,629 | en | 0.770779 |
"""
Implementation of gaussian filter algorithm
"""
from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
from numpy import pi, mgrid, exp, square, zeros, ravel, dot, uint8
from itertools import product
def gen_gaussian_kernel(k_size, sigma):
center = k_size // 2
x, y = mgrid[0 - center : k_size -... | digital_image_processing/filters/gaussian_filter.py | 1,757 | Implementation of gaussian filter algorithm
dst image height and width im2col, turn the k_size*k_size pixels into a row and np.vstack all rows turn the kernel into shape(k*k, 1) reshape and get the dst image read original image turn image in gray scale value get values with two different mask size show result images | 320 | en | 0.69965 |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import re
import tensorflow as tf
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def load_graph(model_file, output_nodes_for_freeze=None):
is_meta = os.path.splitext(model_file)[-1] == ".meta"
tf.comp... | tests/layer_tests/common/utils/tf_utils.py | 4,327 | Copyright (C) 2018-2021 Intel Corporation SPDX-License-Identifier: Apache-2.0 | 77 | en | 0.245491 |
# content of test_electricity.py
from premise import DATA_DIR
from premise.electricity import Electricity
from premise.data_collection import IAMDataCollection
REGION_MAPPING_FILEPATH = (DATA_DIR / "regionmappingH12.csv")
PRODUCTION_PER_TECH = (DATA_DIR / "electricity" / "electricity_production_volumes_per_tech.csv")
... | tests/test_electricity.py | 1,815 | content of test_electricity.py | 30 | ceb | 0.232492 |
#!/usr/bin/python2.6
'''
Creates a MyU3 class that adds higher-level functionality to the base
LabJack U3 class.
'''
from __future__ import division
import u3
from time import sleep
import math
def getU3(**kargs):
'''Returns an open MyU3 object but retries until successful if errors occur.'''
while True:
... | readers/myU3.py | 4,553 | !/usr/bin/python2.6 call the constructor in the base class There are 1200 samples in one streaming request of the U3. Calculate the required streaming frequency from that and the other input parameters. cap at 50 kHz the U3 must operate at lower resolution if the streaming is very fast. 31 indicates single-ended read ... | 804 | en | 0.798266 |
import asyncio
import collections
import math
import signal
import sys
from functools import wraps
class Spy(object):
"""Spy is the debugging system for farc.
farc contains a handful of Spy.on_*() methods
placed at useful locations in the framework.
It is up to a Spy driver (such as the included VcdSp... | farc/__init__.py | 27,174 | An Augmented Hierarchical State Machine (AHSM); a.k.a. ActiveObject/AO.
Adds a priority, message queue and methods to work with the queue.
Framework is a composite class that holds:
- the asyncio event loop
- the registry of AHSMs
- the set of TimeEvents
- the handle to the next TimeEvent
- the table subscriptions to e... | 11,071 | en | 0.889679 |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: type_bank.py
@time: 2019-08-17 18:23
"""
from __future__ import unicode_literals
from flask_babel import lazy_gettext as _
from app_common.maps.default import DEFAULT_SEARCH_CHOICES_INT, DEFAULT_SELECT_CHOICES_INT
# 银行类型(1:基本账户,... | app_common/maps/type_bank.py | 741 | @author: zhanghe
@software: PyCharm
@file: type_bank.py
@time: 2019-08-17 18:23
!/usr/bin/env python encoding: utf-8 银行类型(1:基本账户,2:一般账户) 基本账户(对公) 一般账户(对公) 选择 搜索 | 161 | zh | 0.641331 |
"""
Django settings for mycalendar project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from path... | mycalendar/settings.py | 3,290 | Django settings for mycalendar project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
Build paths insi... | 1,129 | en | 0.631488 |
import logging
from Models import Values
from classes import PlayerActions, OnePosition
from ActionsDispatcher import Action
class PositionsManagerDBException(RuntimeError):
pass
class PositionsManager(object):
def __init__(self, models, accountId, logger=None):
self.models = models
self.accountId = accou... | apps/trade/src/PositionsManager.py | 2,726 | (tick: OneTick, position: OnePosition) -> float
Long, Profit Long, LossCut Short, Profit Short, LossCut | 105 | en | 0.685028 |
from django.contrib import admin
from user.models import *
# 此处设置页面头部标题
admin.site.site_title = '新码农站点后台'
# 此处设置页面显示标题
admin.site.site_header = '新码农后台管理系统'
@admin.register(User)
class Useradmin(admin.ModelAdmin):
list_display = ['id', 'username', 'password', 'nickname', 'birthday', 'gender', 'photo', 'phone', '... | apps/user/admin.py | 1,434 | 此处设置页面头部标题 此处设置页面显示标题 list_display_links 设置其他字段也可以点击链接进入编辑界面 list_editable 设置默认可编辑字段 date_hierarchy 详细时间分层筛选 list_display_links 设置其他字段也可以点击链接进入编辑界面 list_editable 设置默认可编辑字段 date_hierarchy 详细时间分层筛选 | 196 | zh | 0.922452 |
from typing import Optional, List
import autofit as af
import autoarray as aa
import autogalaxy as ag
from autogalaxy.aggregator.imaging import _imaging_from
from autogalaxy.aggregator.abstract import AbstractAgg
from autolens.imaging.fit_imaging import FitImaging
from autolens.analysis.preloads import Pre... | autolens/aggregator/fit_imaging.py | 4,646 | Wraps a PyAutoFit aggregator in order to create generators of fits to imaging data, corresponding to the
results of a non-linear search model-fit.
Returns a `FitImaging` object from a PyAutoFit database `Fit` object and an instance of galaxies from a non-linear
search model-fit.
This function adds the `hyper_model_ima... | 1,211 | en | 0.742335 |
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 14:25:43 2020
@author: greg6
"""
import numpy as np
t = [i for i in range(3)]
lam = [100+i*10 for i in range(2)]
com = ["A","B","C"]
S = dict()
for l in lam:
for u,c in enumerate(com):
S[(l,c)] = l+0.1*u
C = dict()
for i in t:
for u,c in enumerate(c... | Reduce_hessian/tests/B1.py | 930 | Created on Tue May 12 14:25:43 2020
@author: greg6
-*- coding: utf-8 -*- r_idx1 = k*nt+i r_idx2 = j * nc + k + nc * nw c_idx = i+j*nt print(j, k, r_idx2) try: | 161 | en | 0.690703 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mikeeiei.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _... | PyqtProject/test2.py | 5,388 | -*- coding: utf-8 -*- Form implementation generated from reading ui file 'mikeeiei.ui' Created by: PyQt4 UI code generator 4.11.4 WARNING! All changes made in this file will be lost! | 182 | en | 0.840449 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ModelBuilderRLF.py:
"""
__author__ = "Antonio Jesús Banegas-Luna"
__version__ = "1.0"
__maintainer__ = "Antonio"
__email__ = "ajbanegas@ucam.edu"
__status__ = "Development"
from BaseModelBuilder import BaseModelBuilder
class ModelBuilderRLF(BaseModelBuilder):
de... | Scripts/GridSearch/ModelBuilderRLF.py | 925 | ModelBuilderRLF.py:
!/usr/bin/env python -*- coding: utf-8 -*- | 63 | en | 0.380166 |
import warnings
from textwrap import indent
import astropy.units as u
import numpy as np
from astropy.constants import c
from astropy.coordinates import (ICRS,
CartesianDifferential,
CartesianRepresentation, SkyCoord)
from astropy.coordinates.spectral_q... | LI/lib/python3.8/site-packages/astropy/coordinates/spectral_coordinate.py | 31,863 | A spectral coordinate with its corresponding unit.
.. note:: The |SpectralCoord| class is new in Astropy v4.1 and should be
considered experimental at this time. Note that we do not fully
support cases where the observer and target are moving
relativistically relative to each other, so ca... | 12,238 | en | 0.696974 |
"""项目配置"""
# 图灵机器人,99元一月付费版,尽情享用!
tuling_api_key = '88f17f853d974387af64955bed9466f4'
# 自动回复
is_friend_auto_reply = False # 好友自动回复
is_group_reply = False # 此项表示群中是否回复
is_group_at_reply = False # 上一项开启后此项才生效
is_forward_revoke_msg = True # 开启防撤回模式
is_forward_group_at_msg = False # 转发群@我的消息
# 机器人主人
bot_master_name... | pyp/wxrobot-master/config.py | 1,349 | 项目配置
图灵机器人,99元一月付费版,尽情享用! 自动回复 好友自动回复 此项表示群中是否回复 上一项开启后此项才生效 开启防撤回模式 转发群@我的消息 机器人主人 使用备注名更安全,只允许一个,可远程控制机器人,如果不设置(空)则将文件助手设置为管理员,但不具备远程控制功能 监听某些好友群聊,如老板 需要监听的人名称,使用备注名更安全,允许多个用|分隔,如:主管|项目经理|产品狗 在这些群里监听好友说的话,匹配模式:包含“唯一集团工作群”的群 转发信息至群 打开转发模式,主人发送给机器人的消息都将转发至forward_groups群 需要将消息转发的群,匹配模式同上 群分享监控 监控群分享,匹配模式同上 | 309 | zh | 0.996618 |
# -*- coding: utf-8 -*-
#
# 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.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
# ... | docs/conf.py | 8,692 | -*- coding: utf-8 -*- 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. All configuration values have a default; values that are commented out serve to show the default. If extensions (or modules to docu... | 6,463 | en | 0.706732 |
# -*- coding: UTF-8 -*-
# Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
#
# You may assume no duplicates in the array.
#
# Here are few examples.
# [1,3,5,6], 5 → 2
# [1,3,5,6], 2 → 1
# [1,3,5,6], 7 → 4
# [1,3,5... | Python/SearchInsertPosition.py | 889 | :type nums: List[int]
:type target: int
:rtype: int
-*- coding: UTF-8 -*- Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5... | 395 | en | 0.81685 |
import math
import numpy as np
from kinematics.forward import ForwardKinematics
from kinematics.kinematics import Kinematics
from kinematics.solution import InverseKinematicsShoulderSolution, InverseKinematicsSpecificSolution, \
InverseKinematicsSolution, InverseKinematicsWristSolution
class InverseKinematics(K... | webots/controllers/ur_controller/kinematics/inverse.py | 17,766 | Theta 5 Theta 6 only using one of the theta 5's for now.. only using one of the theta 5's for now.. Theta 3Theta 1 | 114 | en | 0.836795 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
das developers note:
This a is modification of the original SpacePy pycdf package. All
refereneces to the greater spacepy package have been removed to create
a small standalone module.
--cwp 2018-10-18
The libcdf.so location code has been changed to f... | pycdf/__init__.py | 199,114 | An attribute, g or z, for a CDF
.. warning::
This class should not be used directly, but only in its
subclasses, :class:`gAttr` and :class:`zAttr`. The methods
listed here are safe to use in the subclasses.
Represents a CDF attribute, providing access to the Entries in a format
that looks like a Python
li... | 89,016 | en | 0.715627 |
# -*- coding: utf-8 -*- #
# Copyright 2016 Google LLC. 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 requir... | gcloud/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/containers_utils.py | 25,608 | Base exception for containers.
InvalidMetadataKeyException is for not allowed metadata keys.
Raised when COS image could not be found.
Raised on attempt to update-container on instance without containers.
Helper to create the metadata for konlet.
Create tags message with parameters for container VM or VM templates.
Dum... | 4,765 | en | 0.775296 |
#!/usr/bin/evn python
# -*- coding: utf-8 -*-
# python version 2.7.6
import magic
mime = magic.Magic(mime=True)
print mime.from_file("/Users/mac/Documents/data/fastq/8.fastq") | files/judgeFileType.py | 178 | !/usr/bin/evn python -*- coding: utf-8 -*- python version 2.7.6 | 63 | en | 0.363375 |
import tensorflow as tf
import tensorflow.contrib.distributions as tfd
import numpy as np
import os.path as opth
import tqdm
import os
from sklearn.utils import shuffle
import argparse
HOME = os.path.expanduser('~')
os.environ["CUDA_VISIBLE_DEVICES"] = "2";
layers = tf.keras.layers
parser = argparse.ArgumentParser()
... | wfi/cw/wfi-cw5.py | 17,454 | 5064 This is feature layer for FM loss !! 95 100 1000.0 300.0 40000 30000 Use AWF2 for unlabled setnp.concatenate(train_x_unlabeled)np.concatenate(train_y_unlabeled)np.concatenate(train_x_unlabeled2)np.concatenate(train_y_unlabeled2) 1) For supervised loss L1 distance of features is the loss for the generator We ... | 495 | en | 0.750142 |
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import hashlib
import json
import os
_ENV_DIR = '/var/db/factory/umpire'
_CONFIG_PATH = os.path.join(_ENV_DIR, 'active_umpire.json')
def SaveNewActive... | py/umpire/server/migrations/0010.py | 1,025 | Serialize and saves the configuration as new active config file.
Copyright 2018 The Chromium OS Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. | 225 | en | 0.907286 |
'''
Created by auto_sdk on 2021.03.10
'''
from dingtalk.api.base import RestApi
class OapiCateringUnfreezeRequest(RestApi):
def __init__(self,url=None):
RestApi.__init__(self,url)
self.order_id = None
self.rule_code = None
self.userid = None
def getHttpMethod(self):
return 'POST'
def getapiname(self):
... | other/dingding/dingtalk/api/rest/OapiCateringUnfreezeRequest.py | 361 | Created by auto_sdk on 2021.03.10 | 33 | en | 0.932703 |
# Autogenerated file.
from .client import MidiOutputClient # type: ignore
| jacdac/midi_output/__init__.py | 74 | Autogenerated file. type: ignore | 32 | en | 0.566038 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | nova/conductor/tasks/live_migrate.py | 8,138 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under th... | 1,026 | en | 0.856787 |
# Problem: N soldiers are standing in a circle and
# first person has sword and he kills the 2nd person
# and gives the sword to the third person and so on
# till 99th person kills the 100th person gives the
# sword back to the first person, this goes on till
# only one person survives. Print the survivor.
... | josephus.py | 865 | Problem: N soldiers are standing in a circle and first person has sword and he kills the 2nd person and gives the sword to the third person and so on till 99th person kills the 100th person gives the sword back to the first person, this goes on till only one person survives. Print the survivor. translated to zero-... | 456 | en | 0.861828 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.SettlementbillOpenApiDTO import SettlementbillOpenApiDTO
class AlipayBossFncSettleSettlementbillCreateResponse(AlipayResponse):
def __init__(self):
super... | alipay/aop/api/response/AlipayBossFncSettleSettlementbillCreateResponse.py | 1,004 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
# 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 ... | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_04_01/operations/_service_association_links_operations.py | 5,112 | ServiceAssociationLinksOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2019_04_01.mode... | 1,897 | en | 0.572301 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/securitycenter_v1beta1/proto/securitycenter_service.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 goo... | securitycenter/google/cloud/securitycenter_v1beta1/proto/securitycenter_service_pb2.py | 116,721 | -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.CreateFindingRequest) @@protoc_insertion_point(class_sc... | 2,446 | en | 0.266588 |
#!/usr/bin/env python3
import io
import unittest.mock
import yaz
class ConfigurationPlugin(yaz.Plugin):
"""This is the documentation string for the ConfigurationPlugin"""
choices = {
"yes": True,
"no": False,
"unknown": None,
}
@yaz.task(choice__choices=["yes", "no", "unknow... | yaz/test/test_task_configuration.py | 4,131 | This is the documentation string for the ConfigurationPlugin
This is the documentation for the multi_line_doc_string task
This is the long description, for example:
bla bla,
etc...
This is the documentation for the one_line_doc_string task
This is the documentation for the parameter_help task
This is the documentation... | 712 | en | 0.657508 |
# -*- coding: utf-8 -*-
# Copyright 2017 IBM RESEARCH. 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 requ... | qiskit/extensions/standard/rzz.py | 2,455 | Two-qubit ZZ-rotation gate.
Create new rzz gate.
Invert this gate.
Return OPENQASM string.
Reapply this gate to corresponding qubits in circ.
Apply RZZ to circuit.
two-qubit ZZ-rotation gate.
-*- coding: utf-8 -*- Copyright 2017 IBM RESEARCH. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "L... | 943 | en | 0.802659 |
import numpy as np
from sklearn.utils.testing import assert_array_almost_equal
from smoothot.projection import projection_simplex
def _projection_simplex(v, z=1):
"""
Old implementation for test and benchmark purposes.
The arguments v and z should be a vector and a scalar, respectively.
"""
n_fea... | smoothot/tests/test_projection.py | 1,623 | Old implementation for test and benchmark purposes.
The arguments v and z should be a vector and a scalar, respectively.
Axis = None case. Axis = 1 case. Check same as with for loop. Check works with vector z. Axis = 0 case. Check same as with for loop. Check works with vector z. | 282 | en | 0.896882 |
# Copyright 2019 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/LICENSE-2.0
#
# Unless required by applica... | tensorflow/python/data/experimental/benchmarks/parallel_interleave_benchmark.py | 3,862 | Benchmarks for `tf.data.experimental.parallel_interleave()`.
Returns a dataset that emulates a remote storage data source.
Returns a dataset factory which creates a dataset with 100 elements that
emulates the performance characteristic of a file-based dataset stored in a
remote storage. In particular, the first elemen... | 1,265 | en | 0.803969 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyStevedore(PythonPackage):
"""Manage Dynamic Plugins for Python Applications."""
hom... | var/spack/repos/builtin/packages/py-stevedore/package.py | 668 | Manage Dynamic Plugins for Python Applications.
Copyright 2013-2021 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT) | 238 | en | 0.68714 |
# Tradingview Technical Analysis (tradingview-ta)
# Author: deathlyface (https://github.com/deathlyface)
# Rewritten from https://www.tradingview.com/static/bundles/technicals.f2e6e6a51aebb6cd46f8.js
# License: MIT
class Recommendation:
buy = "BUY"
strong_buy = "STRONG_BUY"
sell = "SELL"
strong_sell = ... | tradingview_ta/technicals.py | 6,525 | Compute Average Directional Index
Args:
adx (float): ADX value
adxpdi (float): ADX+DI value
adxndi (float): ADX-DI value
adxpdi1 (float): ADX+DI[1] value
adxndi1 (float): ADX-DI[1] value
Returns:
string: "BUY", "SELL", or "NEUTRAL"
Compute Awesome Oscillator
Args:
ao (float): AO value
... | 2,248 | en | 0.3583 |
import os
import copy
import numpy as np
import click
from typing import List, Optional
import torch
import pickle
def extract_conv_names(model):
model_names = list(name for name in model.keys())
return model_names
def blend_models(low, high, model_res, level):
levels = [x for x in range(level)]
... | blend.py | 2,518 | start with lower model and add weights above print(name)-------------------------------------------------------------------------------------------------------------------------------------------------------- pylint: disable=no-value-for-parameter-------------------------------------------------------------------------... | 323 | en | 0.283464 |
# Copyright 2019 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | magenta/models/image_stylization/image_stylization_finetune.py | 6,947 | Trains an N-styles style transfer model on the cheap.
Training is done by finetuning the instance norm parameters of a pre-trained
N-styles style transfer model.
Copyright 2019 The Magenta Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the... | 1,176 | en | 0.848069 |
import cv2
import numpy as np
# Gray scale
def BGR2GRAY(img):
b = img[:, :, 0].copy()
g = img[:, :, 1].copy()
r = img[:, :, 2].copy()
# Gray scale
out = 0.2126 * r + 0.7152 * g + 0.0722 * b
out = out.astype(np.uint8)
return out
# LoG filter
def LoG_filter(img, K_size=5, sigma=3):
H, W, C = img.shape
... | Question_11_20/answers/answer_19.py | 1,432 | Gray scale Gray scale LoG filter zero padding LoG Kernel filtering Read image grayscale LoG filtering Save result | 113 | en | 0.469104 |
import logging
import os
import sys
import warnings
from collections import namedtuple
from typing import *
import matplotlib.image
import matplotlib.pyplot as plt
from torch import Tensor
from torch.utils.tensorboard import SummaryWriter
from booster import Diagnostic
from .datatracker import DataTracker
BestScore ... | booster/logging/logger.py | 6,118 | logFormatter = logging.Formatter('%(asctime)s %(name)-4s %(levelname)-4s %(message)s') fileHandler = logging.FileHandler(os.path.join(self.logdir, 'run.log')) fileHandler.setFormatter(logFormatter) self.logger.addHandler(fileHandler) consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setFormatter(logForm... | 399 | en | 0.176687 |
# Copyright (c) 2020 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.org/licenses/LICENSE-2.0
#
# Unless required by app... | python/paddle/tensor/linalg.py | 117,517 | Computes frequency of each value in the input tensor.
Args:
x (Tensor): A Tensor with non-negative integer. Should be 1-D tensor.
weights (Tensor, optional): Weight for each value in the input tensor. Should have the same shape as input. Default is None.
minlength (int, optional): Minimum number of bins. ... | 56,709 | en | 0.644022 |
# ---
# jupyter:
# jupytext:
# formats: ipynb,.pct.py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.3.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
... | doc/source/notebooks/understanding/models.pct.py | 10,545 | --- jupyter: jupytext: formats: ipynb,.pct.py:percent text_representation: extension: .py format_name: percent format_version: '1.3' jupytext_version: 1.3.3 kernelspec: display_name: Python 3 language: python name: python3 --- %% [markdown] Manipulating GPflow models One... | 6,687 | en | 0.799544 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... | kubernetes/test/test_v1_scale_io_persistent_volume_source.py | 1,088 | V1ScaleIOPersistentVolumeSource unit test stubs
Test V1ScaleIOPersistentVolumeSource
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
coding: utf-8 FIXME: ... | 485 | en | 0.423371 |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.ReduceOps import ReduceProd, ReduceAnd, ReduceMax, ReduceMean, ReduceSum, ReduceL2, ReduceMin
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.graph.graph import Node
clas... | tools/mo/openvino/tools/mo/front/tf/reduce_ext.py | 2,065 | Copyright (C) 2018-2021 Intel Corporation SPDX-License-Identifier: Apache-2.0 | 77 | en | 0.245491 |
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import ast
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
from collections import defaultdict
from nltk.stem import WordNetLemmatizer
import datetime
stop_words = stopwords.words('english')
lemmatizer = WordNet... | RA_project/code_python/image_score_posi.py | 5,095 | This computes the positivity score of each statement.
Takes a dictionary with each statement as liste item and the corresponding interlocutor's name in names item
plt.show()Cleaning | 185 | en | 0.662717 |
import socket
class UserException(Exception):
pass
def user_exception(s): raise UserException(s)
class Macro:
"""Represents a macro to be run"""
def __init__(self, code):
"""code: int - index of macro to run"""
self.code = code
class Command:
"""Represents a macro to be run"""
def __init__(self, ... | homevision_netio_controller/controller.py | 7,736 | Represents a macro to be run
Represents a macro to be run
code: int - index of macro to run
command: string - command to send
Args:
ip_address: string
port: int
auth: string
- key for authenticating with netio
on_off_appliance_codes: dict[string] => int - codes to be fed to 'on_off_commands' for each applia... | 1,812 | en | 0.688949 |
import os
import math
import sys
import torch
import numpy as np
from gym_collision_avoidance.envs.policies.InternalPolicy import InternalPolicy
from gym_collision_avoidance.envs import Config
from gym_collision_avoidance.envs.util import *
from gym_collision_avoidance.envs.policies import socialforce
import copy
i... | gym_collision_avoidance/envs/policies/SOCIALFORCEPolicy.py | 7,292 | Filter list by Boolean list Using itertools.compress check if elements before index contains non active agents, if yes, remove them, thus calculate the index shiftsee how many non active agents are before index, minus them calculate index shiftobservation array for social force, consist of N row of agents, each row =... | 2,356 | en | 0.608802 |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyDataladWebapp(PythonPackage):
"""DataLad extension for exposing commands via a web reque... | var/spack/repos/builtin/packages/py-datalad-webapp/package.py | 818 | DataLad extension for exposing commands via a web request API
Copyright 2013-2022 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT) | 252 | en | 0.630187 |
"""Simple quantum computations simulation."""
import numpy as np
def I():
"""Identity operator."""
return np.identity(2)
def X():
"""X-rotation, negation operator."""
return np.identity(2)[..., ::-1]
def H():
"""Adamara operator, superposition."""
return np.array([[1, 1], [1, -1]]) / np.sqrt(2)
def SW... | quantum.py | 1,060 | Controlled negation.
Adamara operator, superposition.
Identity operator.
Swap 2 qubits
X-rotation, negation operator.
Simple quantum computations simulation.
Usage example create 3 qubits in state 000, array size 2 ^ n transform the 2nd qubit into a superposition of 0 and 1 entangle the 1st and 2nd qubit swap the 2nd... | 352 | en | 0.757837 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.