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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python
import numpy as np
import datetime as dt
import sys, os, pickle, time
from keras.models import Model, save_model, load_model
from keras.regularizers import l2
from keras.optimizers import SGD, Adam
import keras.backend as K
import tensorflow as tf
import pandas as pd
import innvestigate
import in... | neural_network_lrp.py | 2,544 | !/usr/bin/env python NEURAL NETWORK PARAMETERS read data and reassign data types to float32 to save memory | 107 | en | 0.495952 |
#!/usr/bin/env python3
import torch
import torch.optim as optim
import os, sys
import warnings
import numpy as np
current_path = os.path.dirname(os.path.realpath(__file__))
PROJECT_HOME = os.path.abspath(os.path.join(current_path, os.pardir, os.pardir, os.pardir, os.pardir))
if PROJECT_HOME not in sys.path:
sys.p... | codes/f_main/trade_main/upbit_trade_main.py | 15,267 | !/usr/bin/env python3 NOTE NOTE | 32 | fr | 0.32425 |
import os
import warnings
warnings.filterwarnings("ignore")
shared_params = ('python CPT_STMeta_Simplify_Obj.py '
'--Dataset ChargeStation '
'--CT 6 '
'--PT 7 '
'--TT 4 '
'--GLL 1 '
'--LSTMUnits 64 '
... | Experiments/StabilityTest/Master_CS_0.py | 1,321 | 可以先选择在 DiDi-Xian, DiDi-Chengdu, Metro-Shanghai, ChargeStation-Beijing 这几个数据集上进行测试,因为耗时比较短 stability test | 104 | zh | 0.523839 |
# pylint: disable=redefined-outer-name
import asyncio
import time
import pytest
DEFAULT_MAX_LATENCY = 10 * 1000
@pytest.mark.asyncio
async def test_slow_server(host):
if not pytest.enable_microbatch:
pytest.skip()
A, B = 0.2, 1
data = '{"a": %s, "b": %s}' % (A, B)
time_start = time.time()... | tests/integration/api_server/test_microbatch.py | 1,764 | pylint: disable=redefined-outer-name | 36 | en | 0.375342 |
import os
import numpy as np
from scipy.stats import multivariate_normal
import inspect
from sklearn.metrics.pairwise import pairwise_distances
def sample(transition_matrix, means, covs, start_state, n_samples,
random_state):
n_states, n_features, _ = covs.shape
states = np.zeros(n_samples, dtype='... | deepblast/utils.py | 3,322 | Return path to filename ``fn`` in the data folder.
During testing it is often necessary to load data files. This
function returns the full path to files in the ``data`` subfolder
by default.
Parameters
----------
fn : str
File name.
subfolder : str, defaults to ``data``
Name of the subfolder that contains the d... | 881 | en | 0.838895 |
from transformers import RobertaConfig
from modeling.hf_head.modeling_roberta_parsing import RobertaForGraphPrediction
from modeling.sequence_labeling import SequenceLabeling
if __name__ == '__main__':
config = RobertaConfig(graph_head_hidden_size_mlp_arc=100, graph_head_hidden_size_mlp_rel=100, dropout_classifi... | parser.py | 630 | config.graph_head_hidden_size_mlp_arc = 100 1. GIVE IT TO PYTORCH LIGHTNING 2. DEFINE DATA MODULE FOR PARSING --> INPUT + LOSS: TRY TO FIT 3. Prediction (recover full graph after bpes- | 184 | en | 0.66232 |
"""
Defines useful extended internal coordinate frames
"""
import numpy as np
import McUtils.Numputils as nput
from McUtils.Coordinerds import (
ZMatrixCoordinateSystem, CartesianCoordinateSystem, CoordinateSystemConverter,
ZMatrixCoordinates, CartesianCoordinates3D, CoordinateSet, CoordinateSystemConverters... | Psience/Molecools/CoordinateSystems.py | 23,570 | Mirrors the standard Cartesian coordinate system in _almost_ all regards, but forces an embedding
...
...
Mirrors the standard ZMatrix coordinate system in _almost_ all regards, but forces an embedding
...
...
:param molecule:
:type molecule: AbstractMolecule
:param converter_options:
:type converter_options:
:param op... | 2,665 | en | 0.6465 |
# mypy: allow-untyped-defs
import os.path
from unittest.mock import patch
from tools.manifest.manifest import Manifest
from tools.wpt import testfiles
def test_getrevish_kwarg():
assert testfiles.get_revish(revish="abcdef") == "abcdef"
assert testfiles.get_revish(revish="123456\n") == "123456"
def test_ge... | tools/wpt/tests/test_testfiles.py | 2,424 | mypy: allow-untyped-defs Dependent affected tests are determined by walking the filesystem, which doesn't work in our test setup. We would need to refactor testfiles.affected_testfiles or have a more complex test setup to support testing those. | 244 | en | 0.943593 |
#!/usr/bin/env python
"""
_Exists_
Oracle implementation of JobGroup.Exists
"""
__all__ = []
from WMCore.WMBS.MySQL.JobGroup.Exists import Exists as ExistsJobGroupMySQL
class Exists(ExistsJobGroupMySQL):
pass
| src/python/WMCore/WMBS/Oracle/JobGroup/Exists.py | 219 | _Exists_
Oracle implementation of JobGroup.Exists
!/usr/bin/env python | 72 | en | 0.373402 |
from unittest import TestCase
from src.adders import HalfAdder, FullAdder, FourBitFullAdder
from tests.utils import decimal_to_boolean_list
class HalfAdderTests(TestCase):
TRUTH_TABLE = (
# A B S Cout
((False, False), (False, False)),
((False, True), (True, False)),
... | tests/test_adders.py | 2,880 | A B S Cout A B Cin S Cout Generate the truth table, since it is HUGE for a 4 bit adder Note: it will generate items like: (((False, True, False, False), (False, False, True, True)), (False, False, True, True, True)) and (((False, True, True, False), (False, True, True, True... | 564 | en | 0.548788 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from scrapy.spiders import Spider
from scrapy.spiders import Request
import json
from hexun.items import HexunItem
from utils.urlUtils import UrlUtils
from utils.dateTimeUtils import DateTimeUtils
class PPSpider(Spider):
name = 'pp'
urlTemplate = 'http://webftcn.herme... | hexun/hexun/spiders/ppSpider.py | 1,509 | !/usr/bin/python -*- coding: UTF-8 -*- | 38 | en | 0.437977 |
# Standard Library
import copy
import json
import re
from .log_helper import default_logger as logger
def format_cfg(cfg):
"""Format experiment config for friendly display"""
# json_str = json.dumps(cfg, indent=2, ensure_ascii=False)
# return json_str
def list2str(cfg):
for key, value in cfg... | up/utils/general/cfg_helper.py | 3,152 | Format experiment config for friendly display
bool, int, float, or str
Standard Library json_str = json.dumps(cfg, indent=2, ensure_ascii=False) return json_str json_str = [re.sub(r"(\"|,$|\{|\}|\[$|\s$)", "", line) for line in json_str if line.strip() not in "{}[]"] for hooks cfg = upgrade_fp16(cfg) | 303 | en | 0.249755 |
# Copyright 2020 StreamSets Inc.
#
# 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 writi... | pipeline/test_metrics.py | 2,643 | Ensure that we properly update metrics when the runner is in starting phase.
Copyright 2020 StreamSets Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENS... | 959 | en | 0.882916 |
#!/usr/bin/env python
#
# This program shows how to use MPI_Alltoall. Each processor
# send/rec a different random number to/from other processors.
#
# numpy is required
import numpy
from numpy import *
# mpi4py module
from mpi4py import MPI
import sys
def myquit(mes):
MPI.Finalize()
print(mes)
... | array/bot/others/P_ex07.py | 1,309 | !/usr/bin/env python This program shows how to use MPI_Alltoall. Each processor send/rec a different random number to/from other processors. numpy is required mpi4py module Initialize MPI and print out hello We are going to send/recv a single value to/from each processor. Here we allocate arrays Fill the send arrays... | 733 | en | 0.520106 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2016 Twitter. 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... | heron/instance/src/python/utils/topology/topology_context_impl.py | 11,290 | Implemention of TopologyContext
This is created by Heron Instance and passed on to the topology spouts/bolts
as the topology context
Registers a specified task hook to this context
:type task_hook: heron.instance.src.python.utils.topology.ITaskHook
:param task_hook: Implementation of ITaskHook
Returns the cluster con... | 3,339 | en | 0.738891 |
'''
Created on Sep 18, 2017
@author: jschm
'''
from cs115 import map
def powerset(lst):
"""returns the power set of the list - the set of all subsets of the list"""
if lst == []:
return [[]]
#power set is a list of lists
#this way is more efficent for getting the combinations of the characters ... | use_it_or_lose_it.py | 4,429 | returns the longest common string
returns the power set of the list - the set of all subsets of the list
determines whether or not it is possible to create target sum using the
values in the list. Values in teh list can be positive, negative, or zero.
Determines whether or not it is possible to create the target sum us... | 1,143 | en | 0.714085 |
# Copyright 2022 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/common/sequence_example_lib.py | 5,993 | Shuffles tensors in `input_tensors`, maintaining grouping.
Counts number of records in files from `file_list` up to `stop_at`.
Args:
file_list: List of TFRecord files to count records in.
stop_at: Optional number of records to stop counting at.
Returns:
Integer number of records in files from `file_list` up to ... | 2,591 | en | 0.805205 |
"""
gaeenv
~~~~~~~
Google App Engine Virtual Environment builder.
"""
import os
from setuptools import setup, find_packages
from gaeenv.main import gaeenv_version
def read_file(file_name):
return open(
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
file_name
)
... | setup.py | 1,214 | gaeenv
~~~~~~~
Google App Engine Virtual Environment builder. | 62 | en | 0.649132 |
# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa
import math
from enum import Enum
from typing import Callable, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.g... | kornia/contrib/face_detection.py | 15,353 | Detect faces in a given image using a CNN.
By default, it uses the method described in :cite:`facedetect-yu`.
Args:
top_k: the maximum number of detections to return before the nms.
confidence_threshold: the threshold used to discard detections.
nms_threshold: the threshold used by the nms for iou.
ke... | 2,491 | en | 0.741201 |
"""
Module Doc String
"""
EMOTIONS = [
"sentimental",
"afraid",
"proud",
"faithful",
"terrified",
"joyful",
"angry",
"sad",
"jealous",
"grateful",
"prepared",
"embarrassed",
"excited",
"annoyed",
"lonely",
"ashamed",
"guilty",
"surprised",
"no... | common.py | 626 | Driver
Module Doc String | 25 | en | 0.092294 |
from django.utils import translation
from django.utils.translation.trans_real import (
to_language as django_to_language,
parse_accept_lang_header as django_parse_accept_lang_header
)
from django.test import RequestFactory, TestCase
from django.urls import reverse
from .. import language_code_to_iso_3166, pars... | donate/core/tests/test_utils.py | 2,319 | Test that our overrides to Django translation functions work. | 61 | en | 0.880661 |
# global
import ivy
import abc
import importlib
from typing import List
# local
from ivy_builder.specs.spec import Spec
from ivy_builder.specs import DatasetSpec
from ivy_builder.specs.spec import locals_to_kwargs
# ToDo: fix cyclic imports, so this method can be imported from the builder module
def load_class_from_... | ivy_builder/specs/network_spec.py | 2,531 | base class for storing general specifications of the neural network
global local ToDo: fix cyclic imports, so this method can be imported from the builder module | 163 | en | 0.671608 |
# coding: utf-8
import pprint
import re
import six
class SetBackupPolicyRequestBody:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and t... | huaweicloud-sdk-dds/huaweicloudsdkdds/v3/model/set_backup_policy_request_body.py | 2,860 | Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
SetBackupPolicyRequestBody - a model defined in... | 808 | en | 0.817823 |
# -*- coding: utf-8 -*-
"""
Rewrite ot.bregman.sinkhorn in Python Optimal Transport (https://pythonot.github.io/_modules/ot/bregman.html#sinkhorn)
using pytorch operations.
Bregman projections for regularized OT (Sinkhorn distance).
"""
import torch
M_EPS = 1e-16
def sinkhorn(a, b, C, reg=1e-1, method='sinkhorn', m... | losses/bregman_pytorch.py | 17,062 | Solve the entropic regularization optimal transport
The input should be PyTorch tensors
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,C>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- C is the (ns,nt) metri... | 7,525 | en | 0.613419 |
# -*- coding: utf-8 -*-
# Copyright 2021 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
#############################################
# WARNING ... | venv/lib/python3.6/site-packages/ansible_collections/vyos/vyos/plugins/module_utils/network/vyos/argspec/route_maps/route_maps.py | 10,483 | The arg spec for the vyos_route_maps module
-*- coding: utf-8 -*- Copyright 2021 Red Hat GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) WARNING This file is auto generated by the cli_rm_builder. Manually editing this file is not advised. T... | 460 | en | 0.691623 |
# Database Lib
"""
Oracle
PostGresSQL
SQLite
SQLServer
Hive
Spark
"""
import os, datetime, pandas, time, re
from collections import namedtuple, OrderedDict
import jmespath
import sqlalchemy
from multiprocessing import Queue, Process
from xutil.helpers import (
log,
elog,
slog,
get_exception_message,
struct,... | xutil/database/base.py | 38,466 | Base class for database connections
SQL Express functions. Supports CRUD transactional operations.
Suppose there is a table named 'cache', sqlx allows:
sqlx.x('cache').insert(rows)
sqlx.x('cache').insert_one(row)
sqlx.x('cache').add(**kws)
sqlx.x('cache').delete(where)
sqlx.x('cache').update(rows, pk_fields)
sqlx.x('... | 2,784 | en | 0.484071 |
# flake8: noqa
# Disable Flake8 because of all the sphinx imports
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you un... | docs/conf.py | 16,080 | Configuration of Airflow Docs
flake8: noqa Disable Flake8 because of all the sphinx imports Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses thi... | 7,649 | en | 0.705281 |
# 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/v2020_08_01/operations/_routes_operations.py | 21,296 | RoutesOperations 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.v2020_08_01.models
:param client:... | 5,475 | en | 0.524519 |
"""
Makes python 2 behave more like python 3.
Ideally we import this globally so all our python 2 interpreters will assist in spotting errors early.
"""
# future imports are harmless if they implement behaviour that already exists in the current interpreter version
from __future__ import absolute_import, division, prin... | errorCheckTool/py23.py | 1,249 | Makes python 2 behave more like python 3.
Ideally we import this globally so all our python 2 interpreters will assist in spotting errors early.
future imports are harmless if they implement behaviour that already exists in the current interpreter version Override dict and make items() behave like iteritems() to reta... | 386 | en | 0.779591 |
import rebound
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
from sherlockpipe.nbodies.PlanetInput import PlanetInput
class StabilityCalculator:
def __init__(self, star_mass):
self.star_mass = star_mass
def mass_from_radius(self, radius):
... | experimental/megno.py | 2,958 | sim.status() integrate for 500 years, integrating to the nearest for i in range(500): sim.integrate(sim.t + i * 2 * np.pi) fig, ax = rebound.OrbitPlot(sim, color=True, unitlabel="[AU]", xlim=[-0.1, 0.1], ylim=[-0.1, 0.1]) plt.show() plt.close(fig)clear_output(wait=True)timestep for each output to keep t... | 1,252 | en | 0.287847 |
# -*- coding: utf-8 -*-
from __future__ import print_function
from acq4.devices.Device import *
from acq4.util import Qt
import acq4.util.Mutex as Mutex
from collections import OrderedDict
class LightSource(Device):
"""Device tracking the state and properties of multiple illumination sources.
"""
# emitte... | acq4/devices/LightSource/LightSource.py | 2,272 | Device tracking the state and properties of multiple illumination sources.
Return the names of all active light sources.
Return a description of the current state of all active light sources.
If onlyActive is False, then information for all sources will be returned, whether or not they are active.
Activa... | 591 | en | 0.775694 |
import asyncio
import dataclasses
import logging
import multiprocessing
from concurrent.futures.process import ProcessPoolExecutor
from enum import Enum
from typing import Dict, List, Optional, Set, Tuple, Union
from clvm.casts import int_from_bytes
from kujenga.consensus.block_body_validation import validate_block_b... | kujenga/consensus/blockchain.py | 42,131 | When Blockchain.receive_block(b) is called, one of these results is returned,
showing whether the block was added to the chain (extending the peak),
and if not, why it was not added.
Adds a block record to the cache.
Clears all block records in the cache which have block_record < height.
Args:
height: Minimum heigh... | 3,161 | en | 0.930704 |
class ListData():
def __init__(instance):
### INTERNAL PARAMETERS #############
instance.missing_data_character = " "
#####################################
instance.dataset = []
def headers(instance):
"""
Returns the first row of the instance.dataset
R... | preprocessor/ListData.py | 40,084 | :param new_column_values:
:param new_column_name:
:param dataset:
:return: Changes the inputted dataset when ran (no need for assigning the output to a variable).
:usage: append_column(NEW_COLUMN_VARIABLES_LIST, NEW_COLUMN_NAME_STRING, DATASET)
:example:
>>> my_list_data = ListData()
>>> my_list_data.dataset =... | 26,350 | en | 0.375172 |
"""[HTTPX](https://www.python-httpx.org/) 驱动适配
```bash
nb driver install httpx
# 或者
pip install nonebot2[httpx]
```
:::tip 提示
本驱动仅支持客户端 HTTP 连接
:::
FrontMatter:
sidebar_position: 3
description: nonebot.drivers.httpx 模块
"""
from typing import Type, AsyncGenerator
from contextlib import asynccontextmanager
fr... | nonebot/drivers/httpx.py | 2,033 | HTTPX Mixin
[HTTPX](https://www.python-httpx.org/) 驱动适配
```bash
nb driver install httpx
# 或者
pip install nonebot2[httpx]
```
:::tip 提示
本驱动仅支持客户端 HTTP 连接
:::
FrontMatter:
sidebar_position: 3
description: nonebot.drivers.httpx 模块
type: ignore | 253 | en | 0.330597 |
from flask import render_template, request, redirect, send_from_directory, jsonify, Blueprint
from direct_answers import choose_direct_answer
from direct_answers import search_result_features
import indieweb_utils
import search_helpers, config, search_page_feeds
import requests
import json
import math
import spacy
impo... | main.py | 10,101 | used for special jamesg.blog search redirect, not for open use If page cannot be converted into an integer, redirect to homepage this code doesn't work right now identify_mistakes = spell.unknown(cleaned_value.split('"')[-1].split(" ")) final_query = "" suggestion = False cleaned_items = cleaned_value.split('"')[-1].sp... | 809 | en | 0.701417 |
# 03_xkcd_multithread_download.py
# In dieser Übung geht es darum den Download der Comics zu beschleunigen
# indem man mehrere Threads zum downloaden nutzt.
import os, threading, requests, bs4
os.chdir(os.path.dirname(__file__))
target_dir='.\\comics'
source_url='https://xkcd.com'
# Prüfe ob Seite erreichbar
url_con... | Python/Buch_ATBS/Teil_2/Kapitel_15_Aufgaben_zeitlich_Planen_und_Programme_starten/03_xkcd_multithread_download/03_xkcd_multithread_download.py | 2,456 | 03_xkcd_multithread_download.py In dieser Übung geht es darum den Download der Comics zu beschleunigen indem man mehrere Threads zum downloaden nutzt. Prüfe ob Seite erreichbar Downloade die Comics als Thread Sammle die Links zu den Comics und den weiterführenden Seiten Starte Download-Thread Füge diesen Thread einer L... | 423 | de | 0.986979 |
# -*- coding: utf-8 -*- #
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | lib/surface/kms/keys/versions/list.py | 2,026 | List the versions within a key.
Lists all of the versions within the given key.
## EXAMPLES
The following command lists all versions within the
key `frodo`, keyring `fellowship`, and location `global`:
$ {command} --location global \
--keyring fellowship \
--key frodo
List the versions within a key.
... | 942 | en | 0.834972 |
# Create your views here.
from django.contrib.auth import get_user_model
from django.db import transaction
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django.utils.translation import ... | openbook_follows/views.py | 7,396 | Create your views here. | 23 | en | 0.928092 |
"""
本文件用以练习 manim 的各种常用对象
SVGMobject
ImageMobject
TextMobject
TexMobeject
Text
参考资料: https://www.bilibili.com/video/BV1CC4y1H7kp
XiaoCY 2020-11-27
"""
#%% 初始化
from manimlib.imports import *
"""
素材文件夹介绍
在 manim 中使用各种素材时可以使用绝对路径声明素材。
为了简单,可以创建 assets 文件夹并放置在 manim 路径下。
如此做,使用素材时可以不加路径。
... | manim/tutorial01_Mobjects.py | 5,248 | 本文件用以练习 manim 的各种常用对象
SVGMobject
ImageMobject
TextMobject
TexMobeject
Text
参考资料: https://www.bilibili.com/video/BV1CC4y1H7kp
XiaoCY 2020-11-27
%% 初始化%% SVGMobject 使用 class 创建一个场景,名字可自定义 这里 class 和 def 暂且当成是固定的套路吧 构造 SVGMobject --- 添加 SVG 图片 manim 内置部分颜色,参见 https://manim.ml/constants.htmlid7 SVGMobj... | 645 | zh | 0.896572 |
# Copyright 2017 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... | src/animal_detection/tf_api/core/box_predictor_test.py | 12,636 | Tests for object_detection.core.box_predictor.
Copyright 2017 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... | 709 | en | 0.823591 |
# 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 __future__ import print_function
import collections
import copy
import itertools
import os
import pprint
import sys
i... | lib/spack/spack/solver/asp.py | 61,361 | Object representing a piece of ASP code.
Result of an ASP solve.
Class to set up and run a Spack concretization solve.
Class with actions to rebuild a spec from ASP results.
Driver for the Python clingo interface.
Arguments:
cores (bool): whether to generate unsatisfiable cores for better
error reporting.
... | 10,785 | en | 0.86332 |
import logging
import sys
from notion.block import PageBlock
from notion.client import NotionClient
from requests import HTTPError, codes
from enex2notion.utils_exceptions import BadTokenException
logger = logging.getLogger(__name__)
def get_root(token, name):
if not token:
logger.warning(
... | enex2notion/cli_notion.py | 1,313 | pragma: no cover pragma: no cover Need empty account to test | 60 | en | 0.710923 |
from flask_testing import TestCase
from flask import url_for
from core import app, db
import unittest
from core.models import FeatureRequest, Client, ProductArea
import datetime
class BaseTest(TestCase):
SQLALCHEMY_DATABASE_URI = "sqlite://"
TESTING = True
def create_app(self):
app.config["TESTIN... | test_core.py | 13,555 | A reusable mixin that adds a client and a product area to the db
A reusable method for this class
A reusable method for this class
Make sure that the create page works
The create page should change the priorities of the other objects when a
new one has the same priority and client
The create page should return with err... | 1,273 | en | 0.886708 |
from .settings import *
RESPA_CATERINGS_ENABLED = True
RESPA_COMMENTS_ENABLED = True
RESPA_PAYMENTS_ENABLED = True
# Bambora Payform provider settings
RESPA_PAYMENTS_PROVIDER_CLASS = 'payments.providers.BamboraPayformProvider'
RESPA_PAYMENTS_BAMBORA_API_URL = 'https://real-bambora-api-url/api'
RESPA_PAYMENTS_BAMBORA_... | respa/test_settings.py | 608 | Bambora Payform provider settings API token auth endpoint | 57 | en | 0.344469 |
# Theory: Indexes
# There are several types of collections to store data in Python.
# Positionally ordered collections of elements are usually called
# sequences, and both lists and strings belong to them. EAch
# element in a list, as well as each character in a string, has an
# index that corresponds to its position.... | Computer science/Programming languages/Python/Working with data/Collections/Lists/Indexes/topic.py | 484 | Theory: Indexes There are several types of collections to store data in Python. Positionally ordered collections of elements are usually called sequences, and both lists and strings belong to them. EAch element in a list, as well as each character in a string, has an index that corresponds to its position. Indexes are ... | 463 | en | 0.970234 |
from __future__ import absolute_import
import requests
import json
import logging
from .base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
def ProviderParser(subparser):
subparser.description = '''
Zeit Provider requires a token to access its API.
You can generate one for ... | lexicon/providers/zeit.py | 5,843 | Implements the DNS Zeit provider. The API is quite simple: you can list all records, add one record or delete one record. - list is pretty straightforward: we get all records then filter for given parameters, - add uses directly the API to add a new record without any added complexity, - delete uses list + delete... | 821 | en | 0.833679 |
# Generated by Django 3.2.9 on 2022-01-01 10:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notes', '0003_auto_20220101_1040'),
]
operations = [
migrations.RenameField(
model_name='notes',
old_name='category'... | notes/migrations/0004_auto_20220101_1047.py | 636 | Generated by Django 3.2.9 on 2022-01-01 10:47 | 45 | en | 0.763604 |
import tkinter as tk
from tkinter import ttk
import json
from dashboard.entities.InputField import InputField
from dashboard.entities.StatusField import StatusField
class Devices(ttk.Frame):
"""
Devices Frame for Settings
"""
def __init__(self, parent, settings):
"""
Constructs a Warni... | dashboard/entities/Devices.py | 1,490 | Devices Frame for Settings
Constructs a WarningPopUp
:param parent: Parent Frame
:param settings: settings class
Removed current sidebar buttons Add sidebar buttons based on json | 183 | en | 0.677385 |
#!/usr/bin/env python3
# Copyright 2021 Xiaomi Corporation (Author: Liyong Guo, Fangjun Kuang)
#
# See ../../../../LICENSE for clarification regarding multiple 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 ... | egs/librispeech/ASR/conformer_mmi/decode.py | 22,952 | Decode dataset.
Args:
dl:
PyTorch's dataloader containing the dataset to decode.
params:
It is returned by :func:`get_params`.
model:
The neural model.
HLG:
The decoding graph. Used only when params.method is NOT ctc-decoding.
H:
The ctc topo. Used only when params.method is ctc-decoding.... | 4,816 | en | 0.812743 |
#!/usr/bin/env python
# -*- Mode: Python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*-
# vi: set ts=4 sw=4 expandtab:
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not us... | src/avm2/generated/generate.py | 2,996 | !/usr/bin/env python -*- Mode: Python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- vi: set ts=4 sw=4 expandtab: ***** BEGIN LICENSE BLOCK ***** Version: MPL 1.1/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file exce... | 1,781 | en | 0.842464 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TrafficWeight:
def __init__(self):
self.request = 0
self.response = 0
class PacketInterval:
def __init__(self):
self.firstPacket = 0
self.lastPacket = 0
| src/utils.py | 227 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
# Dana jest posortowana tablica A[1, ..., n] oraz liczba x. Proszę napisać program, który stwierdza
# czy istnieją indeksy i oraz j takie, że A[i] + A[j] = x.
def sum_search(T, x):
l = 0
r = len(T) - 1
while l <= r:
if T[l] + T[r] == x:
return True
elif T[l] + T[r] > x:
... | Exercises/Exercises_01/07_exercise.py | 466 | Dana jest posortowana tablica A[1, ..., n] oraz liczba x. Proszę napisać program, który stwierdza czy istnieją indeksy i oraz j takie, że A[i] + A[j] = x. | 154 | pl | 0.994844 |
# Generated by Django 2.2.12 on 2020-07-05 18:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vote', '0002_request_track'),
]
operations = [
migrations.AddField(
model_name='track',
name='metadata_locked',
... | nkdsu/apps/vote/migrations/0003_track_metadata_locked.py | 388 | Generated by Django 2.2.12 on 2020-07-05 18:03 | 46 | en | 0.535931 |
# IMPORTATION STANDARD
# IMPORTATION THIRDPARTY
import pytest
# IMPORTATION INTERNAL
from openbb_terminal.cryptocurrency.defi import terraengineer_model
@pytest.mark.vcr
@pytest.mark.parametrize(
"asset,address",
[("ust", "terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8")],
)
def test_get_history_asset_from_te... | tests/openbb_terminal/cryptocurrency/defi/test_terraengineer_model.py | 503 | IMPORTATION STANDARD IMPORTATION THIRDPARTY IMPORTATION INTERNAL | 64 | en | 0.66435 |
from __future__ import print_function
# Part of the JBEI Quantitative Metabolic Modeling Library (JQMM)
# Copyright (c) 2016, The Regents of the University of California.
# For licensing details see "license.txt" and "legal.txt".
from builtins import str
import re
import core
import NamedRangedNumber
class Gene(Name... | code/core/Genes.py | 7,887 | Class for single genes, and values typically associated with them.
Typically it is instantiated with a string representing a name, and a value.
Since genes can potentially have multiple names due to conflicting standards, the superclass also supports
receiving a list of names during instantiation, instead of a strin... | 3,307 | en | 0.848236 |
# Copyright 2019, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | tensorflow_federated/python/core/impl/executors/eager_tf_executor.py | 22,484 | The eager executor only runs TensorFlow, synchronously, in eager mode.
TODO(b/134764569): Add support for data as a building block.
This executor understands the following TFF types: tensors, sequences, named
tuples, and functions. It does not understand placements, federated, or
abstract types.
This executor unders... | 6,682 | en | 0.794006 |
import torch
import argparse
from bindsnet.network import Network
from bindsnet.learning import Hebbian
from bindsnet.pipeline import EnvironmentPipeline
from bindsnet.encoding import bernoulli
from bindsnet.network.monitors import Monitor
from bindsnet.environment import GymEnvironment
from bindsnet.network.topology ... | bindsnet_master/examples/breakout/random_network_baseline.py | 3,724 | Build network. Layers of neurons. Input layer Excitatory layer Readout layer Connections between layers. Input -> excitatory. Excitatory -> readout. Spike recordings for all layers. Voltage recordings for excitatory and readout layers. Add all layers and connections to the network. Add all monitors to the network. Load... | 346 | en | 0.789972 |
"""
Ensemble the predictions from different model outputs.
"""
import argparse
import json
import pickle
import numpy as np
from collections import Counter
from data.loader import DataLoader
from utils import scorer, constant
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('pred_files... | ensemble.py | 2,365 | Ensemble by majority vote.
Ensemble the predictions from different model outputs.
read predictions | 100 | en | 0.867509 |
import os
import sys
import shutil
import subprocess
from config import rfam_local as conf
from config import gen_config as gc
from utils import genome_search_utils as gsu
# ------------------------------------------------------------------------
def split_genome_to_chunks(updir, upid):
"""
updir:
upid... | scripts/support/split_genomes.py | 2,532 | ------------------------------------------------------------------------ get updir location check if we need to split the seq_file split sequence file into smalled chunks now index the fasta files for input consistency if the sequence file is small, copy it in the search_chunks directory copy file index file ----------... | 468 | en | 0.619726 |
#!/usr/bin/env python
"""Pathspecs are methods of specifying the path on the client.
The GRR client has a number of drivers to virtualize access to different objects
to create a Virtual File System (VFS) abstraction. These are called 'VFS
Handlers' and they provide typical file-like operations (e.g. read, seek, tell
a... | grr/lib/rdfvalues/paths.py | 10,292 | A glob expression for a client path.
A glob expression represents a set of regular expressions which match files on
the client. The Glob expression supports the following expansions:
1) Client attribute expansions are surrounded with %% characters. They will be
expanded from the client AFF4 object.
2) Groupings a... | 3,709 | en | 0.827563 |
#!/usr/bin/env python3
# Copyright (c) 2020 The Garliccoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''Test generateblock rpc.
'''
from test_framework.test_framework import GarliccoinTestFramework
from test_... | test/functional/rpc_generateblock.py | 5,521 | Test generateblock rpc.
!/usr/bin/env python3 Copyright (c) 2020 The Garliccoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Generate 110 blocks to spend Generate some extra mempool transactions to verify they don't... | 330 | en | 0.635099 |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | pybind/slxos/v17r_1_01a/routing_system/router/router_bgp/router_bgp_attributes/cluster_id/__init__.py | 11,443 | This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-common-def - based on the path /routing-system/router/router-bgp/router-bgp-attributes/cluster-id. Each member element of
the container is represented as a class variable - with a specific
YANG type.
Getter method for cluster_id_... | 1,476 | en | 0.646565 |
from django.contrib import messages, auth
from django.contrib.auth.decorators import login_required
from payments.forms import MakePaymentForm
from django.shortcuts import render, get_object_or_404, redirect
from django.core.urlresolvers import reverse
from django.template.context_processors import csrf
from django.con... | payments/views.py | 1,691 | service = get_object_or_404(Service, pk=id) | 43 | en | 0.565954 |
#!/usr/bin/env python2.7
# William Lam
# wwww.virtuallyghetto.com
#
# 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... | samples/set_vcenter_motd.py | 2,935 | !/usr/bin/env python2.7 William Lam wwww.virtuallyghetto.com 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... | 984 | en | 0.848623 |
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
data=pd.read_csv(path)
#Code starts here
data.rename(columns={'Total':'Total_Medals'},inplace=True)
# Data Loading
data['Better_Event'] = np.where(data['Tota... | code.py | 2,668 | --------------Importing header filesPath of the file is stored in the variable pathCode starts here Data Loading Summer or Winter Top 10 Plotting top 10 Top Performing Countries Best in the world Plotting the best | 215 | en | 0.65079 |
from functools import partial as curry
from django import forms
from django.utils import timezone
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from pinax.images.models import ImageSet
from mdeditor.fields import MDTextFormField
from .conf import settings
from .models... | pinax/blog/forms.py | 4,090 | set initial data from the latest revision | 41 | en | 0.564377 |
from mininet.topo import Topo
class Project1_Topo_0866007(Topo):
def __init__(self):
Topo.__init__(self)
# Add hosts
h1 = self.addHost('h1', ip='192.168.0.1/24')
h2 = self.addHost('h2', ip='192.168.0.2/24')
h3 = self.addHost('h3', ip='192.168.0.3/24')
h4 = self.add... | project1_0866007/bonus_0866007.py | 815 | Add hosts Add switches Add links | 32 | en | 0.637601 |
# Copyright 2011 Google Inc.
#
# 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,... | src/osx_trace_test.py | 3,284 | Copyright 2011 Google Inc. 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 distribu... | 605 | en | 0.843199 |
import datetime
from django.contrib.syndication import feeds, views
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from django.utils import tzinfo
from django.utils.feedgenerator import rfc2822_date, rfc3339_date
from models import Entry
from xml.dom import minidom
try:
se... | tests/regressiontests/syndication/tests.py | 13,237 | Tests for the deprecated API (feed() view and the feed_dict etc).
Tests for the high-level syndication feed framework.
Test add_domain() prefixes domains onto the correct URLs.
Test the structure and content of feeds generated by Atom1Feed.
Test that datetimes with timezones don't get trodden on.
Tests that the base ur... | 1,694 | en | 0.875619 |
"""
Provides linkedin api-related code
"""
import random
import logging
from time import sleep
import json
from linkedin_api.utils.helpers import get_id_from_urn
from linkedin_api.client import Client
logger = logging.getLogger(__name__)
class Linkedin(object):
"""
Class for accessing Linkedin API.
"""... | linkedin_api/linkedin.py | 19,287 | Class for accessing Linkedin API.
Return data for a single company.
[public_id] - public identifier i.e. univeristy-of-queensland
"
Return a list of company posts
[public_id] - public identifier ie - microsoft
[urn_id] - id provided by the related URN
Return the full conversation at a given [conversation_urn_id]
Retu... | 2,242 | en | 0.842029 |
import os
import sys
sys.path.append(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
)
from src.DbHelper import DbHelper
persons = [
'Lucy',
'Franz',
'Susanne',
'Jonathan',
'Max',
'Stephan',
'Julian',
'Frederike',
'Amy',
'Miriam... | src/Simple_Fraud_Detection/solution/01_fill_fraud_db_with_nodes.py | 1,660 | See https://neo4j.com/developer/aura-connect-driver/ for Aura specific connection URL. Connecting to Aura, use the "neo4j+s" URI scheme Bolt Port https://neo4j.com/docs/operations-manual/current/configuration/ports/ | .NET | Java | JavaScript | Go | Python | 256 | en | 0.743682 |
# Keypirinha launcher (keypirinha.com)
import keypirinha as kp
import keypirinha_util as kpu
import keypirinha_net as kpnet
import json
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
from faker import Faker
class FakerData(kp.Plugin):
ITEMCAT = kp.ItemCategory.USER_BASE + 1
ITEMRE... | src/fakerdata.py | 3,462 | Keypirinha launcher (keypirinha.com) The default ammount of suggestions to show after the user selected the faker category The default language used to instantiate Faker Generate outputs We don't want to generate the output each time the user enter a new query Let's keep the output, so this way Keypirinha itself can fi... | 396 | en | 0.775254 |
from queue import Queue, Empty, Full
from ..core import DriverBase, format_msg
import pika
class Driver(DriverBase):
def __init__(self, exchange, queue, routing_key=None, buffer_maxsize=None,
*args, **kwargs):
super().__init__()
self._args = args
self._kwargs = kwargs
... | piot/outputs/amqp.py | 2,154 | Flush buffer Add to buffer | 26 | en | 0.571851 |
# -*- coding: utf-8 -*-
import subprocess
def test_too_many_arguments_in_fixture(absolute_path):
"""
End-to-End test to check arguments count.
It is required due to how 'function_type' parameter
works inside 'flake8'.
Otherwise it is not set, unit tests can not cover `is_method` correctly.
... | tests/test_checkers/test_high_complexity.py | 623 | End-to-End test to check arguments count.
It is required due to how 'function_type' parameter
works inside 'flake8'.
Otherwise it is not set, unit tests can not cover `is_method` correctly.
-*- coding: utf-8 -*- | 215 | en | 0.638676 |
import itertools
try:
import theano
import theano.tensor as T
from theano.gradient import disconnected_grad
except ImportError:
theano = None
T = None
from ._backend import Backend
from .. import make_graph_backend_decorator
class _TheanoBackend(Backend):
def __init__(self):
super().... | pymanopt/autodiff/backends/_theano.py | 4,274 | Returns a function accepting `2 * len(arguments)` arguments to
compute a Hessian-vector product of a multivariate function.
Notes
-----
The implementation is based on TensorFlow's '_hessian_vector_product'
function in 'tensorflow.python.ops.gradients_impl'.
Returns a function accepting two arguments to compute a
Hessi... | 649 | en | 0.735338 |
#!-*-coding:utf-8-*-
import sys
# import PyQt4 QtCore and QtGui modules
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtCore
from pylinac import VMAT
from dmlc import Ui_MainWindow
class DirectoryPath(object):
def __init__(self, pathDir, getCountImages):
self._pathDir = pathDi... | VMAT/Dmlc/main.py | 4,151 | MainWindow inherits QMainWindow
!-*-coding:utf-8-*- import PyQt4 QtCore and QtGui modules ----------------------------------------------------- create application create widget connection QObject.connect( app, SIGNAL( 'lastWindowClosed()' ), app, SLOT( 'quit()' ) ) execute application | 286 | en | 0.353619 |
import numpy as np
import pickle
import math
try:
from utilities import dot_loss, next_batch
except ImportError:
from utilities.utilities import dot_loss, next_batch
class DontCacheRef(Exception):
pass
class BasicConverter(object):
def __init__(self, learning_rate = 0.05, batch_size = 1, num_epochs =... | nndrone/converters.py | 12,628 | training control training history Return the cached list of reference outputs for the base model Create the list of reference outputs for the base model this will match if original model was trained with correct dimensionality Get the list of reference outputs for the base model to inflate the learning without change i... | 2,097 | en | 0.887515 |
import emoji
emoji.emojize('\:sunglasses:?')
#Transformação #Comentário
String['Curso em Videos Python']
frase[9:13]
frase[9:21:2]
frase[:5]
frase[15:]
frase[9::3]
#Aula Curso Em Video Python 9 => revisão 2 [13/07/2020 14h00m]
#Funcionalidades de Trasnformação
Objeti.Methodo() #Comentário
frase.fi... | natural-languages-python.py | 876 | Transformação ComentárioAula Curso Em Video Python 9 => revisão 2 [13/07/2020 14h00m]Funcionalidades de TrasnformaçãoComentárioAcha, buscaAcha, buscaSubistuitudo em minusculotudo maiusculo o lado direito "r" é uma keyword de direita strip vai remover os, somente os espaços da esquerda keyword "r"Funcionalidade Divisão ... | 429 | pt | 0.988508 |
_HAS_OPS = False
def _register_extensions():
import os
import imp
import torch
# load the custom_op_library and register the custom ops
lib_dir = os.path.dirname(__file__)
_, path, _ = imp.find_module("_C", [lib_dir])
torch.ops.load_library(path)
try:
_register_extensions()
_HAS... | torchvision/extension.py | 1,581 | Make sure that CUDA versions match between the pytorch install and torchvision install
load the custom_op_library and register the custom ops | 143 | en | 0.823146 |
# Copyright 2018 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_io/hadoop/python/ops/hadoop_dataset_ops.py | 2,501 | A Sequence File Dataset that reads the sequence file.
Create a `SequenceFileDataset`.
`SequenceFileDataset` allows a user to read data from a hadoop sequence
file. A sequence file consists of (key value) pairs sequentially. At
the moment, `org.apache.hadoop.io.Text` is the only serialization type
being supported, and ... | 1,428 | en | 0.740516 |
# Copyright (c) 2018 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/fluid/tests/unittests/test_while_op.py | 2,853 | Copyright (c) 2018 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 applicable law or agree... | 583 | en | 0.863545 |
from models.joint_fpn import JointFpn
from trainers.segmentation_trainer import SegmentationTrainer
from data_generators.joint_data_generator import JointDataGenerator
from data_generators.scenenet_rgbd_data_generator import ScenenetRGBDDataGenerator
from utils.config import process_config
from utils.dirs import create... | train_joint.py | 1,975 | capture the config path from the run arguments then process the json configuration file use mixed precision for training create the experiments dirs | 148 | en | 0.548635 |
# coding: utf-8
import warnings
import numpy as np
import pandas as pd
from packaging import version
from sklearn.metrics import pairwise_distances_chunked
from sklearn.utils import check_X_y,check_random_state
from sklearn.preprocessing import LabelEncoder
import functools
from pyclustering.cluster.clarans import cla... | clust_indices.py | 6,800 | coding: utf-8 They changed the name of calinski_harabaz_score in later version of sklearn: https://github.com/scikit-learn/scikit-learn/blob/c4733f4895c1becdf587b38970f6f7066656e3f9/doc/whats_new/v0.20.rstid2012 accumulate distances from each sample to each cluster intra_index selects intra-cluster distances within clu... | 652 | en | 0.776842 |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
from common.onnx_layer_test_class import Caffe2OnnxLayerTest
class TestImageScaler(Caffe2OnnxLayerTest):
def create_net(self, shape, scale, ir_version):
"""
ONNX net ... | tests/layer_tests/onnx_tests/test_image_scaler.py | 5,106 | ONNX net IR net
Input->ImageScaler->Output => Input->ScaleShift(Power)
ONNX net IR net
Input->Concat(+scaled const)->Output => Input->Concat(+const)
Copyright (C) 2018-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 Create ONNX mod... | 514 | en | 0.206604 |
lista = ['item1', 'item2', 'item3', 123, 12.43, 898.34, 00.989]
print(lista)
del lista[0] # pode remover tudo ou apenas um item de um indice permanentemente
popped = lista.pop(0) #pode remover um item pelo indice de uma lista, porem o item tirado pode ser posto em uma variavel
lista.remove('item3') # pode remover um it... | python/cursoemvideo-python/03-mundo-3/listas/lista 1/listas.py | 1,318 | pode remover tudo ou apenas um item de um indice permanentementepode remover um item pelo indice de uma lista, porem o item tirado pode ser posto em uma variavel pode remover um item pelo valor / remove o primeiro valor da lista list cria uma lista coloca os itens de forma ordenada em uma lista permanentemente faz o me... | 659 | pt | 0.997352 |
import random
### Advantage Logic ###
def advantage(rollfunc):
roll1 = rollfunc
roll2 = rollfunc
if roll1 > roll2:
return roll1
else:
return roll2
### Disadvantage Logic ###
def disadvantage(rollfunc):
roll1 = rollfunc
roll2 = rollfunc
if roll1 < roll2:
return roll1
... | DieRolls.py | 746 | Advantage Logic Disadvantage Logic Die Rolls | 46 | en | 0.589802 |
# Copyright 2021 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 in wr... | legate/pandas/frontend/accessors.py | 3,547 | Copyright 2021 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 in writing, software di... | 555 | en | 0.858923 |
"""
This is the UGaLi analysis sub-package.
Classes related to higher-level data analysis live here.
Modules
objects :
mask :
"""
| ugali/analysis/__init__.py | 148 | This is the UGaLi analysis sub-package.
Classes related to higher-level data analysis live here.
Modules
objects :
mask : | 138 | en | 0.716722 |
from keras.models import Sequential, load_model
from keras.layers.core import Dense, Dropout, Activation,Flatten
from keras.layers.recurrent import LSTM, GRU, SimpleRNN
from keras.layers.convolutional import Convolution2D, Convolution1D, MaxPooling2D, MaxPooling1D, AveragePooling2D
from keras.layers.normalization impor... | test_gen_spec.py | 3,080 | "weights/DNN_spec_20160425v2.hdf5" noisylistpath = sys.argv[2] For Noisy data 5 Frmae For Noisy data The un-enhanced part of spec should be un-normalized | 154 | en | 0.721465 |
from myelin.utils import CallbackList, Experience
class RLInteraction:
"""An episodic interaction between an agent and an environment."""
def __init__(self, env, agent, callbacks=None, termination_conditions=None):
self.env = env
self.agent = agent
self.callbacks = CallbackList(callba... | myelin/core/interactions.py | 1,832 | An episodic interaction between an agent and an environment.
Starts agent-environment interaction. | 98 | en | 0.844718 |
from __future__ import division
import numpy as np
from scipy import ndimage as ndi
from ..morphology import dilation, erosion, square
from ..util import img_as_float, view_as_windows
from ..color import gray2rgb
def _find_boundaries_subpixel(label_img):
"""See ``find_boundaries(..., mode='subpixel')``.
Not... | venv/lib/python3.8/site-packages/skimage/segmentation/boundaries.py | 9,983 | See ``find_boundaries(..., mode='subpixel')``.
Notes
-----
This function puts in an empty row and column between each *actual*
row and column of the image, for a corresponding shape of $2s - 1$
for every image dimension of size $s$. These "interstitial" rows
and columns are filled as ``True`` if they separate two labe... | 6,372 | en | 0.583085 |
from __future__ import print_function
import argparse
import gym
from itertools import count
import numpy as np
import mxnet as mx
import mxnet.ndarray as F
from mxnet import gluon
from mxnet.gluon import nn
from mxnet import autograd
parser = argparse.ArgumentParser(description='MXNet actor-critic example')
parser... | example/gluon/actor_critic.py | 3,624 | Sample a sequence of actions reverse accumulate and normalize rewards compute loss and gradient Here we differentiate the stochastic graph, corresponds to the first term of equation (6) in https://arxiv.org/pdf/1506.05254.pdf Optimizer minimizes the loss but we want to maximizing the reward, so use we use -reward here. | 320 | en | 0.843892 |
import click
from typing import Sequence, Tuple
from click.formatting import measure_table, iter_rows
class OrderedCommand(click.Command):
def get_params(self, ctx):
rv = super().get_params(ctx)
rv.sort(key=lambda o: (not o.required, o.name))
return rv
def format_options(self, ctx, f... | src/cli.py | 3,482 | Writes all the options into the formatter if they exist. | 56 | en | 0.816037 |
import argparse
import glob
import os
import time
import vlc
import cv2
import numpy as np
from enum import Enum
from tqdm import tqdm
from PIL import Image, ImageDraw, ImageFont
from align.align_trans import get_reference_facial_points
from align.detector import load_detect_faces_models, process_faces
from align.vis... | test_video_stream.py | 8,945 | Detect bboxes and landmarks for all faces in the image and warp the faces. Filter results by detection probability. features is tensor, so converting to numpy arr below Visualize the results Process frame BGR -> RGB Display the resulting frame Quit if we press 'q'. When everything is done, release the capture. | 311 | en | 0.849147 |
from userinput import *
from types import SimpleNamespace
import sys
from PyQt5.QtCore import pyqtSignal as pys
class numberInput(QtWidgets.QMainWindow,Ui_MainWindow):
input_num=pys(str)
def __init__(self,opacity=1,loc=(200,200),parent=None):
super(numberInput,self).__init__(parent)
... | udvent_reworked_v2_2_friday/input_Number.py | 2,226 | self.setWindowFlags(QtCore.Qt.FramelessWindowHint) | 50 | en | 0.184616 |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... | orc8r/gateway/python/magma/magmad/tests/sync_rpc_client_tests.py | 4,065 | Tests for the SyncRPCClient
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... | 530 | en | 0.860432 |
from typing import Dict, List
from sortedcontainers import SortedDict
from shamrock.types.blockchain_format.coin import Coin
from shamrock.types.blockchain_format.sized_bytes import bytes32
from shamrock.types.mempool_item import MempoolItem
class Mempool:
def __init__(self, max_size_in_cost: int):
self... | shamrock/full_node/mempool.py | 3,433 | Adds an item to the mempool by kicking out transactions (if it doesn't fit), in order of increasing fee per cost
Checks whether the mempool is at full capacity and cannot accept a transaction with size cost.
Gets the minimum fpc rate that a transaction with specified cost will need in order to get included.
Removes an ... | 551 | en | 0.85197 |
import time
import copy
import pickle
import warnings
import numpy as np
import scipy.sparse as sp
import torch
import torch.nn.functional as F
from sklearn.metrics import roc_auc_score, average_precision_score, precision_recall_curve, auc
def sparse_to_tuple(sparse_mx):
if not sp.isspmatrix_coo(sparse_mx):
... | vgae/utils.py | 5,096 | get logists and labels logists = A_pred.view(-1) labels = adj_label.to_dense().view(-1) calc scores calc reconstracted adj_mat and accuracy with the threshold for best f1 weights for log_lik loss move input data and label to gpu if needed r_test = get_scores(dl.test_edges, dl.test_edges_false, A_pred, dl.adj_label) sp.... | 355 | en | 0.571588 |
# -*- coding: utf-8 -*-
# @Author: Yanqi Gu
# @Date: 2019-04-20 16:30:52
# @Last Modified by: Yanqi Gu
# @Last Modified time: 2019-04-20 16:57:49
| DPDecisionTree/__init__.py | 150 | -*- coding: utf-8 -*- @Author: Yanqi Gu @Date: 2019-04-20 16:30:52 @Last Modified by: Yanqi Gu @Last Modified time: 2019-04-20 16:57:49 | 139 | en | 0.443622 |
# Copyright (c) 2016,2017,2018,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Contains a collection of generally useful calculation tools."""
import functools
from operator import itemgetter
import numpy as np
from numpy.core.numeric import ... | src/metpy/calc/tools.py | 53,973 | Convert extended (non-abbrievated) directions to abbrieviation.
Handle reshaping coordinate array to have proper dimensionality.
This puts the values along the specified axis.
Handle None if preprocess, else handles anything not in DIR_STRS.
Delete masked points from arrays.
Takes arrays and removes masked points to ... | 25,356 | en | 0.723945 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.