uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
edc78cf51921d77471daa9d1 | train | function | def translate_x_rel(img, pct, **kwargs):
pixels = pct * img.size[0]
_check_args_tf(kwargs)
return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
| def translate_x_rel(img, pct, **kwargs):
| pixels = pct * img.size[0]
_check_args_tf(kwargs)
return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
| ), **kwargs)
def shear_y(img, factor, **kwargs):
_check_args_tf(kwargs)
return img.transform(img.size, Image.AFFINE, (1, 0, 0, factor, 1, 0), **kwargs)
def translate_x_rel(img, pct, **kwargs):
| 64 | 64 | 60 | 11 | 53 | datduong/pytorch-image-models | timm/data/auto_augment.py | Python | translate_x_rel | translate_x_rel | 68 | 71 | 68 | 68 | 52277eed30c303d767607b5b7c613e5c8d6d23e5 | bigcode/the-stack | train |
463bd61b3679a719f5350165 | train | function | def _enhance_increasing_level_to_arg(level, _hparams):
# the 'no change' level is 1.0, moving away from that towards 0. or 2.0 increases the enhancement blend
# range [0.1, 1.9]
level = (level / _MAX_LEVEL) * .9
level = 1.0 + _randomly_negate(level)
return level,
| def _enhance_increasing_level_to_arg(level, _hparams):
# the 'no change' level is 1.0, moving away from that towards 0. or 2.0 increases the enhancement blend
# range [0.1, 1.9]
| level = (level / _MAX_LEVEL) * .9
level = 1.0 + _randomly_negate(level)
return level,
| 0.1,
def _enhance_increasing_level_to_arg(level, _hparams):
# the 'no change' level is 1.0, moving away from that towards 0. or 2.0 increases the enhancement blend
# range [0.1, 1.9]
| 64 | 64 | 93 | 60 | 4 | datduong/pytorch-image-models | timm/data/auto_augment.py | Python | _enhance_increasing_level_to_arg | _enhance_increasing_level_to_arg | 192 | 197 | 192 | 194 | 4e583db4c85725878d51c5d11e19cba7758f215e | bigcode/the-stack | train |
30b9173d45ef0e801b2378e5 | train | class | class AutoAugment:
def __init__(self, policy):
self.policy = policy
def __call__(self, img):
sub_policy = random.choice(self.policy)
for op in sub_policy:
img = op(img)
return img
| class AutoAugment:
| def __init__(self, policy):
self.policy = policy
def __call__(self, img):
sub_policy = random.choice(self.policy)
for op in sub_policy:
img = op(img)
return img
| params)
elif name == 'v0':
return auto_augment_policy_v0(hparams)
elif name == 'v0r':
return auto_augment_policy_v0r(hparams)
else:
assert False, 'Unknown AA policy (%s)' % name
class AutoAugment:
| 64 | 64 | 55 | 5 | 58 | datduong/pytorch-image-models | timm/data/auto_augment.py | Python | AutoAugment | AutoAugment | 495 | 504 | 495 | 496 | 9b4289ad4008f384572495dde70e1835a715ed68 | bigcode/the-stack | train |
caf75b0dd391b0756a7a1f78 | train | function | def _posterize_increasing_level_to_arg(level, hparams):
# As per Tensorflow models research and UDA impl
# range [4, 0], 'keep 4 down to 0 MSB of original image',
# intensity/severity of augmentation increases with level
return 4 - _posterize_level_to_arg(level, hparams)[0],
| def _posterize_increasing_level_to_arg(level, hparams):
# As per Tensorflow models research and UDA impl
# range [4, 0], 'keep 4 down to 0 MSB of original image',
# intensity/severity of augmentation increases with level
| return 4 - _posterize_level_to_arg(level, hparams)[0],
| 4),
def _posterize_increasing_level_to_arg(level, hparams):
# As per Tensorflow models research and UDA impl
# range [4, 0], 'keep 4 down to 0 MSB of original image',
# intensity/severity of augmentation increases with level
| 63 | 64 | 79 | 61 | 2 | datduong/pytorch-image-models | timm/data/auto_augment.py | Python | _posterize_increasing_level_to_arg | _posterize_increasing_level_to_arg | 229 | 233 | 229 | 232 | ab5e7f36e2793b3f3ef3088d94ba6c94daaa0c24 | bigcode/the-stack | train |
9048dd99a4bd088418a6f536 | train | class | class ConnectionState(Registerable):
parsers: dict[EMsg, Callable]
def __init__(self, client: Client, **kwargs: Any):
self.client = client
self.dispatch = client.dispatch
self.http = client.http
self.handled_friends = asyncio.Event()
self.handled_emoticons = asyncio.Eve... | class ConnectionState(Registerable):
| parsers: dict[EMsg, Callable]
def __init__(self, client: Client, **kwargs: Any):
self.client = client
self.dispatch = client.dispatch
self.http = client.http
self.handled_friends = asyncio.Event()
self.handled_emoticons = asyncio.Event()
self.handled_groups = as... | _CHECKING:
from .abc import Message
from .client import Client
from .gateway import SteamWebSocket
log = logging.getLogger(__name__)
class TradeQueue:
def __init__(self):
self.queue: deque[TradeOffer] = deque()
self._waiting_for: dict[int, asyncio.Future[TradeOffer]] = {}
async d... | 256 | 256 | 11,341 | 6 | 249 | Gobot1234/steam | steam/state.py | Python | ConnectionState | ConnectionState | 125 | 1,357 | 125 | 125 | 1fbd1c6ffc9220666de30b363ef2c17b1cc07053 | bigcode/the-stack | train |
0b0eebc69bbfafdf1614cb8e | train | class | class TradeQueue:
def __init__(self):
self.queue: deque[TradeOffer] = deque()
self._waiting_for: dict[int, asyncio.Future[TradeOffer]] = {}
async def wait_for(self, id: int) -> TradeOffer:
for trade in reversed(self.queue): # check if it's already here
if trade.id == id:
... | class TradeQueue:
| def __init__(self):
self.queue: deque[TradeOffer] = deque()
self._waiting_for: dict[int, asyncio.Future[TradeOffer]] = {}
async def wait_for(self, id: int) -> TradeOffer:
for trade in reversed(self.queue): # check if it's already here
if trade.id == id:
self... | struct_messages,
)
from .trade import DescriptionDict, TradeOffer, TradeOfferDict
from .user import User
if TYPE_CHECKING:
from .abc import Message
from .client import Client
from .gateway import SteamWebSocket
log = logging.getLogger(__name__)
class TradeQueue:
| 64 | 64 | 216 | 4 | 60 | Gobot1234/steam | steam/state.py | Python | TradeQueue | TradeQueue | 92 | 122 | 92 | 92 | f3bc9a0455beec19e59c58d21884fa47db8e2076 | bigcode/the-stack | train |
7f9a424f358a516bbab1b59e | train | function | def save_checkpoint(state, args, is_best, filename='checkpoint.pth.tar'):
"""Saves checkpoint to disk"""
directory = "runs/%s/%s/%s/"%(args.dataset, args.model, args.checkname)
if not os.path.exists(directory):
os.makedirs(directory)
filename = directory + filename
torch.save(state, filename... | def save_checkpoint(state, args, is_best, filename='checkpoint.pth.tar'):
| """Saves checkpoint to disk"""
directory = "runs/%s/%s/%s/"%(args.dataset, args.model, args.checkname)
if not os.path.exists(directory):
os.makedirs(directory)
filename = directory + filename
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, directory + 'model_bes... | lr
for i in range(1, len(optimizer.param_groups)):
optimizer.param_groups[i]['lr'] = lr * 10
# refer to https://github.com/xternalz/WideResNet-pytorch
def save_checkpoint(state, args, is_best, filename='checkpoint.pth.tar'):
| 64 | 64 | 95 | 17 | 46 | grow-yhq/PyTorch-Encoding | encoding/utils.py | Python | save_checkpoint | save_checkpoint | 99 | 107 | 99 | 99 | 8986d0aea3f55356c126eff516f1ce5dee5fa54a | bigcode/the-stack | train |
ef6cae4344dec6088a25f55f | train | function | def get_optimizer(args, model, diff_LR=True):
"""
Returns an optimizer for given model,
Args:
args: :attr:`args.lr`, :attr:`args.momentum`, :attr:`args.weight_decay`
model: if using different lr, define `model.pretrained` and `model.head`.
"""
if diff_LR and model.pretrained is not ... | def get_optimizer(args, model, diff_LR=True):
| """
Returns an optimizer for given model,
Args:
args: :attr:`args.lr`, :attr:`args.momentum`, :attr:`args.weight_decay`
model: if using different lr, define `model.pretrained` and `model.head`.
"""
if diff_LR and model.pretrained is not None:
print('Using different learning ... |
## LICENSE file in the root directory of this source tree
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
"""Encoding Util Tools"""
import shutil
import os
import math
import torch
__all__ = ['get_optimizer', 'LR_Scheduler', 'save_checkpoint']
def get_optimizer(args, model, diff_LR=True):... | 64 | 64 | 182 | 12 | 52 | grow-yhq/PyTorch-Encoding | encoding/utils.py | Python | get_optimizer | get_optimizer | 19 | 41 | 19 | 19 | c392f4ea48f96b6bf40940428b33c340110df5b6 | bigcode/the-stack | train |
84130b6266c02bb2798c0447 | train | class | class LR_Scheduler(object):
"""Learning Rate Scheduler
Step mode: ``lr = baselr * 0.1 ^ {floor(epoch-1 / lr_step)}``
Cosine mode: ``lr = baselr * 0.5 * (1 + cos(iter/maxiter))``
Poly mode: ``lr = baselr * (1 - iter/maxiter) ^ 0.9``
Args:
args: :attr:`args.lr_scheduler` lr scheduler mode... | class LR_Scheduler(object):
| """Learning Rate Scheduler
Step mode: ``lr = baselr * 0.1 ^ {floor(epoch-1 / lr_step)}``
Cosine mode: ``lr = baselr * 0.5 * (1 + cos(iter/maxiter))``
Poly mode: ``lr = baselr * (1 - iter/maxiter) ^ 0.9``
Args:
args: :attr:`args.lr_scheduler` lr scheduler mode (`cos`, `poly`),
... | Args:
args: :attr:`args.lr`, :attr:`args.momentum`, :attr:`args.weight_decay`
model: if using different lr, define `model.pretrained` and `model.head`.
"""
if diff_LR and model.pretrained is not None:
print('Using different learning rate for pre-trained features')
optimizer =... | 166 | 166 | 556 | 6 | 159 | grow-yhq/PyTorch-Encoding | encoding/utils.py | Python | LR_Scheduler | LR_Scheduler | 44 | 95 | 44 | 44 | e02f28e8265f3ea81f933e8857d319219079336f | bigcode/the-stack | train |
a45237438f5557c4e5602ef7 | train | function | def test_change_one_click_status_reverse():
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Phase 1: create initial recurring
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create one click recurring
recurring_id = do_one_click_paymen... | def test_change_one_click_status_reverse():
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Phase 1: create initial recurring
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create one click recurring
| recurring_id = do_one_click_payment(recurrings, CARD_NON3DS_CONFIRMED)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Phase 2: change one-click status (preauth complete operation)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# prepa... | password=GATEWAY_PASSWORD, debug=DEBUG_MODE)
recurrings = RecurringsApi(ApiClient(config))
def test_change_one_click_status_reverse():
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Phase 1: create initial recurring
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | 64 | 64 | 209 | 40 | 24 | Sinkler/python-sdk-v2 | tests/recurrings/onclick/RecurringOneClickChangeStatusReverseUAT.py | Python | test_change_one_click_status_reverse | test_change_one_click_status_reverse | 16 | 43 | 16 | 21 | 424ae2b4c6c3adc1b4a8606375b0945dc5a5110e | bigcode/the-stack | train |
8e9b002ed83b125fee58f93c | train | function | def test_get_ansible_vault_path():
ansible_vault_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_VAULT_OUTPUT_DIR)
result_path = get_ansible_vault_path(CLUSTER_NAME_SAVE)
assert os.path.exists(ansible_vault_path)
assert result_path == ansible_vault_path
| def test_get_ansible_vault_path():
| ansible_vault_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_VAULT_OUTPUT_DIR)
result_path = get_ansible_vault_path(CLUSTER_NAME_SAVE)
assert os.path.exists(ansible_vault_path)
assert result_path == ansible_vault_path
| )
assert os.path.exists(terraform_path)
assert result_path == terraform_path
def test_get_ansible_path():
assert get_ansible_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR)
def test_get_ansible_vault_path():
| 64 | 64 | 74 | 9 | 55 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_ansible_vault_path | test_get_ansible_vault_path | 65 | 69 | 65 | 65 | 5e9508bfeab065a8e24a09323bf4d79ec92461cb | bigcode/the-stack | train |
fabc5f52714eb9750a7d635f | train | function | def test_save_ansible_config_file():
config_file_settings = OrderedDict(ANSIBLE_CONFIG_FILE_SETTINGS)
ansible_config_file_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR, ANSIBLE_CFG_FILE)
save_ansible_config_file(config_file_settings, ansible_config_file_path)
f = open(ansible_co... | def test_save_ansible_config_file():
| config_file_settings = OrderedDict(ANSIBLE_CONFIG_FILE_SETTINGS)
ansible_config_file_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR, ANSIBLE_CFG_FILE)
save_ansible_config_file(config_file_settings, ansible_config_file_path)
f = open(ansible_config_file_path, mode='r')
ansible... | inventory_content
assert 'test-4 ansible_host=10.0.0.4' in inventory_content
assert 'ansible_user=operations' in inventory_content
assert 'ansible_ssh_private_key_file=id_rsa' in inventory_content
def test_save_ansible_config_file():
| 64 | 64 | 131 | 8 | 55 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_save_ansible_config_file | test_save_ansible_config_file | 131 | 138 | 131 | 131 | ad231cc732c827487b081f651e3822695c14c59d | bigcode/the-stack | train |
ea260db0917d9145fac84cd7 | train | function | def test_load_manifest():
build_path = get_build_path(CLUSTER_NAME_LOAD)
docs = load_manifest(build_path)
assert docs == TEST_DOCS
| def test_load_manifest():
| build_path = get_build_path(CLUSTER_NAME_LOAD)
docs = load_manifest(build_path)
assert docs == TEST_DOCS
| IFEST_FILE_NAME)
manifest_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, MANIFEST_FILE_NAME)
manifest_stream = open(manifest_path, 'r')
manifest_file_content = safe_load_all(manifest_stream)
assert TEST_DOCS == manifest_file_content
def test_load_manifest():
| 64 | 64 | 33 | 5 | 58 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_load_manifest | test_load_manifest | 104 | 107 | 104 | 104 | acd0922df46422d10ea4564e496a0af15c6338c8 | bigcode/the-stack | train |
914f6fea6854dea8a39ff55b | train | function | def test_get_ansible_config_file_path_for_build():
assert get_ansible_config_file_path_for_build(os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE)) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR, ANSIBLE_CFG_FILE)
| def test_get_ansible_config_file_path_for_build():
| assert get_ansible_config_file_path_for_build(os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE)) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR, ANSIBLE_CFG_FILE)
| , ANSIBLE_OUTPUT_DIR)
result_path = get_ansible_path_for_build(os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE))
assert os.path.exists(ansible_path_for_build_path)
assert result_path == ansible_path_for_build_path
def test_get_ansible_config_file_path_for_build():
| 64 | 64 | 61 | 11 | 52 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_ansible_config_file_path_for_build | test_get_ansible_config_file_path_for_build | 90 | 93 | 90 | 90 | aff506973f4abac90b401d351d2f090adb30903a | bigcode/the-stack | train |
59756f63264e0a8a5237b435 | train | function | def test_get_ansible_path_for_build():
ansible_path_for_build_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR)
result_path = get_ansible_path_for_build(os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE))
assert os.path.exists(ansible_path_for_build_path)
assert result_path == ansible_pa... | def test_get_ansible_path_for_build():
| ansible_path_for_build_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR)
result_path = get_ansible_path_for_build(os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE))
assert os.path.exists(ansible_path_for_build_path)
assert result_path == ansible_path_for_build_path
| SIBLE_CFG_FILE)
def test_get_inventory_path_for_build():
assert get_inventory_path_for_build(os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE)) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE)
def test_get_ansible_path_for_build():
| 64 | 64 | 81 | 9 | 55 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_ansible_path_for_build | test_get_ansible_path_for_build | 83 | 87 | 83 | 83 | ea9765dd63eed973da0bb388c866c8a2ca568305 | bigcode/the-stack | train |
ca514db4864f4668aabbba96 | train | function | def test_get_terraform_path():
terraform_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, TERRAFORM_OUTPUT_DIR)
result_path = get_terraform_path(CLUSTER_NAME_SAVE)
assert os.path.exists(terraform_path)
assert result_path == terraform_path
| def test_get_terraform_path():
| terraform_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, TERRAFORM_OUTPUT_DIR)
result_path = get_terraform_path(CLUSTER_NAME_SAVE)
assert os.path.exists(terraform_path)
assert result_path == terraform_path
| == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE)
def test_get_manifest_path():
assert get_manifest_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, MANIFEST_FILE_NAME)
def test_get_terraform_path():
| 64 | 64 | 58 | 7 | 57 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_terraform_path | test_get_terraform_path | 53 | 57 | 53 | 53 | 9e7186020495bd1adacc7211a4a88be4d1d2dd8b | bigcode/the-stack | train |
151c322d8051edc6d4c2abb5 | train | function | def test_get_ansible_path():
assert get_ansible_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR)
| def test_get_ansible_path():
| assert get_ansible_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR)
| test_get_terraform_path():
terraform_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, TERRAFORM_OUTPUT_DIR)
result_path = get_terraform_path(CLUSTER_NAME_SAVE)
assert os.path.exists(terraform_path)
assert result_path == terraform_path
def test_get_ansible_path():
| 64 | 64 | 38 | 7 | 56 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_ansible_path | test_get_ansible_path | 60 | 62 | 60 | 60 | f78e470b7ec0f4424408e5a349fd4f69732bc7a5 | bigcode/the-stack | train |
cd4cea2cb70dd7dd8b4f53e1 | train | function | def test_save_manifest():
save_manifest(TEST_DOCS, CLUSTER_NAME_SAVE, MANIFEST_FILE_NAME)
manifest_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, MANIFEST_FILE_NAME)
manifest_stream = open(manifest_path, 'r')
manifest_file_content = safe_load_all(manifest_stream)
assert TEST_DOCS == manifest_fi... | def test_save_manifest():
| save_manifest(TEST_DOCS, CLUSTER_NAME_SAVE, MANIFEST_FILE_NAME)
manifest_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, MANIFEST_FILE_NAME)
manifest_stream = open(manifest_path, 'r')
manifest_file_content = safe_load_all(manifest_stream)
assert TEST_DOCS == manifest_file_content
| _get_ansible_config_file_path_for_build():
assert get_ansible_config_file_path_for_build(os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE)) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR, ANSIBLE_CFG_FILE)
def test_save_manifest():
| 64 | 64 | 77 | 5 | 59 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_save_manifest | test_save_manifest | 96 | 101 | 96 | 96 | 388104fb3fe43373e058a044d79f26db90826813 | bigcode/the-stack | train |
90d46e06454a16ab05ee4f7c | train | function | def test_get_manifest_path():
assert get_manifest_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, MANIFEST_FILE_NAME)
| def test_get_manifest_path():
| assert get_manifest_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, MANIFEST_FILE_NAME)
| USTER_NAME_SAVE)
assert os.path.exists(build_path)
assert result_path == build_path
def test_get_inventory_path():
assert get_inventory_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE)
def test_get_manifest_path():
| 64 | 64 | 35 | 6 | 58 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_manifest_path | test_get_manifest_path | 48 | 50 | 48 | 48 | b810ad8265bb8f743a716c9c7af143469f083911 | bigcode/the-stack | train |
5a1f11441e433e1187fb0563 | train | function | def test_get_inventory_path_for_build():
assert get_inventory_path_for_build(os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE)) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE)
| def test_get_inventory_path_for_build():
| assert get_inventory_path_for_build(os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE)) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE)
| _path == ansible_vault_path
def test_get_ansible_config_file_path():
assert get_ansible_config_file_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR, ANSIBLE_CFG_FILE)
def test_get_inventory_path_for_build():
| 64 | 64 | 50 | 8 | 56 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_inventory_path_for_build | test_get_inventory_path_for_build | 77 | 80 | 77 | 77 | e984c171005b457f3ab56eb41f47f2a3c7455a22 | bigcode/the-stack | train |
efdb0af6135cee0ea42066a3 | train | function | def test_get_ansible_config_file_path():
assert get_ansible_config_file_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR, ANSIBLE_CFG_FILE)
| def test_get_ansible_config_file_path():
| assert get_ansible_config_file_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_OUTPUT_DIR, ANSIBLE_CFG_FILE)
| (OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_VAULT_OUTPUT_DIR)
result_path = get_ansible_vault_path(CLUSTER_NAME_SAVE)
assert os.path.exists(ansible_vault_path)
assert result_path == ansible_vault_path
def test_get_ansible_config_file_path():
| 64 | 64 | 48 | 9 | 54 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_ansible_config_file_path | test_get_ansible_config_file_path | 72 | 74 | 72 | 72 | 4494b310a283b53fd2ebc3f5e5894ce0f8d3adc1 | bigcode/the-stack | train |
608de8ee345cf131a9b21b01 | train | function | def test_save_inventory():
cluster_model = dict_to_objdict(TEST_CLUSTER_MODEL)
save_inventory(TEST_INVENTORY, cluster_model)
f = open(os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE), mode='r')
inventory_content = f.read()
assert 'test-1 ansible_host=10.0.0.1' in inventory_conten... | def test_save_inventory():
| cluster_model = dict_to_objdict(TEST_CLUSTER_MODEL)
save_inventory(TEST_INVENTORY, cluster_model)
f = open(os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE), mode='r')
inventory_content = f.read()
assert 'test-1 ansible_host=10.0.0.1' in inventory_content
assert 'test-2 ansibl... | _NAME_SAVE)
sp_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, TERRAFORM_OUTPUT_DIR, SP_FILE_NAME)
sp_stream = open(sp_path, 'r')
sp_file_content = safe_load(sp_stream)
assert TEST_SP == sp_file_content
def test_save_inventory():
| 64 | 64 | 182 | 5 | 58 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_save_inventory | test_save_inventory | 118 | 128 | 118 | 118 | 8cf9c7b949fc8b5dacc33f8c9cc46bbbf9806fda | bigcode/the-stack | train |
570dbf06b12570b2a5263d44 | train | function | def test_get_output_path():
output_path = os.path.join(OUTPUT_PATH)
result_path = os.path.normpath(get_output_path())
assert os.path.exists(output_path)
assert result_path == output_path
| def test_get_output_path():
| output_path = os.path.join(OUTPUT_PATH)
result_path = os.path.normpath(get_output_path())
assert os.path.exists(output_path)
assert result_path == output_path
| xxxxxxxxxxxxxxx',
'tenant': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}
ANSIBLE_CONFIG_FILE_SETTINGS = [('defaults', {
'interpreter_python': 'auto_legacy_silent',
'allow_world_readable_tmpfiles': 'true'
})]
def tes... | 64 | 64 | 46 | 6 | 58 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_output_path | test_get_output_path | 29 | 33 | 29 | 29 | f45bc2c243119679cc0e24723c008c8b1e72dc56 | bigcode/the-stack | train |
ef679694b9d1c64802330196 | train | function | def test_get_inventory_path():
assert get_inventory_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE)
| def test_get_inventory_path():
| assert get_inventory_path(CLUSTER_NAME_SAVE) == os.path.join(
OUTPUT_PATH, CLUSTER_NAME_SAVE, ANSIBLE_INVENTORY_FILE)
| assert result_path == output_path
def test_get_build_path():
build_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE)
result_path = get_build_path(CLUSTER_NAME_SAVE)
assert os.path.exists(build_path)
assert result_path == build_path
def test_get_inventory_path():
| 64 | 64 | 38 | 6 | 57 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_inventory_path | test_get_inventory_path | 43 | 45 | 43 | 43 | 647911830f05a4a27dd89191490e9cf7033c975e | bigcode/the-stack | train |
bb60e87a974239f0827485f5 | train | function | def test_save_sp():
save_sp(TEST_SP, CLUSTER_NAME_SAVE)
sp_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, TERRAFORM_OUTPUT_DIR, SP_FILE_NAME)
sp_stream = open(sp_path, 'r')
sp_file_content = safe_load(sp_stream)
assert TEST_SP == sp_file_content
| def test_save_sp():
| save_sp(TEST_SP, CLUSTER_NAME_SAVE)
sp_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE, TERRAFORM_OUTPUT_DIR, SP_FILE_NAME)
sp_stream = open(sp_path, 'r')
sp_file_content = safe_load(sp_stream)
assert TEST_SP == sp_file_content
| , 'r')
manifest_file_content = safe_load_all(manifest_stream)
assert TEST_DOCS == manifest_file_content
def test_load_manifest():
build_path = get_build_path(CLUSTER_NAME_LOAD)
docs = load_manifest(build_path)
assert docs == TEST_DOCS
def test_save_sp():
| 64 | 64 | 72 | 5 | 58 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_save_sp | test_save_sp | 110 | 115 | 110 | 110 | 594494afc743bba2cc4c1ef6f26f97ea593ac838 | bigcode/the-stack | train |
b553c92d75eb9306f15db05d | train | function | def test_get_build_path():
build_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE)
result_path = get_build_path(CLUSTER_NAME_SAVE)
assert os.path.exists(build_path)
assert result_path == build_path
| def test_get_build_path():
| build_path = os.path.join(OUTPUT_PATH, CLUSTER_NAME_SAVE)
result_path = get_build_path(CLUSTER_NAME_SAVE)
assert os.path.exists(build_path)
assert result_path == build_path
| _world_readable_tmpfiles': 'true'
})]
def test_get_output_path():
output_path = os.path.join(OUTPUT_PATH)
result_path = os.path.normpath(get_output_path())
assert os.path.exists(output_path)
assert result_path == output_path
def test_get_build_path():
| 64 | 64 | 50 | 6 | 57 | sbbroot/epiphany | tests/unit/helpers/test_build_io.py | Python | test_get_build_path | test_get_build_path | 36 | 40 | 36 | 36 | c43c89bf738f23a517517297e7250e554b738ebd | bigcode/the-stack | train |
7c2ef717cf96dc2c88119e87 | train | function | @login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
| @login_manager.user_loader
def load_user(user_id):
| return User.query.get(int(user_id))
| the LoginManager for the server
login_manager = LoginManager()
login_manager.init_app(server)
login_manager.login_view = '/login'
# Create User class with UserMixin
class User(UserMixin, base):
pass
# callback to reload the user object
@login_manager.user_loader
def load_user(user_id):
| 64 | 64 | 20 | 11 | 52 | nekrasovp/dash-auth-flask-nginx | dash-auth-flask/server.py | Python | load_user | load_user | 47 | 49 | 47 | 48 | 813f748a41cbba65f94c5485911443e40039eee8 | bigcode/the-stack | train |
d6fa8cc0aa75167735dd762e | train | class | class User(UserMixin, base):
pass
| class User(UserMixin, base):
| pass
| ', 'con'),
SQLALCHEMY_TRACK_MODIFICATIONS=False
)
db.init_app(server)
# Setup the LoginManager for the server
login_manager = LoginManager()
login_manager.init_app(server)
login_manager.login_view = '/login'
# Create User class with UserMixin
class User(UserMixin, base):
| 64 | 64 | 10 | 7 | 56 | nekrasovp/dash-auth-flask-nginx | dash-auth-flask/server.py | Python | User | User | 42 | 43 | 42 | 42 | 916565012262d98a16257850134e02c4d0b33a3e | bigcode/the-stack | train |
7bc7e648a234ac07d0a5c781 | train | class | class BaseEstimator(Base):
"""Base class for all estimators in scikit-learn
Notes
-----
All estimators should specify all the parameters that can be set
at the class level in their ``__init__`` as explicit keyword
arguments (no ``*args`` or ``**kwargs``).
"""
def __init_subclass__(cls)... | class BaseEstimator(Base):
| """Base class for all estimators in scikit-learn
Notes
-----
All estimators should specify all the parameters that can be set
at the class level in their ``__init__`` as explicit keyword
arguments (no ``*args`` or ``**kwargs``).
"""
def __init_subclass__(cls):
orig_init = cls._... | # Original authors from Sckit-Learn:
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# License: BSD 3 clause
# This code originates from the Scikit-Learn library,
# it was since modified to allow GPU acceleration.
# This code is under BSD 3 clause license.
# Authors mentioned above do not endorse or promote ... | 115 | 256 | 979 | 5 | 109 | nickpowersys/cuml | python/cuml/_thirdparty/sklearn/utils/skl_dependencies.py | Python | BaseEstimator | BaseEstimator | 17 | 128 | 17 | 17 | efd7bd59af2c1cf6a089914a902d205c226441dc | bigcode/the-stack | train |
b3360360592f5702dee403a0 | train | class | class BaseComposition:
"""Handles parameter management for classifiers composed of named estimators.
"""
def _get_params(self, attr, deep=True):
out = super().get_params(deep=deep)
if not deep:
return out
estimators = getattr(self, attr)
out.update(estimators)
... | class BaseComposition:
| """Handles parameter management for classifiers composed of named estimators.
"""
def _get_params(self, attr, deep=True):
out = super().get_params(deep=deep)
if not deep:
return out
estimators = getattr(self, attr)
out.update(estimators)
for name, estimat... | n_samples,), default=None
Target values.
**fit_params : dict
Additional fit parameters.
Returns
-------
X_new : ndarray array of shape (n_samples, n_features_new)
Transformed array.
"""
# non-optimized default implementation; override... | 144 | 144 | 482 | 4 | 140 | nickpowersys/cuml | python/cuml/_thirdparty/sklearn/utils/skl_dependencies.py | Python | BaseComposition | BaseComposition | 167 | 220 | 167 | 167 | 8680a1f5eae57d787c5054f24fcf5f6e0b03cd25 | bigcode/the-stack | train |
f44143fc8281d6fd04c3d38e | train | class | class TransformerMixin:
"""Mixin class for all transformers in scikit-learn."""
def fit_transform(self, X, y=None, **fit_params):
"""
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params
and returns a transformed version of X.
... | class TransformerMixin:
| """Mixin class for all transformers in scikit-learn."""
def fit_transform(self, X, y=None, **fit_params):
"""
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params
and returns a transformed version of X.
Parameters
----... | )
y = check_array(y, **check_y_params)
else:
X, y = check_X_y(X, y, **check_params)
out = X, y
if check_params.get('ensure_2d', True):
self._check_n_features(X, reset=reset)
return out
class TransformerMixin:
| 72 | 72 | 240 | 4 | 67 | nickpowersys/cuml | python/cuml/_thirdparty/sklearn/utils/skl_dependencies.py | Python | TransformerMixin | TransformerMixin | 131 | 164 | 131 | 131 | 007e1946bdfbb4359540d2e48e684d81186f8f3a | bigcode/the-stack | train |
4724643e2aa0dd4e4802a738 | train | class | class Migration(migrations.Migration):
dependencies = [
('subd', '0010_contract_comission'),
]
operations = [
migrations.AlterModelOptions(
name='contract',
options={'verbose_name': '\u0414\u043e\u0433\u043e\u0432\u043e\u0440', 'verbose_name_plural': '\u0414\u043e\u... | class Migration(migrations.Migration):
| dependencies = [
('subd', '0010_contract_comission'),
]
operations = [
migrations.AlterModelOptions(
name='contract',
options={'verbose_name': '\u0414\u043e\u0433\u043e\u0432\u043e\u0440', 'verbose_name_plural': '\u0414\u043e\u0433\u043e\u0432\u043e\u0440\u044b'},
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-17 11:28
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
| 52 | 64 | 104 | 7 | 44 | ffedoroff/omgtu | semestr7/subd/migrations/0011_auto_20161117_1128.py | Python | Migration | Migration | 8 | 19 | 8 | 9 | a5e9706e4dd10776ab665c0f40fd4df9def3a480 | bigcode/the-stack | train |
791ea5e3c66c30c9f7a84240 | train | function | def allscores(tournament, team):
# SELECT score FROM tournament_matches_teams WHERE
# tourneyid='".tournament.id."' AND team='".teamid."'");
query = TournamentMatchesTeams.objects.filter(
tourney=tournament, team=team
)
return sum(query.values_list('score', flat=True))
| def allscores(tournament, team):
# SELECT score FROM tournament_matches_teams WHERE
# tourneyid='".tournament.id."' AND team='".teamid."'");
| query = TournamentMatchesTeams.objects.filter(
tourney=tournament, team=team
)
return sum(query.values_list('score', flat=True))
| _what_teams_called = lambda: None
get_num_teams = lambda: None
make_tournament_link = lambda: None
def allscores(tournament, team):
# SELECT score FROM tournament_matches_teams WHERE
# tourneyid='".tournament.id."' AND team='".teamid."'");
| 64 | 64 | 69 | 36 | 27 | Mause/pyalp | pyalp/apps/tournaments/views.py | Python | allscores | allscores | 17 | 24 | 17 | 20 | 38702780a06742f3536c6db3779ea2c6e0d6f59d | bigcode/the-stack | train |
859ba9fe1c05c57bad6be2d0 | train | class | class TournamentsView(CreateView):
def get(self, request):
context = {}
tournament_id = request.GET.get('id', False)
if tournament_id:
tournament = Tournament.objects.filter(tournament_id).one()
# tournament = 'SELECT tourneyid, ttype, tournaments.*
# FR... | class TournamentsView(CreateView):
| def get(self, request):
context = {}
tournament_id = request.GET.get('id', False)
if tournament_id:
tournament = Tournament.objects.filter(tournament_id).one()
# tournament = 'SELECT tourneyid, ttype, tournaments.*
# FROM tournaments WHERE tourneyid='.(i... | ournament_link = lambda: None
def allscores(tournament, team):
# SELECT score FROM tournament_matches_teams WHERE
# tourneyid='".tournament.id."' AND team='".teamid."'");
query = TournamentMatchesTeams.objects.filter(
tourney=tournament, team=team
)
return sum(query.values_list('score', f... | 83 | 83 | 278 | 7 | 76 | Mause/pyalp | pyalp/apps/tournaments/views.py | Python | TournamentsView | TournamentsView | 27 | 69 | 27 | 27 | 4f250806bf404effb47a4390a494951d37375830 | bigcode/the-stack | train |
d7ab5c5ca47095f352c2f9d9 | train | function | @app.route("/")
def test():
return 'ok'
| @app.route("/")
def test():
| return 'ok'
| from flask import Flask
from config import Config
from modules.admin.admin import admin_blue
app = Flask(__name__)
app.config.from_object(Config)
app.register_blueprint(admin_blue,url_prefix='/admin')
@app.route("/")
def test():
| 47 | 64 | 11 | 6 | 41 | 18210208326/information_t | manage.py | Python | test | test | 7 | 9 | 7 | 8 | d9b85cc2d997550e1d194bf332264e37165e6eb9 | bigcode/the-stack | train |
f3c71b5d348f0cfb546aef4f | train | class | class ImuTimeStampTester:
def __init__(self, logName):
self.logName = logName
def run(self):
# try to parse rostopic-echo file and search for timestamps
with open(self.logName, "r") as f:
data = f.readlines()
state = 0
secVal = 0.000;
nanoVal = 0.0
timestamps = np.zeros(1)
... | class ImuTimeStampTester:
| def __init__(self, logName):
self.logName = logName
def run(self):
# try to parse rostopic-echo file and search for timestamps
with open(self.logName, "r") as f:
data = f.readlines()
state = 0
secVal = 0.000;
nanoVal = 0.0
timestamps = np.zeros(1)
firstTime = True
for... | '''
'''
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
class ImuTimeStampTester:
| 23 | 142 | 475 | 7 | 15 | wdross/sick_scan_xd | tools/imu_tester/imu_timestamp_test.py | Python | ImuTimeStampTester | ImuTimeStampTester | 9 | 65 | 9 | 9 | aca72edc7b12f9f34ed12884673fb3f84dffa30d | bigcode/the-stack | train |
4de4ea1bbb2d78dd21122bdd | train | class | class TestSf(unittest.TestCase):
"""
Test TestSf
"""
default_types = [
""
]
default_modules = [
"sfp_base64",
"sfp_bitcoin",
"sfp_company",
"sfp_cookie",
"sfp_countryname",
"sfp_creditcard",
"sfp_email",
"sfp_errors",
... | class TestSf(unittest.TestCase):
| """
Test TestSf
"""
default_types = [
""
]
default_modules = [
"sfp_base64",
"sfp_bitcoin",
"sfp_company",
"sfp_cookie",
"sfp_countryname",
"sfp_creditcard",
"sfp_email",
"sfp_errors",
"sfp_ethereum",
"sfp_... | # test_sf.py
import subprocess
import sys
import unittest
class TestSf(unittest.TestCase):
| 21 | 256 | 1,397 | 7 | 13 | khiemtq-cyber/spiderfoot | test/integration/test_sf.py | Python | TestSf | TestSf | 7 | 142 | 7 | 7 | a632cc9a3ff76e8e99880b68cdabe10ef0c03687 | bigcode/the-stack | train |
d0c1fe53d7cad8cae820b2e3 | train | function | def brightness_to_percentage(byt):
"""Convert brightness from absolute 0..255 to percentage."""
return int((byt*100.0)/255.0)
| def brightness_to_percentage(byt):
| """Convert brightness from absolute 0..255 to percentage."""
return int((byt*100.0)/255.0)
| _entry, async_add_entities):
"""Set up discovered switches."""
devs = []
for dev in hass.data[TPLINK_DOMAIN][CONF_LIGHT]:
devs.append(TPLinkSmartBulb(dev))
async_add_entities(devs, True)
return True
def brightness_to_percentage(byt):
| 64 | 64 | 34 | 7 | 56 | shanbs/home-assistant | homeassistant/components/tplink/light.py | Python | brightness_to_percentage | brightness_to_percentage | 52 | 54 | 52 | 52 | 57fa6181b28d929d4626db68a70f14b0541dc773 | bigcode/the-stack | train |
268622b2d312b1135f05d992 | train | class | class TPLinkSmartBulb(Light):
"""Representation of a TPLink Smart Bulb."""
def __init__(self, smartbulb) -> None:
"""Initialize the bulb."""
self.smartbulb = smartbulb
self._sysinfo = None
self._state = None
self._available = False
self._color_temp = None
... | class TPLinkSmartBulb(Light):
| """Representation of a TPLink Smart Bulb."""
def __init__(self, smartbulb) -> None:
"""Initialize the bulb."""
self.smartbulb = smartbulb
self._sysinfo = None
self._state = None
self._available = False
self._color_temp = None
self._brightness = None
... | IES = ['tplink']
PARALLEL_UPDATES = 0
_LOGGER = logging.getLogger(__name__)
ATTR_CURRENT_POWER_W = 'current_power_w'
ATTR_DAILY_ENERGY_KWH = 'daily_energy_kwh'
ATTR_MONTHLY_ENERGY_KWH = 'monthly_energy_kwh'
def async_setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the platform.
... | 256 | 256 | 1,278 | 9 | 246 | shanbs/home-assistant | homeassistant/components/tplink/light.py | Python | TPLinkSmartBulb | TPLinkSmartBulb | 62 | 232 | 62 | 62 | 8babdaf88debab3dbc1317021cfcd0fa73e9bb1d | bigcode/the-stack | train |
7e6e4468f8ac94127c53d9b8 | train | function | def brightness_from_percentage(percent):
"""Convert percentage to absolute value 0..255."""
return (percent*255.0)/100.0
| def brightness_from_percentage(percent):
| """Convert percentage to absolute value 0..255."""
return (percent*255.0)/100.0
| devs.append(TPLinkSmartBulb(dev))
async_add_entities(devs, True)
return True
def brightness_to_percentage(byt):
"""Convert brightness from absolute 0..255 to percentage."""
return int((byt*100.0)/255.0)
def brightness_from_percentage(percent):
| 64 | 64 | 31 | 6 | 58 | shanbs/home-assistant | homeassistant/components/tplink/light.py | Python | brightness_from_percentage | brightness_from_percentage | 57 | 59 | 57 | 57 | a7eff4b4975544f3c8d623c311a0a27fb5c5f2cd | bigcode/the-stack | train |
5554141f6862eca19db933f6 | train | function | def async_setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the platform.
Deprecated.
"""
_LOGGER.warning('Loading as a platform is no longer supported, '
'convert to use the tplink component.')
| def async_setup_platform(hass, config, add_entities, discovery_info=None):
| """Set up the platform.
Deprecated.
"""
_LOGGER.warning('Loading as a platform is no longer supported, '
'convert to use the tplink component.')
|
_LOGGER = logging.getLogger(__name__)
ATTR_CURRENT_POWER_W = 'current_power_w'
ATTR_DAILY_ENERGY_KWH = 'daily_energy_kwh'
ATTR_MONTHLY_ENERGY_KWH = 'monthly_energy_kwh'
def async_setup_platform(hass, config, add_entities, discovery_info=None):
| 64 | 64 | 53 | 16 | 48 | shanbs/home-assistant | homeassistant/components/tplink/light.py | Python | async_setup_platform | async_setup_platform | 32 | 38 | 32 | 32 | 2c0e6ce815cd282ec1703dc69788dc15641094d1 | bigcode/the-stack | train |
82f7da79fa5cbda9abc3b6de | train | function | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up discovered switches."""
devs = []
for dev in hass.data[TPLINK_DOMAIN][CONF_LIGHT]:
devs.append(TPLinkSmartBulb(dev))
async_add_entities(devs, True)
return True
| async def async_setup_entry(hass, config_entry, async_add_entities):
| """Set up discovered switches."""
devs = []
for dev in hass.data[TPLINK_DOMAIN][CONF_LIGHT]:
devs.append(TPLinkSmartBulb(dev))
async_add_entities(devs, True)
return True
| ass, config, add_entities, discovery_info=None):
"""Set up the platform.
Deprecated.
"""
_LOGGER.warning('Loading as a platform is no longer supported, '
'convert to use the tplink component.')
async def async_setup_entry(hass, config_entry, async_add_entities):
| 63 | 64 | 66 | 15 | 48 | shanbs/home-assistant | homeassistant/components/tplink/light.py | Python | async_setup_entry | async_setup_entry | 41 | 49 | 41 | 41 | cce1c99dcf0e4e51df1881856bd2ad3d0389c92f | bigcode/the-stack | train |
3ccd5c9ab508001bea0008a5 | train | class | class JTAGSubtarget(Module):
def __init__(self, pads, out_fifo, in_fifo, period_cyc):
self.submodules.bus = bus = JTAGBus(pads)
###
half_cyc = int(period_cyc // 2)
timer = Signal(max=half_cyc)
timer_rdy = Signal()
timer_stb = Signal()
self.comb += timer... | class JTAGSubtarget(Module):
| def __init__(self, pads, out_fifo, in_fifo, period_cyc):
self.submodules.bus = bus = JTAGBus(pads)
###
half_cyc = int(period_cyc // 2)
timer = Signal(max=half_cyc)
timer_rdy = Signal()
timer_stb = Signal()
self.comb += timer_rdy.eq(timer == 0)
s... | self.trst = Signal(reset=1)
###
self.comb += [
pads.tck_t.oe.eq(1),
pads.tck_t.o.eq(self.tck),
pads.tms_t.oe.eq(1),
pads.tms_t.o.eq(self.tms),
pads.tdi_t.oe.eq(1),
pads.tdi_t.o.eq(self.tdi),
]
self.specials += [... | 256 | 256 | 1,146 | 7 | 248 | gregdavill/Glasgow | software/glasgow/applet/jtag/__init__.py | Python | JTAGSubtarget | JTAGSubtarget | 54 | 196 | 54 | 54 | fd14a60b66b272fd05104872298ac8dceb57b517 | bigcode/the-stack | train |
16ca317ff736b059ea7a1e99 | train | class | class JTAGApplet(GlasgowApplet, name="jtag"):
logger = logging.getLogger(__name__)
help = "test integrated circuits via IEEE 1149.1 JTAG"
description = """
Identify, test and debug integrated circuits and board assemblies via IEEE 1149.1 JTAG.
"""
__pins = ("tck", "tms", "tdi", "tdo", "trst")
... | class JTAGApplet(GlasgowApplet, name="jtag"):
| logger = logging.getLogger(__name__)
help = "test integrated circuits via IEEE 1149.1 JTAG"
description = """
Identify, test and debug integrated circuits and board assemblies via IEEE 1149.1 JTAG.
"""
__pins = ("tck", "tms", "tdi", "tdo", "trst")
@classmethod
def add_build_arguments(c... | , endian="little")
data = await self.lower.exchange_dr(self._dr_prefix + data + self._dr_suffix)
if self._dr_suffix:
return data[len(self._dr_prefix):-len(self._dr_suffix)]
else:
return data[len(self._dr_prefix):]
async def read_dr(self, count, idempotent=False):
... | 256 | 256 | 1,504 | 15 | 240 | gregdavill/Glasgow | software/glasgow/applet/jtag/__init__.py | Python | JTAGApplet | JTAGApplet | 635 | 775 | 635 | 635 | 33cddf52bb0e16bd4c26c9a8cfe82c1e6023117d | bigcode/the-stack | train |
366a73213b55243e8999cfc4 | train | class | class TAPInterface:
def __init__(self, lower, ir_prefix, ir_suffix, dr_prefix, dr_suffix):
self.lower = lower
self._ir_prefix = ir_prefix
self._ir_suffix = ir_suffix
self._ir_overhead = len(ir_prefix) + len(ir_suffix)
self._dr_prefix = dr_prefix
self._dr_suffix ... | class TAPInterface:
| def __init__(self, lower, ir_prefix, ir_suffix, dr_prefix, dr_suffix):
self.lower = lower
self._ir_prefix = ir_prefix
self._ir_suffix = ir_suffix
self._ir_overhead = len(ir_prefix) + len(ir_suffix)
self._dr_prefix = dr_prefix
self._dr_suffix = dr_suffix
... | = irs[tap]
total_ir_length = sum(length for offset, length in irs)
dr_offset, dr_length = tap, 1
total_dr_length = len(idcodes)
bypass = bitarray("1", endian="little")
def affix(offset, length, total_length):
prefix = bypass * offset
suffix = bypass * (... | 129 | 129 | 430 | 4 | 125 | gregdavill/Glasgow | software/glasgow/applet/jtag/__init__.py | Python | TAPInterface | TAPInterface | 587 | 632 | 587 | 587 | 1650844f073867d0b157d4ebf52d904378c2f630 | bigcode/the-stack | train |
3fc3c292e3b0e64dc2860903 | train | class | class JTAGInterface:
def __init__(self, interface, logger):
self.lower = interface
self._logger = logger
self._level = logging.DEBUG if self._logger.name == __name__ else logging.TRACE
self._state = "Unknown"
self._current_ir = None
def _log_l(self, message, *ar... | class JTAGInterface:
| def __init__(self, interface, logger):
self.lower = interface
self._logger = logger
self._level = logging.DEBUG if self._logger.name == __name__ else logging.TRACE
self._state = "Unknown"
self._current_ir = None
def _log_l(self, message, *args):
self._lo... | di, shreg_o[0]),
),
NextValue(bus.tck, 0),
NextValue(shreg_o, Cat(shreg_o[1:], 1)),
NextValue(count, count - 1),
NextValue(bit, bit + 1),
NextState("SHIFT-HOLD")
)
)
self.fsm.act("SHIFT-HOLD",
... | 256 | 256 | 3,223 | 5 | 251 | gregdavill/Glasgow | software/glasgow/applet/jtag/__init__.py | Python | JTAGInterface | JTAGInterface | 199 | 584 | 199 | 199 | 794b085b8983363aa3cd52b1cb829231fafbad4c | bigcode/the-stack | train |
18499d3548ab1f393c25b661 | train | class | class JTAGBus(Module):
def __init__(self, pads):
self.tck = Signal(reset=1)
self.tms = Signal(reset=1)
self.tdo = Signal(reset=1)
self.tdi = Signal(reset=1)
self.trst_z = Signal(reset=0)
self.trst = Signal(reset=1)
###
self.comb += [
pa... | class JTAGBus(Module):
| def __init__(self, pads):
self.tck = Signal(reset=1)
self.tms = Signal(reset=1)
self.tdo = Signal(reset=1)
self.tdi = Signal(reset=1)
self.trst_z = Signal(reset=0)
self.trst = Signal(reset=1)
###
self.comb += [
pads.tck_t.oe.eq(1),
... | asyncio
from bitarray import bitarray
from migen import *
from migen.genlib.cdc import MultiReg
from .. import *
from ...support.pyrepl import *
from ...gateware.pads import *
from ...database.jedec import *
from ...arch.jtag import *
class JTAGBus(Module):
| 66 | 66 | 220 | 6 | 60 | gregdavill/Glasgow | software/glasgow/applet/jtag/__init__.py | Python | JTAGBus | JTAGBus | 15 | 41 | 15 | 15 | 0e9eff905c2ab7c27e359116d4f5833a4b1b4e55 | bigcode/the-stack | train |
08f3d770de8b2f219e9630be | train | class | class JTAGAppletTestCase(GlasgowAppletTestCase, applet=JTAGApplet):
@synthesis_test
def test_build(self):
self.assertBuilds()
| class JTAGAppletTestCase(GlasgowAppletTestCase, applet=JTAGApplet):
@synthesis_test
| def test_build(self):
self.assertBuilds()
| .logger.error("cannot select TAP #%d" % args.tap_index)
return
await AsyncInteractiveConsole(locals={"tap_iface":tap_iface}).interact()
# -------------------------------------------------------------------------------------------------
class JTAGAppletTestCase(GlasgowAppletTestCase, applet... | 64 | 64 | 39 | 27 | 37 | gregdavill/Glasgow | software/glasgow/applet/jtag/__init__.py | Python | JTAGAppletTestCase | JTAGAppletTestCase | 779 | 782 | 779 | 780 | 5cbde436c9c5ed409fa2c41b2608095d09ebf7a2 | bigcode/the-stack | train |
b2751f51a51d9f4d68f56130 | train | function | def save_txt(fn, txt_info):
f = open(fn, "w")
for text in txt_info:
# print(text)
f.write(text)
| def save_txt(fn, txt_info):
| f = open(fn, "w")
for text in txt_info:
# print(text)
f.write(text)
| _q), (baseline_features, baseline_q), save_name, txt_info,
verbose = True, iteration = 30)
txt_info.append("\n")
file_name = "{}/info.txt".format(exp_path_dp)
save_txt(file_name, txt_info)
def save_txt(fn, txt_info):
| 63 | 64 | 34 | 8 | 55 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | save_txt | save_txt | 697 | 701 | 697 | 697 | a59dbf2cae01d07fdee58101f496028417503e0a | bigcode/the-stack | train |
1449f40e235652ed350d7165 | train | function | def MSX(vector):
vector = np.array(vector)
indeces = np.argsort(vector)[::-1]
negative_sum = sum(vector[vector < 0])
pos_sum = 0
MSX_idx = []
for idx in indeces:
pos_sum += vector[idx]
MSX_idx.append(idx)
if pos_sum > abs(negative_sum):
break
return MSX_id... | def MSX(vector):
| vector = np.array(vector)
indeces = np.argsort(vector)[::-1]
negative_sum = sum(vector[vector < 0])
pos_sum = 0
MSX_idx = []
for idx in indeces:
pos_sum += vector[idx]
MSX_idx.append(idx)
if pos_sum > abs(negative_sum):
break
return MSX_idx, vector[MSX_idx... | + center_pos, v + 0.01 * v, "sum ≈ {}".format(np.round(v, 4)), color='black', fontweight='ultralight', ha='center')
plt.savefig(save_name + image_end)
# vis.matplot(plt)
def MSX(vector):
| 63 | 64 | 95 | 5 | 58 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | MSX | MSX | 138 | 149 | 138 | 138 | 17988c081884d6bdaa375c5a7c59043b9c530312 | bigcode/the-stack | train |
cdc960e51208bcb2e29336ea | train | function | def pretty_print_action(action):
for i in range(len(action)):
action[i] = int(action[i])
txt = ""
txt += ("Top_M: {}, Top_B: {}, Top_I: {}\n".format(action[0], action[1], action[2]))
txt += ("Bottom_M: {}, Bottom_B: {}, Bottom_I: {}\n".format(action[3], action[4], action[5]))
txt += ("Pylon:... | def pretty_print_action(action):
| for i in range(len(action)):
action[i] = int(action[i])
txt = ""
txt += ("Top_M: {}, Top_B: {}, Top_I: {}\n".format(action[0], action[1], action[2]))
txt += ("Bottom_M: {}, Bottom_B: {}, Bottom_I: {}\n".format(action[3], action[4], action[5]))
txt += ("Pylon: {}\n".format(action[6]))
ret... | ("S_T: {:^5},S_B: {:^5},E_T: {:^5},E_B: {:^5}\n\n".format(
state[63],state[64],state[65],state[66]))
return all_text
def pretty_print_action(action):
| 62 | 64 | 108 | 6 | 55 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | pretty_print_action | pretty_print_action | 778 | 785 | 778 | 778 | 3d59451a943fd5a7b72d34f8ddbf745d3315e7bc | bigcode/the-stack | train |
8b636bc82965d108a3bba967 | train | function | def detail_plot(values, group, save_name, y_label = "", values_msx = None, q_values = None, IGX_action = None):
plt.clf()
global TITLES
global XLABELS
# print(values.shape, values_msx.shape)
# grid = plt.GridSpec(math.ceil(len(TITLES) / SUB_PLOT_NUN), SUB_PLOT_NUN)
fig, axs = plt.subplots(m... | def detail_plot(values, group, save_name, y_label = "", values_msx = None, q_values = None, IGX_action = None):
| plt.clf()
global TITLES
global XLABELS
# print(values.shape, values_msx.shape)
# grid = plt.GridSpec(math.ceil(len(TITLES) / SUB_PLOT_NUN), SUB_PLOT_NUN)
fig, axs = plt.subplots(math.ceil(len(TITLES) / SUB_PLOT_NUN), SUB_PLOT_NUN, figsize = SUB_FIGURE_SIZE)
fig.delaxes(axs[math.ceil(len... | print(np_values)
# print(max_values)
for i, v in enumerate(max_values):
plt.gca().text(i + center_pos, v + 0.01 * v, "sum ≈ {}".format(np.round(v, 4)), color='black', fontweight='ultralight', ha='center')
plt.savefig(save_name + image_end)
# vis.matplot(plt)
def MSX(vector):
vector = n... | 212 | 212 | 707 | 31 | 181 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | detail_plot | detail_plot | 151 | 207 | 151 | 151 | cbead25ffa129b08df8af3818227c3e0dc4094b8 | bigcode/the-stack | train |
d8fb1481484790b38c1b60ab | train | function | def denormalization(values):
denorm_values = np.array(values).copy()
if VERSION in ["GFVs_all_1"]:
denorm_values[8 : 10] /= norm_vector_GVFs_all_v1[0]
denorm_values[10 : 22] /= norm_vector_GVFs_all_v1[1]
denorm_values[22 : 82] /= norm_vector_GVFs_all_v1[2]
denorm_values[82 : 94] ... | def denormalization(values):
| denorm_values = np.array(values).copy()
if VERSION in ["GFVs_all_1"]:
denorm_values[8 : 10] /= norm_vector_GVFs_all_v1[0]
denorm_values[10 : 22] /= norm_vector_GVFs_all_v1[1]
denorm_values[22 : 82] /= norm_vector_GVFs_all_v1[2]
denorm_values[82 : 94] /= norm_vector_GVFs_all_v1[3]... | _vector_GVFs_all_v1[2]
norm_values[82 : 94] *= norm_vector_GVFs_all_v1[3]
norm_values[94 : 130] *= norm_vector_GVFs_all_v1[4]
return norm_values.tolist()
def denormalization(values):
| 64 | 64 | 145 | 6 | 58 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | denormalization | denormalization | 45 | 53 | 45 | 45 | a1e276920ecf680e4f583b5afb8472737052c75e | bigcode/the-stack | train |
3e9ec8ac8f831c8675f2251f | train | function | def pretty_print(state, text = ""):
state_list = state.copy().tolist()
state = []
all_text = ""
for s in state_list:
state.append(str(int(s)))
all_text += text
all_text += ("Wave:\t" + state[-1])
all_text += (" Minerals:\t" + state[0])
all_text += (" Building_Self\n")
all_tex... | def pretty_print(state, text = ""):
| state_list = state.copy().tolist()
state = []
all_text = ""
for s in state_list:
state.append(str(int(s)))
all_text += text
all_text += ("Wave:\t" + state[-1])
all_text += (" Minerals:\t" + state[0])
all_text += (" Building_Self\n")
all_text += ("T:{:^5},{:^5},{:^5},B:{:^5},{... | state_txt_2 = pretty_print(state_2, text = "State 2:\n")
txt_info.append(state_txt_2)
txt_info.append("baseline state best action: {}\n".format(pretty_print_action(baseline_actions[baseline_best_idx].tolist())))
txt_info.append("baseline features: {}\n".format(baseline_features.tolist()))
txt_info.a... | 255 | 256 | 895 | 9 | 246 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | pretty_print | pretty_print | 704 | 775 | 704 | 704 | 7af5e48a6d7451e6ab74c0cf285678facbf7826f | bigcode/the-stack | train |
bf28eff47bc014a0128f1bff | train | function | def intergated_gradients(model, x, txt_info, save_name, iteration = 100, baseline = None, verbose = True):
y_baseline = model(baseline).item()
x = x.view(1, -1)
x.size()[1]
optimizer = Adam(model.parameters(), lr = 0.001)
if baseline is None:
baseline = torch.zeros_like(x)
# elif verbose... | def intergated_gradients(model, x, txt_info, save_name, iteration = 100, baseline = None, verbose = True):
| y_baseline = model(baseline).item()
x = x.view(1, -1)
x.size()[1]
optimizer = Adam(model.parameters(), lr = 0.001)
if baseline is None:
baseline = torch.zeros_like(x)
# elif verbose:
# txt_info.append("baseline: {}\n".format(baseline))
intergated_grad = torch.zeros_like(x)
... | , t_feature, txt_info, save_name,
baseline = b_feature, verbose = verbose, iteration = iteration)
return msx_idx, msx_value
def differenc_vector_action(model, target, baseline, save_name, txt_info = [], verbose = True, iteration = 100, show_image = True):
t_f... | 174 | 174 | 582 | 29 | 144 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | intergated_gradients | intergated_gradients | 514 | 555 | 514 | 514 | c0d8356847742d1bb56f68b20374e33cbd54454e | bigcode/the-stack | train |
d93748d491a35b043afcf24e | train | function | def plot_IG_MSX(values, values_msx, group, save_name, elements = [], title = 'decomposition values', y_label = "", q_values = None, IGX_action = None):
global VERSION
global XLABELS
if VERSION in ["GFVs_all_1"]:
if "features" in save_name:
values = normalization(values)
if "... | def plot_IG_MSX(values, values_msx, group, save_name, elements = [], title = 'decomposition values', y_label = "", q_values = None, IGX_action = None):
| global VERSION
global XLABELS
if VERSION in ["GFVs_all_1"]:
if "features" in save_name:
values = normalization(values)
if "weights" in save_name:
values = denormalization(values)
detail_plot(values, group, save_name, y_label = y_label, values_msx = values_msx,... | 0.5,-0.07), loc='upper center')
for mb in MSX_bars:
mb.set_hatch("////")
y_lim = ax.get_ylim()
np_values = np.array(values).T
txt_pos = y_lim[1] - (y_lim[1] - y_lim[0]) / 25
max_values = np_values.max(axis = 1)
sum_values = np_values.sum(axis = 1)
# print(np_values)
# p... | 255 | 256 | 1,071 | 43 | 212 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | plot_IG_MSX | plot_IG_MSX | 324 | 410 | 324 | 325 | bfd7831f810b517390229e91d5bf190c7c34361c | bigcode/the-stack | train |
42816deb00e0d9a19e332eab | train | function | def plot_detail_sub(values, values_msx, group, ax, idx, elements = [], title = 'decomposition values', y_label = "", q_values = None, IGX_action = None, xl = None):
global VERSION
global XLABELS
# set width of bar
length = len(values[0])
barWidth = 1 / (len(values) + 1)
x_labels_fe... | def plot_detail_sub(values, values_msx, group, ax, idx, elements = [], title = 'decomposition values', y_label = "", q_values = None, IGX_action = None, xl = None):
| global VERSION
global XLABELS
# set width of bar
length = len(values[0])
barWidth = 1 / (len(values) + 1)
x_labels_feature = ["F{}".format(x + 1 + idx) for x in range(len(values))]
if idx == 0:
ax.bar(0, 0, width=barWidth, hatch="////", color = "white", label="MSX bar")
... |
fig.savefig("{}_detail{}".format(save_name, image_end))
fig.clear()
matplotlib.use('Agg')
plt.close(fig)
def plot_legend(labels):
# colors = ["g", "w"]
texts = labels
plt.bar([1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],
label="MSX Bar", hatch="////", color = "whi... | 255 | 256 | 1,421 | 46 | 209 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | plot_detail_sub | plot_detail_sub | 223 | 321 | 223 | 224 | 6032a1a16e5fe4496ece1390b5a6e7c00c1cbce3 | bigcode/the-stack | train |
4fb5145beb40622c8af23fdb | train | function | def esf_state_pair(fq_model, state_1, frame_1, state_2, frame_2, env, save_path,
entail = "",txt_info = None, version = ""):
set_VERSION_and_LABELS(version)
if txt_info is None:
txt_info = []
action_1 = env.get_big_A(state_1[env.miner_index], state_1[env.pylon_index])
... | def esf_state_pair(fq_model, state_1, frame_1, state_2, frame_2, env, save_path,
entail = "",txt_info = None, version = ""):
| set_VERSION_and_LABELS(version)
if txt_info is None:
txt_info = []
action_1 = env.get_big_A(state_1[env.miner_index], state_1[env.pylon_index])
action_2 = env.get_big_A(state_2[env.miner_index], state_2[env.pylon_index])
state_actions_1 = env.combine_sa(state_1, action_1)
state_... | _idx].tolist(), v_features[sub_action].tolist()]).T
q_print_values = [q_best_value.item(), q_value[sub_action].item()]
# print(11111111111111)
plot_action_group(GVFs_plot, ans, save_name + "_features", title = 'GVFs', y_label = "GVFs Values", q_values = q_print_values)
sub_action = sub_a... | 256 | 256 | 985 | 42 | 214 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | esf_state_pair | esf_state_pair | 628 | 695 | 628 | 629 | 0b94e114307b90139a11f4156690a3acd063151a | bigcode/the-stack | train |
dfd34fc6ee69ba59e53d4916 | train | function | def set_VERSION_and_LABELS(version):
global VERSION
global TITLES
global XLABELS
VERSION = version
if VERSION == "GFVs_all_1":
TITLES = OrderedDict({"Destory and Lowest HP Probability": (0, 8),
"Currency to be Earned": (8, 2),
"Expected Units to Spawn... | def set_VERSION_and_LABELS(version):
| global VERSION
global TITLES
global XLABELS
VERSION = version
if VERSION == "GFVs_all_1":
TITLES = OrderedDict({"Destory and Lowest HP Probability": (0, 8),
"Currency to be Earned": (8, 2),
"Expected Units to Spawn": (10, 12),
"Futur... | ("Top_M: {}, Top_B: {}, Top_I: {}\n".format(action[0], action[1], action[2]))
txt += ("Bottom_M: {}, Bottom_B: {}, Bottom_I: {}\n".format(action[3], action[4], action[5]))
txt += ("Pylon: {}\n".format(action[6]))
return txt
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy ... | 256 | 256 | 2,679 | 8 | 247 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | set_VERSION_and_LABELS | set_VERSION_and_LABELS | 804 | 894 | 804 | 804 | d091b27a124775825145dc6e5d73bab27cf0f6f1 | bigcode/the-stack | train |
ef5059b146a3f3d5234ae1b0 | train | function | def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canva... | def fig2data ( fig ):
| """
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
... | [1], action[2]))
txt += ("Bottom_M: {}, Bottom_B: {}, Bottom_I: {}\n".format(action[3], action[4], action[5]))
txt += ("Pylon: {}\n".format(action[6]))
return txt
def fig2data ( fig ):
| 64 | 64 | 170 | 7 | 56 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | fig2data | fig2data | 786 | 802 | 786 | 786 | ba1269a5022d52a4ae48742666d0740fe87de6a5 | bigcode/the-stack | train |
8b601b8531a225da9bd89fef | train | function | def plot_msx_plus(values, save_name, title = 'decomposition values', y_label = ""):
# if VERSION in ["GFVs_all_1"]:
# detail_plot(values, save_name)
global XLABELS
plt.clf()
x_pos = []
x_name = []
# idx = np.argsort(np.array(values))[::-1]
# values = sorted(values, reverse=True)
... | def plot_msx_plus(values, save_name, title = 'decomposition values', y_label = ""):
# if VERSION in ["GFVs_all_1"]:
# detail_plot(values, save_name)
| global XLABELS
plt.clf()
x_pos = []
x_name = []
# idx = np.argsort(np.array(values))[::-1]
# values = sorted(values, reverse=True)
idx = list(range(len(values)))
# print(XLABELS)
# print(idx)
for i in range(len(values)):
x_pos.append(i + 1)
if VERSION == "v10... | (True)
plt.gca().set_axisbelow(True)
plt.xticks(x_pos, x_name, rotation=40)
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
plt.ylabel(y_label)
plt.title(title)
# vis.matplot(plt)
plt.savefig(save_name + image_end)
# print(VERSION)
def plot_msx_plus(values, save_name, title... | 125 | 125 | 418 | 43 | 82 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | plot_msx_plus | plot_msx_plus | 96 | 135 | 96 | 98 | 8cb820d411e347d71775180ca3c1d8cb2cddc1bb | bigcode/the-stack | train |
d07763cc171728f1536d0688 | train | function | def normalization(values):
norm_values = np.array(values).copy()
if VERSION in ["GFVs_all_1"]:
norm_values[8 : 10] *= norm_vector_GVFs_all_v1[0]
norm_values[10 : 22] *= norm_vector_GVFs_all_v1[1]
norm_values[22 : 82] *= norm_vector_GVFs_all_v1[2]
norm_values[82 : 94] *= norm_vect... | def normalization(values):
| norm_values = np.array(values).copy()
if VERSION in ["GFVs_all_1"]:
norm_values[8 : 10] *= norm_vector_GVFs_all_v1[0]
norm_values[10 : 22] *= norm_vector_GVFs_all_v1[1]
norm_values[22 : 82] *= norm_vector_GVFs_all_v1[2]
norm_values[82 : 94] *= norm_vector_GVFs_all_v1[3]
n... | _NUN = 3
VERSION = ""
TITLES = []
XLABELS = []
norm_vector_GVFs_all_v1 = np.array([1500, 100, 30, 200, 5000])
# image_end = ".png"
image_end = ".jpg"
def normalization(values):
| 64 | 64 | 136 | 4 | 60 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | normalization | normalization | 35 | 43 | 35 | 35 | f8eac91a7d3862650d66d09413416d3becee2082 | bigcode/the-stack | train |
32ff878eeacc1d3d9d5588a5 | train | function | def esf_action_pair(fq_model, state, frame, state_actions, actions, save_path,
txt_info = None, pick_actions = [1, 1, 1], decision_point = "undifined", version = ""):
set_VERSION_and_LABELS(version)
if txt_info is None:
txt_info = []
exp_path_dp = save_path + "/{}".format(decisio... | def esf_action_pair(fq_model, state, frame, state_actions, actions, save_path,
txt_info = None, pick_actions = [1, 1, 1], decision_point = "undifined", version = ""):
| set_VERSION_and_LABELS(version)
if txt_info is None:
txt_info = []
exp_path_dp = save_path + "/{}".format(decision_point)
# if not os.path.isdir(exp_path_dp):
# os.mkdir(exp_path_dp)
os.makedirs(exp_path_dp, exist_ok=True)
state_txt = pretty_print(state, text = "State:\n")
tx... | Gradient', y_label = "IGX", IGX_action = "Best_action")
msx_vector = np.zeros(len(x[0]))
msx_vector[MSX_idx] = MSX_values
# plot_msx_plus(msx_vector, save_name + "_MSX+", title = 'MSX+', y_label = "IGX")
# plot_action_group(np.array([msx_vector]).T, ["Sub_action"], save_name + "_MSX+",... | 256 | 256 | 891 | 50 | 205 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | esf_action_pair | esf_action_pair | 557 | 626 | 557 | 558 | 667db7d964bda004d80c320c86bf474033a56948 | bigcode/the-stack | train |
4c89ec8828d85b6cca863d74 | train | function | def plot_action_group(values, group, save_name, elements = [], title = 'decomposition values', y_label = "", q_values = None, IGX_action = None):
global VERSION
global XLABELS
# print(2)
if VERSION in ["GFVs_all_1"]:
if "features" in save_name:
values = normalization(values)
... | def plot_action_group(values, group, save_name, elements = [], title = 'decomposition values', y_label = "", q_values = None, IGX_action = None):
| global VERSION
global XLABELS
# print(2)
if VERSION in ["GFVs_all_1"]:
if "features" in save_name:
values = normalization(values)
if "weights" in save_name:
values = denormalization(values)
# print(3333333333333)
detail_plot(values, group, save_nam... | )
sum_values = np_values.sum(axis = 1)
# print(np_values)
# print(max_values)
for i, v in enumerate(max_values):
if q_values is None:
plt.gca().text(i + center_pos, txt_pos, "{} > {}".format(IGX_action, group[i]), color='black', fontweight='ultralight', ha='center')
else... | 255 | 256 | 988 | 37 | 218 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | plot_action_group | plot_action_group | 415 | 495 | 415 | 416 | 09a2a91c9c1a960116b5492922fdab4e9fb0d7f7 | bigcode/the-stack | train |
7e58853212bcc6655929ec32 | train | function | def differenc_vector_state(model, target, baseline, save_name, txt_info = [], verbose = True, iteration = 100, show_image = True):
t_feature, t_value = target
b_feature, b_value = baseline
(msx_idx, msx_value), _ = intergated_gradients(model, t_feature, txt_info, save_name,
... | def differenc_vector_state(model, target, baseline, save_name, txt_info = [], verbose = True, iteration = 100, show_image = True):
| t_feature, t_value = target
b_feature, b_value = baseline
(msx_idx, msx_value), _ = intergated_gradients(model, t_feature, txt_info, save_name,
baseline = b_feature, verbose = verbose, iteration = iteration)
return msx_idx, msx_value
| right'].set_color('none')
# plt.gca().spines['top'].set_color('none')
plt.savefig(save_name + image_end)
def differenc_vector_state(model, target, baseline, save_name, txt_info = [], verbose = True, iteration = 100, show_image = True):
| 64 | 64 | 103 | 32 | 32 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | differenc_vector_state | differenc_vector_state | 497 | 503 | 497 | 497 | 00e9667eede8b83bdfc4061efb52f85f7d4e3484 | bigcode/the-stack | train |
f8d6e1747f00181b3406956d | train | function | def plot_legend(labels):
# colors = ["g", "w"]
texts = labels
plt.bar([1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],
label="MSX Bar", hatch="////", color = "white")
for i in range(len(texts)):
plt.bar([1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],
label="{:s}".format(texts[i]) )... | def plot_legend(labels):
# colors = ["g", "w"]
| texts = labels
plt.bar([1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],
label="MSX Bar", hatch="////", color = "white")
for i in range(len(texts)):
plt.bar([1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],
label="{:s}".format(texts[i]) )
plt.legend(bbox_to_anchor=(0, -0.15, 1, 0),nco... | (True)
# autolabel_hatch(rects, x_name)
fig.savefig("{}_detail{}".format(save_name, image_end))
fig.clear()
matplotlib.use('Agg')
plt.close(fig)
def plot_legend(labels):
# colors = ["g", "w"]
| 63 | 64 | 178 | 17 | 46 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | plot_legend | plot_legend | 209 | 221 | 209 | 211 | d03612aed952813a2768ed90a97d600888c24c8b | bigcode/the-stack | train |
868ae812c134d27307be153c | train | function | def differenc_vector_action(model, target, baseline, save_name, txt_info = [], verbose = True, iteration = 100, show_image = True):
t_feature, t_value = target
b_feature, b_value = baseline
(msx_idx, msx_value), intergated_grad = intergated_gradients(model, t_feature, txt_info, save_name,
... | def differenc_vector_action(model, target, baseline, save_name, txt_info = [], verbose = True, iteration = 100, show_image = True):
| t_feature, t_value = target
b_feature, b_value = baseline
(msx_idx, msx_value), intergated_grad = intergated_gradients(model, t_feature, txt_info, save_name,
baseline = b_feature, verbose = verbose, iteration = iteration)
return msx_idx,... | , txt_info, save_name,
baseline = b_feature, verbose = verbose, iteration = iteration)
return msx_idx, msx_value
def differenc_vector_action(model, target, baseline, save_name, txt_info = [], verbose = True, iteration = 100, show_image = True):
| 64 | 64 | 110 | 32 | 31 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | differenc_vector_action | differenc_vector_action | 505 | 512 | 505 | 505 | caaf9c7ec2c41de917e688539fd7a90cf5e963c1 | bigcode/the-stack | train |
4621202a51a6a9171f4d7c90 | train | function | def plot(values, save_name, title = 'decomposition values', y_label = ""):
global VERSION
global XLABELS
# if VERSION in ["GFVs_all_1"]:
# if "features" in save_name:
# values = normalization(values)
# if "weights" in save_name:
# values = denormalization(values)... | def plot(values, save_name, title = 'decomposition values', y_label = ""):
| global VERSION
global XLABELS
# if VERSION in ["GFVs_all_1"]:
# if "features" in save_name:
# values = normalization(values)
# if "weights" in save_name:
# values = denormalization(values)
# detail_plot(values, save_name)
plt.clf()
x_pos = []
x_nam... | 1[1]
denorm_values[22 : 82] /= norm_vector_GVFs_all_v1[2]
denorm_values[82 : 94] /= norm_vector_GVFs_all_v1[3]
denorm_values[94 : 130] /= norm_vector_GVFs_all_v1[4]
return denorm_values.tolist()
def plot(values, save_name, title = 'decomposition values', y_label = ""):
| 97 | 97 | 324 | 20 | 77 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | plot | plot | 55 | 92 | 55 | 56 | 55290d2c7b8c0cedf67e82a85a5d07c8f4d10b54 | bigcode/the-stack | train |
4eb00b4e5806073fa7ba8c6c | train | function | def pretty_print_to_state(pretty_state):
state = np.zeros(68)
count = 0
self_units = []
enemy_units = []
for i, ps in enumerate(pretty_state):
numbers = [float(word) for word in ps.split() if word.isdigit()]
if len(numbers) == 0:
continue
numbers_np = np.array(num... | def pretty_print_to_state(pretty_state):
| state = np.zeros(68)
count = 0
self_units = []
enemy_units = []
for i, ps in enumerate(pretty_state):
numbers = [float(word) for word in ps.split() if word.isdigit()]
if len(numbers) == 0:
continue
numbers_np = np.array(numbers)
if count == 0:
... | _B", "FT_I", "FB_M", "FB_B", "FB_I", "ET_M", "ET_B", "ET_I", "EB_M", "EB_B", "EB_I", "FT_N", "FB_N", "ET_N", "EB_N", "ETB"]
def pretty_print_to_state(pretty_state):
| 71 | 72 | 241 | 9 | 62 | osu-xai/abp | abp/explanations/embedded_semantic_features.py | Python | pretty_print_to_state | pretty_print_to_state | 897 | 923 | 897 | 897 | cb506adb355fd4d257f48773ba721d0491550474 | bigcode/the-stack | train |
776b263116c88d726c13416e | train | function | def solve(grid):
"""
Find the solution to a Sudoku grid.
Args:
grid(string): a string representing a sudoku grid.
Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns:
The dictionary representation of the final sudoku grid. Fals... | def solve(grid):
| """
Find the solution to a Sudoku grid.
Args:
grid(string): a string representing a sudoku grid.
Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns:
The dictionary representation of the final sudoku grid. False if no solution ... | 1)
# Now use recurrence to solve each one of the resulting sudokus, and
for value in values[s]:
new_sudoku = values.copy()
new_sudoku[s] = value
attempt = search(new_sudoku)
if attempt:
return attempt
def solve(grid):
| 64 | 64 | 108 | 4 | 59 | Prider/AI | sudoku-5421/solution.py | Python | solve | solve | 189 | 200 | 189 | 189 | a0f7f4ca6bdcb35f768868389d7f6b3f8bfbe7f4 | bigcode/the-stack | train |
21f6f75987593e4737f82aa2 | train | function | def reduce_puzzle(values):
"""
Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False.
If the sudoku is solved, return the sudoku.
If after an iteration of both functions, the sudoku remains the same, return the sudoku.
Input: A sudoku in dicti... | def reduce_puzzle(values):
| """
Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False.
If the sudoku is solved, return the sudoku.
If after an iteration of both functions, the sudoku remains the same, return the sudoku.
Input: A sudoku in dictionary form.
Output: The... | in dictionary form.
Output: Resulting Sudoku in dictionary form after filling in only choices.
"""
for unit in unitlist:
for digit in '123456789':
dplaces = [box for box in unit if digit in values[box]]
if len(dplaces) == 1:
values[dplaces[0]] = digit
ret... | 84 | 84 | 283 | 6 | 77 | Prider/AI | sudoku-5421/solution.py | Python | reduce_puzzle | reduce_puzzle | 143 | 169 | 143 | 143 | bf9f33e3b99ebef42757ad222379373d76773b03 | bigcode/the-stack | train |
ed8eea1b93ca92a5413e1cd1 | train | function | def eliminate(values):
"""Eliminate values from peers of each box with a single value.
Go through all the boxes, and whenever there is a box with a single value,
eliminate this value from the set of values of all its peers.
Args:
values: Sudoku in dictionary form.
Returns:
Resultin... | def eliminate(values):
| """Eliminate values from peers of each box with a single value.
Go through all the boxes, and whenever there is a box with a single value,
eliminate this value from the set of values of all its peers.
Args:
values: Sudoku in dictionary form.
Returns:
Resulting Sudoku in dictionary ... | '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '')
for c in cols))
if r in 'CF': print(line)
return
def eliminate(values):
| 64 | 64 | 141 | 4 | 59 | Prider/AI | sudoku-5421/solution.py | Python | eliminate | eliminate | 109 | 125 | 109 | 109 | 74ada2b6f23798238e4604e224012229797b50ff | bigcode/the-stack | train |
c6ce29ef9a4a6945978ccb48 | train | function | def search(values):
"Using depth-first search and propagation, try all possible values."
# First, reduce the puzzle using the previous function
values = reduce_puzzle(values)
if values is False:
return False ## Failed earlier
if all(len(values[s]) == 1 for s in boxes):
return values... | def search(values):
| "Using depth-first search and propagation, try all possible values."
# First, reduce the puzzle using the previous function
values = reduce_puzzle(values)
if values is False:
return False ## Failed earlier
if all(len(values[s]) == 1 for s in boxes):
return values ## Solved!
# Ch... | loop.
stalled = solved_values_before == solved_values_after
# Sanity check, return False if there is a box with zero available values:
if len([box for box in values.keys() if len(values[box]) == 0]):
return False
return values
def search(values):
| 64 | 64 | 171 | 4 | 59 | Prider/AI | sudoku-5421/solution.py | Python | search | search | 171 | 187 | 171 | 171 | 87323ecd24bd9507183c13abc4a2fde599d4a170 | bigcode/the-stack | train |
ff1d5c3b559c322f55d3a6f9 | train | function | def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers.
"""
# dictionary of digit as a key and number of occurre... | def naked_twins(values):
| """Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers.
"""
# dictionary of digit as a key and number of occurrences in a unit
for un... | twin
values(dict): a dictionary of the form {'box_name': '123456789', ...}
"""
for digit in twins:
new_values = values[box].replace(digit, '')
values = assign_value(values, box, new_values)
pass
def naked_twins(values):
| 64 | 64 | 204 | 6 | 57 | Prider/AI | sudoku-5421/solution.py | Python | naked_twins | naked_twins | 52 | 72 | 52 | 52 | 2ac168bd5b1e930ea32b547f287a9f224847cdc7 | bigcode/the-stack | train |
cb29e7573a0e6c2d79057d5e | train | function | def grid_values(grid):
"""Convert grid string into {<box>: <value>} dict with '123456789' value for empties.
Args:
grid: Sudoku grid in string form, 81 characters long
Returns:
Sudoku grid in dictionary form:
- keys: Box labels, e.g. 'A1'
- values: Value in corresponding box... | def grid_values(grid):
| """Convert grid string into {<box>: <value>} dict with '123456789' value for empties.
Args:
grid: Sudoku grid in string form, 81 characters long
Returns:
Sudoku grid in dictionary form:
- keys: Box labels, e.g. 'A1'
- values: Value in corresponding box, e.g. '8', or '1234567... | unit:
# skip the twin box
if values[box] == key_digit:
continue
# replace other boxes which had twin digists
if set(values[box]).intersection(set(key_digit)):
replace_digit(box, key_digit, va... | 64 | 64 | 160 | 5 | 58 | Prider/AI | sudoku-5421/solution.py | Python | grid_values | grid_values | 74 | 92 | 74 | 74 | 2a017ff109754e3651abfeef4e88911ef7f0fdaa | bigcode/the-stack | train |
837a020f72fb325abf4bf8be | train | function | def cross(A, B):
"Cross product of elements in A and elements in B."
return [s+t for s in A for t in B]
| def cross(A, B):
| "Cross product of elements in A and elements in B."
return [s+t for s in A for t in B]
| import collections
assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
revCols = '987654321'
def cross(A, B):
| 33 | 64 | 33 | 6 | 27 | Prider/AI | sudoku-5421/solution.py | Python | cross | cross | 6 | 8 | 6 | 6 | eebaf6334a5a3db075763cefd403dd3d44eb2a5a | bigcode/the-stack | train |
d688c7360d8c4f82cb4109c1 | train | function | def replace_digit(box, twins, values):
"""Replace digits of twins in each box in units.
Args:
box: an element in A1,A2
twins: two digit belong of twin
values(dict): a dictionary of the form {'box_name': '123456789', ...}
"""
for digit in twins:
new_values = values[box].re... | def replace_digit(box, twins, values):
| """Replace digits of twins in each box in units.
Args:
box: an element in A1,A2
twins: two digit belong of twin
values(dict): a dictionary of the form {'box_name': '123456789', ...}
"""
for digit in twins:
new_values = values[box].replace(digit, '')
values = assig... | # Don't waste memory appending actions that don't actually change any values
if values[box] == value:
return values
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def replace_digit(box, twins, values):
| 64 | 64 | 100 | 9 | 54 | Prider/AI | sudoku-5421/solution.py | Python | replace_digit | replace_digit | 40 | 50 | 40 | 40 | c7bedb9e76e8668cabc4156f41b5aeceab4d05a1 | bigcode/the-stack | train |
cb2dd4d77cccb57c8fac0144 | train | function | def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste memory appending actions that don't actually change any values
if values[box] == value:
return values... | def assign_value(values, box, value):
| """
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste memory appending actions that don't actually change any values
if values[box] == value:
return values
values[box] = value
if len(v... | d1_units + d2_units
units = dict((s, [u for u in unitlist if s in u]) for s in boxes)
peers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)
def assign_value(values, box, value):
| 64 | 64 | 97 | 9 | 55 | Prider/AI | sudoku-5421/solution.py | Python | assign_value | assign_value | 25 | 38 | 25 | 25 | 7dc79574d3ee981393fcb941353d8e1de6ad967a | bigcode/the-stack | train |
49f4731ca4ae7182d3420a98 | train | function | def display(values):
"""
Display the values as a 2-D grid.
Input: The sudoku in dictionary form
Output: None
"""
width = 1+max(len(values[s]) for s in boxes)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '')
... | def display(values):
| """
Display the values as a 2-D grid.
Input: The sudoku in dictionary form
Output: None
"""
width = 1+max(len(values[s]) for s in boxes)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '')
for ... | values = []
all_digits = '123456789'
for c in grid:
if c == '.':
values.append(all_digits)
elif c in all_digits:
values.append(c)
assert len(values) == 81
return dict(zip(boxes, values))
def display(values):
| 64 | 64 | 112 | 4 | 60 | Prider/AI | sudoku-5421/solution.py | Python | display | display | 95 | 107 | 95 | 95 | 67894d5c7388ca2e7523582ec12dfb04a98ba80d | bigcode/the-stack | train |
dfd096c6b1e894a2e1c0d939 | train | function | def only_choice(values):
"""Finalize all values that are the only choice for a unit.
Go through all the units, and whenever there is a unit with a value
that only fits in one box, assign the value to this box.
Input: Sudoku in dictionary form.
Output: Resulting Sudoku in dictionary form after fill... | def only_choice(values):
| """Finalize all values that are the only choice for a unit.
Go through all the units, and whenever there is a unit with a value
that only fits in one box, assign the value to this box.
Input: Sudoku in dictionary form.
Output: Resulting Sudoku in dictionary form after filling in only choices.
... | [box for box in values.keys() if len(values[box]) == 1]
for box in solved_values:
digit = values[box]
for peer in peers[box]:
values[peer] = values[peer].replace(digit,'')
return values
def only_choice(values):
| 64 | 64 | 133 | 5 | 58 | Prider/AI | sudoku-5421/solution.py | Python | only_choice | only_choice | 127 | 141 | 127 | 127 | b933e627ae294ae2630847a7a705585d062599a5 | bigcode/the-stack | train |
3a3bd04c856db8556467e39d | train | function | def append_sort(N, L):
cost = 0
for i in range(1, N):
if L[i-1] >= L[i]:
a, b = L[i-1], L[i]
n = 0
while a >= b + (10**n - 1):
n += 1
b *= 10
L[i] = max(b, a+1)
cost += n
return cost
| def append_sort(N, L):
| cost = 0
for i in range(1, N):
if L[i-1] >= L[i]:
a, b = L[i-1], L[i]
n = 0
while a >= b + (10**n - 1):
n += 1
b *= 10
L[i] = max(b, a+1)
cost += n
return cost
| # Codejam 2021, Round 1A: Append Sort
def append_sort(N, L):
| 22 | 64 | 100 | 7 | 14 | theXYZT/codejam-2021 | Round 1A/append-sort.py | Python | append_sort | append_sort | 3 | 18 | 3 | 3 | c8ba93cc36a67316c5bfe541c4d860a9e6f16f29 | bigcode/the-stack | train |
04dab09f12820efe4ba876ec | train | class | class Loan:
""" Single Loan class
With input principal, rate, payment, and extra payment, compute the amortization schedule, as well as
overall metrics such as time to loan termination, total principal paid, and total interest paid.
"""
def __init__(self, principal, rate, payment, extra_payment=0.0)... | class Loan:
| """ Single Loan class
With input principal, rate, payment, and extra payment, compute the amortization schedule, as well as
overall metrics such as time to loan termination, total principal paid, and total interest paid.
"""
def __init__(self, principal, rate, payment, extra_payment=0.0):
""... | class Loan:
| 3 | 206 | 687 | 3 | 0 | sharonytlau/dash-loan-calculator | algorithms/Loan.py | Python | Loan | Loan | 1 | 68 | 1 | 1 | 04622d84f761ce0488811e725d70b80b8a0460ec | bigcode/the-stack | train |
b743fa01b10f8576c8f510b0 | train | class | class ApiHeaderHandler(BaseMtlsHandler):
async def get(self):
"""
Show request headers for API requests. No AuthZ required.
---
description: Shows all headers received by server
responses:
200:
description: Pretty-formatted list... | class ApiHeaderHandler(BaseMtlsHandler):
| async def get(self):
"""
Show request headers for API requests. No AuthZ required.
---
description: Shows all headers received by server
responses:
200:
description: Pretty-formatted list of headers.
"""
log_data... | .get("headers.sensitive_headers", [])):
continue
response_html.append(
f"<p><strong>{xhtml_escape(k)}</strong>: {xhtml_escape(v)}</p>"
)
self.write("{}".format("\n".join(response_html)))
class ApiHeaderHandler(BaseMtlsHandler):
| 63 | 64 | 175 | 9 | 54 | shyovn/consoleme | consoleme/handlers/v1/headers.py | Python | ApiHeaderHandler | ApiHeaderHandler | 46 | 70 | 46 | 46 | 83a414e6c375c145a793854fd24c7997fbebba43 | bigcode/the-stack | train |
c19aa66fb5ae7ba63a65fd9c | train | class | class HeaderHandler(BaseHandler):
async def get(self):
"""
Show request headers for API requests. AuthZ is required.
---
description: Shows all headers received by server
responses:
200:
description: Pretty-formatted list of hea... | class HeaderHandler(BaseHandler):
| async def get(self):
"""
Show request headers for API requests. AuthZ is required.
---
description: Shows all headers received by server
responses:
200:
description: Pretty-formatted list of headers.
"""
if not ... | .escape import xhtml_escape
from consoleme.config import config
from consoleme.handlers.base import BaseHandler, BaseMtlsHandler
from consoleme.lib.plugins import get_plugin_by_name
stats = get_plugin_by_name(config.get("plugins.metrics", "default_metrics"))()
log = config.get_logger()
class HeaderHandler(BaseHandler... | 67 | 67 | 224 | 6 | 61 | shyovn/consoleme | consoleme/handlers/v1/headers.py | Python | HeaderHandler | HeaderHandler | 11 | 43 | 11 | 11 | e451e97ee3608f951795ec772f3f61949f83b430 | bigcode/the-stack | train |
93a90cd12888365f3e449f22 | train | class | class Pipe(ABC):
"""
Pipeline Step, we refer as pipe, steps that recieve in input a data matrix and
return in output a transformed data matrix
See fit and transform methods for more details
"""
@abstractmethod
def fit(self, x, y):
"""
Generic fit method used to train the Pip... | class Pipe(ABC):
| """
Pipeline Step, we refer as pipe, steps that recieve in input a data matrix and
return in output a transformed data matrix
See fit and transform methods for more details
"""
@abstractmethod
def fit(self, x, y):
"""
Generic fit method used to train the Pipe
:param ... | : numpy 2D array, columns are the features and rows the data samples
"""
def fit_transform(self, x, y):
"""
To be implemented as a fit and transform on the same input data, see fit and transform for details
:param x:
:param y:
:return:
"""
class Pipe(ABC):
| 74 | 75 | 252 | 5 | 69 | paolotron/PatternLib | PatternLib/blueprint.py | Python | Pipe | Pipe | 46 | 77 | 46 | 46 | fb2b9cc11fdd7ba64cdc138ad91cda317a1ee1b1 | bigcode/the-stack | train |
c55968320be42f38e1a156cb | train | class | class Source(ABC):
"""
Source step, the initial step of the data pipeline, can take any object
in input and outputs a data matrix
"""
@abstractmethod
def fit(self, x, y):
"""
generic fit method for source step
:param x: Object
:param y: Object
:return: Non... | class Source(ABC):
| """
Source step, the initial step of the data pipeline, can take any object
in input and outputs a data matrix
"""
@abstractmethod
def fit(self, x, y):
"""
generic fit method for source step
:param x: Object
:param y: Object
:return: None
"""
... | data pipeline step should inherith a blueprint from this module,
the common pipeline steps should be:
Source -> Pipe -> ... -> Pipe -> Faucet
"""
class NoFitError(Exception):
def __init__(self, message="Data was not fitted"):
super().__init__(message)
class Source(ABC):
| 64 | 64 | 177 | 5 | 59 | paolotron/PatternLib | PatternLib/blueprint.py | Python | Source | Source | 16 | 43 | 16 | 16 | 70684c0159ebdf46f7e00d6fc1a2af08c89646f3 | bigcode/the-stack | train |
f5517dd818048987fad0d019 | train | class | class Faucet(ABC):
"""
General Data ML algorithms, classificators, regressors or clusterers
"""
@abstractmethod
def fit(self, x, y):
"""
Generic fit method used to train the Faucet
:param x: numpy 2D array, columns should be the features and rows the data samples
:pa... | class Faucet(ABC):
| """
General Data ML algorithms, classificators, regressors or clusterers
"""
@abstractmethod
def fit(self, x, y):
"""
Generic fit method used to train the Faucet
:param x: numpy 2D array, columns should be the features and rows the data samples
:param y: numpy 1D arr... | (self, x, y):
"""
To be implemented as a fit and transform on the same input data, see fit and transform for details
:param x: numpy 2D array
:param y: numpy 1D array
:return: numpy 2D array
"""
class Faucet(ABC):
| 69 | 70 | 236 | 5 | 64 | paolotron/PatternLib | PatternLib/blueprint.py | Python | Faucet | Faucet | 80 | 109 | 80 | 80 | ddb97fb102cd1f9a5bb3ca78426747d789539005 | bigcode/the-stack | train |
6a4bc2082557d7e0e0d75f25 | train | class | class NoFitError(Exception):
def __init__(self, message="Data was not fitted"):
super().__init__(message)
| class NoFitError(Exception):
| def __init__(self, message="Data was not fitted"):
super().__init__(message)
| , abstractmethod
"""
BluePrint module for defining common methods of the TibLib package classes,
every class that represents a data pipeline step should inherith a blueprint from this module,
the common pipeline steps should be:
Source -> Pipe -> ... -> Pipe -> Faucet
"""
class NoFitError(Exception):
| 64 | 64 | 27 | 6 | 58 | paolotron/PatternLib | PatternLib/blueprint.py | Python | NoFitError | NoFitError | 11 | 13 | 11 | 11 | a01f0a2450246b9a275d5d06557f03f4661451b1 | bigcode/the-stack | train |
a9aa6b65a615da307b6a189a | train | function | def replace_text_segment_param(lines, key, value, values, key_word="_framework_"):
new_lines = []
current_kernel = ""
for line in lines:
# replace amdhas_next_free_vgpr
if line.find(".amdhsa_kernel") != -1:
kernel_name = line.strip().split(" ")[-1]
current_kerne... | def replace_text_segment_param(lines, key, value, values, key_word="_framework_"):
| new_lines = []
current_kernel = ""
for line in lines:
# replace amdhas_next_free_vgpr
if line.find(".amdhsa_kernel") != -1:
kernel_name = line.strip().split(" ")[-1]
current_kernel = kernel_name
new_lines.append(line)
elif line.find(key) != -... | 80
]
vgprs_layers = [
0,
256,
128,
84,
64,
48,
40,
36,
32,
28,
28
]
def replace_text_segment_param(lines, key, value, values, key_word="_framework_"):
| 74 | 75 | 253 | 19 | 55 | SJTU-IPADS/reef-artifacts | script/replace_register_usage.py | Python | replace_text_segment_param | replace_text_segment_param | 63 | 89 | 63 | 63 | 52136285f17b4ec737ab26bafed7f0a24eb66009 | bigcode/the-stack | train |
fccfc9b265844430a2028b6d | train | function | def replace_symbol_segment_param(lines, key, value, values, key_word="_framework_"):
new_lines = []
current_kernel = ""
for line in lines:
# replace amdhas_next_free_vgpr
if line.find(".name:") != -1:
kernel_name = line.strip().split(" ")[-1]
current_kernel = ke... | def replace_symbol_segment_param(lines, key, value, values, key_word="_framework_"):
| new_lines = []
current_kernel = ""
for line in lines:
# replace amdhas_next_free_vgpr
if line.find(".name:") != -1:
kernel_name = line.strip().split(" ")[-1]
current_kernel = kernel_name
new_lines.append(line)
elif line.find(key) != -1 and cu... | new_value)
# print("replace %s %s to %d" % (current_kernel, key, new_value))
new_lines.append(new_line)
else:
new_lines.append(line)
return new_lines
def replace_symbol_segment_param(lines, key, value, values, key_word="_framework_"):
| 66 | 66 | 222 | 19 | 46 | SJTU-IPADS/reef-artifacts | script/replace_register_usage.py | Python | replace_symbol_segment_param | replace_symbol_segment_param | 91 | 114 | 91 | 91 | 79253ca591e8ea86f21ea71861490b260b53953a | bigcode/the-stack | train |
91b768fe50541d2d5f35668f | train | function | def batch_replace(lines, key_word, private_segment):
lines = replace_text_segment_param(lines, ".amdhsa_next_free_vgpr", None, vgprs_layers, key_word)
lines = replace_text_segment_param(lines, ".amdhsa_next_free_sgpr", None, sgprs_layers, key_word)
if private_segment:
lines = replace_text_segment_pa... | def batch_replace(lines, key_word, private_segment):
| lines = replace_text_segment_param(lines, ".amdhsa_next_free_vgpr", None, vgprs_layers, key_word)
lines = replace_text_segment_param(lines, ".amdhsa_next_free_sgpr", None, sgprs_layers, key_word)
if private_segment:
lines = replace_text_segment_param(lines, ".amdhsa_private_segment_fixed_size", max_... | new_value= ""
if value != None:
new_value = value
else:
new_value = values[num_layers]
new_line = " %s %d\n" % (key, new_value)
# print("replace %s %s to %d" % (current_kernel, key, new_value))
new_lines.appen... | 103 | 103 | 346 | 11 | 91 | SJTU-IPADS/reef-artifacts | script/replace_register_usage.py | Python | batch_replace | batch_replace | 116 | 133 | 116 | 116 | 58d3daf24e204a4155ae7f3c09fe8cca41c782ab | bigcode/the-stack | train |
28a9a944691540bc4b1d1404 | train | function | def checkio(data):
l = list(data)
my_dict = {i: l.count(i) for i in l}
res=list()
for item in l:
if my_dict[item]>1:
res.append(item)
return res
| def checkio(data):
| l = list(data)
my_dict = {i: l.count(i) for i in l}
res=list()
for item in l:
if my_dict[item]>1:
res.append(item)
return res
| def checkio(data):
| 5 | 64 | 54 | 5 | 0 | formeo/checkio_tasks | Non-uniqueElements.py | Python | checkio | checkio | 1 | 8 | 1 | 1 | a3fc53aa037c59d07f903c6dfcf030070d9f1851 | bigcode/the-stack | train |
921ab3f1eb5cd6d67b4a6908 | train | class | class RouteTablesOperations(object):
"""RouteTablesOperations 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.
:t... | class RouteTablesOperations(object):
| """RouteTablesOperations 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.v2017... | 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 cause incorrect behavior and will be lost if the code is regenerated.
# ---------------------... | 256 | 256 | 5,798 | 6 | 250 | vbarbaresi/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_11_01/operations/_route_tables_operations.py | Python | RouteTablesOperations | RouteTablesOperations | 28 | 596 | 28 | 28 | 7f7f0699bfb9636aa56fcf9a8529ffe5f0bf8556 | bigcode/the-stack | train |
c38efb798e89ce5bc0cc5f29 | train | class | class NetworkDrawer(object):
"""
This class provides functionality for drawing the potential energy surface
for a pressure-dependent reaction network using the Cairo 2D graphics
engine. The most common use case is simply::
NetworkDrawer().draw(network, file_format='png', path='network.png')... | class NetworkDrawer(object):
| """
This class provides functionality for drawing the potential energy surface
for a pressure-dependent reaction network using the Cairo 2D graphics
engine. The most common use case is simply::
NetworkDrawer().draw(network, file_format='png', path='network.png')
where ``network`` i... | to use, copy, modify, merge, publish, distribute, sublicense, #
# and/or sell copies of the Software, and to permit persons to whom the #
# Software is furnished to do so, subject to the following conditions: #
# #
# The above ... | 256 | 256 | 4,751 | 5 | 250 | mbprend/RMG-Py | rmgpy/pdep/draw.py | Python | NetworkDrawer | NetworkDrawer | 45 | 520 | 45 | 45 | 70cde1f18a9aca49d5fd8ae4c11ae1855765fb28 | bigcode/the-stack | train |
6fae0ef3ad4b93796196482f | train | class | class Migration(migrations.Migration):
dependencies = [
('ricerca_app', '0029_spinoffareainnovaziones3calabria_spinoffdatibase'),
]
operations = [
migrations.RenameModel(
old_name='SpinoffAreaInnovazioneS3Calabria',
new_name='SpinoffStartupAreaInnovazioneS3Calabria'... | class Migration(migrations.Migration):
| dependencies = [
('ricerca_app', '0029_spinoffareainnovaziones3calabria_spinoffdatibase'),
]
operations = [
migrations.RenameModel(
old_name='SpinoffAreaInnovazioneS3Calabria',
new_name='SpinoffStartupAreaInnovazioneS3Calabria',
),
migrations.RenameMo... | # Generated by Django 3.2.7 on 2021-11-25 04:04
from django.db import migrations
class Migration(migrations.Migration):
| 36 | 64 | 188 | 7 | 28 | UniversitaDellaCalabria/Ricerca | ricerca_app/migrations/0030_auto_20211125_0404.py | Python | Migration | Migration | 6 | 29 | 6 | 7 | 5911df18d184142b0a72ea1b9632f0bf5256813c | bigcode/the-stack | train |
7d40e2859d0d253c7ec197bd | train | function | def is_active_staff_or_superuser(user):
"""
Checks if user is active staff or superuser.
"""
return user and user.is_active and (user.is_staff or user.is_superuser)
| def is_active_staff_or_superuser(user):
| """
Checks if user is active staff or superuser.
"""
return user and user.is_active and (user.is_staff or user.is_superuser)
| a common authorization base for the Course Access Groups API views.
"""
authentication_classes = (
BasicAuthentication,
SessionAuthentication,
TokenAuthentication,
OAuth2Authentication,
)
permission_classes = (
IsAuthenticated,
IsSiteAdminUser,
)
def... | 64 | 64 | 42 | 9 | 55 | appsembler/course-access-groups | course_access_groups/permissions.py | Python | is_active_staff_or_superuser | is_active_staff_or_superuser | 141 | 145 | 141 | 141 | 4d33ed649c2e08010fd9a606d5e473ac0fc72e82 | bigcode/the-stack | train |
ad5159ac4d5f56a0687134bc | train | function | def is_organization_staff(user, course):
"""
Helper to check if the user is organization staff.
:param user: User to check access against.
:param course: The Course or CourseOverview object to check access for.
:return: bool
TODO: Handle single-site setups in which organization is not importa... | def is_organization_staff(user, course):
| """
Helper to check if the user is organization staff.
:param user: User to check access against.
:param course: The Course or CourseOverview object to check access for.
:return: bool
TODO: Handle single-site setups in which organization is not important
TODO: What if a course has two org... | import BasicAuthentication, SessionAuthentication, TokenAuthentication
from rest_framework.permissions import BasePermission, IsAuthenticated
from .models import CourseAccessGroup, GroupCourse, Membership, PublicCourse
from .openedx_modules import OAuth2Authentication
log = logging.getLogger(__name__)
def is_organiz... | 64 | 64 | 194 | 9 | 55 | appsembler/course-access-groups | course_access_groups/permissions.py | Python | is_organization_staff | is_organization_staff | 21 | 49 | 21 | 21 | 3401568ac6d61568039d9b403e604f9bea7bf807 | bigcode/the-stack | train |
5f742c12467af4593b0edf6d | train | class | class CommonAuthMixin:
"""
Provides a common authorization base for the Course Access Groups API views.
"""
authentication_classes = (
BasicAuthentication,
SessionAuthentication,
TokenAuthentication,
OAuth2Authentication,
)
permission_classes = (
IsAuthen... | class CommonAuthMixin:
| """
Provides a common authorization base for the Course Access Groups API views.
"""
authentication_classes = (
BasicAuthentication,
SessionAuthentication,
TokenAuthentication,
OAuth2Authentication,
)
permission_classes = (
IsAuthenticated,
IsSite... | course.id).exists()
class IsSiteAdminUser(BasePermission):
"""
Allow access to only site admins if in multisite mode or staff or superuser
if in standalone mode
"""
def has_permission(self, request, view):
return is_site_admin_user(request)
class CommonAuthMixin:
| 64 | 64 | 64 | 5 | 59 | appsembler/course-access-groups | course_access_groups/permissions.py | Python | CommonAuthMixin | CommonAuthMixin | 124 | 138 | 124 | 124 | 557ff3784f7febf85c138804ce151931770d0e20 | bigcode/the-stack | train |
bd2842f8b4757cf5241f9ae3 | train | function | def get_current_organization(request):
"""
Return a single organization for the current site.
:param request:
:raise Site.DoesNotExist when the site isn't found.
:raise Organization.DoesNotExist when the organization isn't found.
:raise Organization.MultipleObjectsReturned when more than one or... | def get_current_organization(request):
| """
Return a single organization for the current site.
:param request:
:raise Site.DoesNotExist when the site isn't found.
:raise Organization.DoesNotExist when the organization isn't found.
:raise Organization.MultipleObjectsReturned when more than one organization is returned.
:return Org... | (
course_id=str(course.id),
active=True,
).values('organization_id')
return UserOrganizationMapping.objects.filter(
user=user,
organization_id__in=course_org_ids,
is_active=True,
is_amc_admin=True,
).exists()
def get_current_organization(request):
| 64 | 64 | 98 | 7 | 57 | appsembler/course-access-groups | course_access_groups/permissions.py | Python | get_current_organization | get_current_organization | 52 | 63 | 52 | 52 | a8dc94f42bea6e2efcf51a7b66f0bfbfbd1dfd0a | bigcode/the-stack | train |
435ed4798e7469ed63265e43 | train | class | class IsSiteAdminUser(BasePermission):
"""
Allow access to only site admins if in multisite mode or staff or superuser
if in standalone mode
"""
def has_permission(self, request, view):
return is_site_admin_user(request)
| class IsSiteAdminUser(BasePermission):
| """
Allow access to only site admins if in multisite mode or staff or superuser
if in standalone mode
"""
def has_permission(self, request, view):
return is_site_admin_user(request)
| (course):
"""
Check PublicCourse access within the user's organization(s).
:param user: User model object.
:param course: CourseOverview model object.
:return: bool.
"""
return PublicCourse.objects.filter(course_id=course.id).exists()
class IsSiteAdminUser(BasePermission):
| 64 | 64 | 54 | 8 | 56 | appsembler/course-access-groups | course_access_groups/permissions.py | Python | IsSiteAdminUser | IsSiteAdminUser | 114 | 121 | 114 | 114 | 76ba32cdfd9c9cb74ceda0472ddf76a717aa07e3 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.