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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
87f011477d3db7168c6b66bd | train | class | class Solution:
def deleteNode(self, node: ListNode):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val, node.next = node.next.val, node.next.next
| class Solution:
| def deleteNode(self, node: ListNode):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val, node.next = node.next.val, node.next.next
| INKING = """
删除该节点之后,该节点的值为下一节点的值,该节点的下一节点为下下个节点
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
| 64 | 64 | 57 | 3 | 60 | reedwave/leetcode-cn | DeleteNodeInALinkedList.py | Python | Solution | Solution | 43 | 49 | 43 | 43 | 29f158ffa75aca6bc8d94e7abca5909cf51ab73e | bigcode/the-stack | train |
07622ee7069ab59dac175975 | train | class | class NewsclassifierConfig(AppConfig):
name = 'newsclassifier'
| class NewsclassifierConfig(AppConfig):
| name = 'newsclassifier'
| from django.apps import AppConfig
class NewsclassifierConfig(AppConfig):
| 14 | 64 | 14 | 7 | 6 | Jellytrial/news_classification_webapp | app/newsclassifier/apps.py | Python | NewsclassifierConfig | NewsclassifierConfig | 4 | 5 | 4 | 4 | f1a4029c8c91e5d482f8d46042ef05268682d2e8 | bigcode/the-stack | train |
6b0e3a0728be58e22eeded0d | train | function | def _dump_request(response):
_print_request(response)
data = dump.dump_all(response)
try:
logger.trace(data.decode())
except Exception:
data = str(data).replace('\\r\\n', '\r\n')
logger.trace(data)
| def _dump_request(response):
| _print_request(response)
data = dump.dump_all(response)
try:
logger.trace(data.decode())
except Exception:
data = str(data).replace('\\r\\n', '\r\n')
logger.trace(data)
| str(h) + ' ' + h.url)
logger.debug(h.request.method + ': ' + str(h) + ' ' + h.url)
def _print_request(response):
logger.debug(' {} {} [{}]'.format(response.request.method, response.request.url, response.status_code))
def _dump_request(response):
| 64 | 64 | 54 | 6 | 58 | wp99cp/postcard_creator_wrapper | postcard_creator/token.py | Python | _dump_request | _dump_request | 43 | 50 | 43 | 43 | 3827f367a401fe3272041a690aeb1d1149bd3765 | bigcode/the-stack | train |
f5bfffb744b5fad0871cace5 | train | function | def base64_decode(string):
padding = 4 - (len(string) % 4)
string = string + ("=" * padding)
return base64.urlsafe_b64decode(string)
| def base64_decode(string):
| padding = 4 - (len(string) % 4)
string = string + ("=" * padding)
return base64.urlsafe_b64decode(string)
| GING_TRACE_LVL, 'TRACE')
setattr(logger, 'trace', lambda *args: logger.log(LOGGING_TRACE_LVL, *args))
def base64_encode(string):
encoded = base64.urlsafe_b64encode(string).decode('ascii')
return encoded.rstrip("=")
def base64_decode(string):
| 64 | 64 | 41 | 6 | 58 | wp99cp/postcard_creator_wrapper | postcard_creator/token.py | Python | base64_decode | base64_decode | 27 | 30 | 27 | 27 | 1841025e234339bea549e06f2fe742573ba9a624 | bigcode/the-stack | train |
1b69d0e610251fa60c401105 | train | function | def _log_and_dump(r):
_log_response(r)
_dump_request(r)
| def _log_and_dump(r):
| _log_response(r)
_dump_request(r)
| .status_code))
def _dump_request(response):
_print_request(response)
data = dump.dump_all(response)
try:
logger.trace(data.decode())
except Exception:
data = str(data).replace('\\r\\n', '\r\n')
logger.trace(data)
def _log_and_dump(r):
| 64 | 64 | 19 | 7 | 57 | wp99cp/postcard_creator_wrapper | postcard_creator/token.py | Python | _log_and_dump | _log_and_dump | 53 | 55 | 53 | 53 | a352e4d523c7b351bc69a8a856224db077049936 | bigcode/the-stack | train |
a4e62dde473ba95afacbcf20 | train | class | class Token(object):
def __init__(self, _protocol='https://'):
self.protocol = _protocol
self.base = '{}account.post.ch'.format(self.protocol)
self.swissid = '{}login.swissid.ch'.format(self.protocol)
self.token_url = '{}postcardcreator.post.ch/saml/SSO/alias/defaultAlias'.format(sel... | class Token(object):
| def __init__(self, _protocol='https://'):
self.protocol = _protocol
self.base = '{}account.post.ch'.format(self.protocol)
self.swissid = '{}login.swissid.ch'.format(self.protocol)
self.token_url = '{}postcardcreator.post.ch/saml/SSO/alias/defaultAlias'.format(self.protocol)
s... | _TRACE_LVL, 'TRACE')
setattr(logger, 'trace', lambda *args: logger.log(LOGGING_TRACE_LVL, *args))
def base64_encode(string):
encoded = base64.urlsafe_b64encode(string).decode('ascii')
return encoded.rstrip("=")
def base64_decode(string):
padding = 4 - (len(string) % 4)
string = string + ("=" * paddi... | 256 | 256 | 2,784 | 4 | 252 | wp99cp/postcard_creator_wrapper | postcard_creator/token.py | Python | Token | Token | 58 | 345 | 58 | 58 | cdea32b6b407247fd851be1153bde4a8ae84e3e0 | bigcode/the-stack | train |
38902d8370e4dc0ece05df53 | train | function | def _log_response(h):
for h in h.history:
logger.debug(h.request.method + ': ' + str(h) + ' ' + h.url)
logger.debug(h.request.method + ': ' + str(h) + ' ' + h.url)
| def _log_response(h):
| for h in h.history:
logger.debug(h.request.method + ': ' + str(h) + ' ' + h.url)
logger.debug(h.request.method + ': ' + str(h) + ' ' + h.url)
| .urlsafe_b64encode(string).decode('ascii')
return encoded.rstrip("=")
def base64_decode(string):
padding = 4 - (len(string) % 4)
string = string + ("=" * padding)
return base64.urlsafe_b64decode(string)
def _log_response(h):
| 64 | 64 | 53 | 6 | 58 | wp99cp/postcard_creator_wrapper | postcard_creator/token.py | Python | _log_response | _log_response | 33 | 36 | 33 | 33 | bbb26e540f91c5b10096a62a65deee8423e22b48 | bigcode/the-stack | train |
ac51312c3f5c9aa07787a784 | train | function | def base64_encode(string):
encoded = base64.urlsafe_b64encode(string).decode('ascii')
return encoded.rstrip("=")
| def base64_encode(string):
| encoded = base64.urlsafe_b64encode(string).decode('ascii')
return encoded.rstrip("=")
| cardCreatorException
LOGGING_TRACE_LVL = 5
logger = logging.getLogger('postcard_creator')
logging.addLevelName(LOGGING_TRACE_LVL, 'TRACE')
setattr(logger, 'trace', lambda *args: logger.log(LOGGING_TRACE_LVL, *args))
def base64_encode(string):
| 64 | 64 | 28 | 6 | 58 | wp99cp/postcard_creator_wrapper | postcard_creator/token.py | Python | base64_encode | base64_encode | 22 | 24 | 22 | 22 | 767ca3248a48dff809f4221361ec454903188852 | bigcode/the-stack | train |
ec9c11d04172733719016ca8 | train | function | def _print_request(response):
logger.debug(' {} {} [{}]'.format(response.request.method, response.request.url, response.status_code))
| def _print_request(response):
| logger.debug(' {} {} [{}]'.format(response.request.method, response.request.url, response.status_code))
| _b64decode(string)
def _log_response(h):
for h in h.history:
logger.debug(h.request.method + ': ' + str(h) + ' ' + h.url)
logger.debug(h.request.method + ': ' + str(h) + ' ' + h.url)
def _print_request(response):
| 64 | 64 | 28 | 6 | 58 | wp99cp/postcard_creator_wrapper | postcard_creator/token.py | Python | _print_request | _print_request | 39 | 40 | 39 | 39 | f3aba19d4de31797aae05f9653e346bb30d7ff37 | bigcode/the-stack | train |
29d06b015d411d5e84e53290 | train | class | class TestAppIconCommands:
def setup_method(self):
"""Method to instantiate to created_bp_list and created_app_list"""
self.created_bp_list = []
self.created_marketplace_bp_list = []
def teardown_method(self):
"""Method to delete creates bps and apps during tests"""
fo... | class TestAppIconCommands:
| def setup_method(self):
"""Method to instantiate to created_bp_list and created_app_list"""
self.created_bp_list = []
self.created_marketplace_bp_list = []
def teardown_method(self):
"""Method to delete creates bps and apps during tests"""
for bp_name in self.created_b... | import pytest
import uuid
import sys
from click.testing import CliRunner
from calm.dsl.log import get_logging_handle
from calm.dsl.cli import main as cli
from calm.dsl.api import get_api_client
DSL_BP_FILEPATH = "tests/existing_vm_example/test_existing_vm_bp.py"
APP_ICON_IMAGE_PATH = "tests/cli/images/test_app_icon.j... | 89 | 256 | 1,228 | 6 | 83 | tuxtof/calm-dsl | tests/cli/test_app_icon_commands.py | Python | TestAppIconCommands | TestAppIconCommands | 15 | 191 | 15 | 15 | d2e7d2a56ae022d540db72b48951197f5db3eee6 | bigcode/the-stack | train |
cfbd134904df64ae42750dfb | train | class | class ResBlock(nn.Module):
def __init__(self, inplanes, planes):
super(ResBlock, self).__init__()
self.inplanes = inplanes
self.conv1 = nn.Conv3d(inplanes, planes, 3, bias=False)
self.bn1 = nn.BatchNorm3d(planes)
self.conv2 = nn.Conv3d(planes, planes, 3, bias=False)
s... | class ResBlock(nn.Module):
| def __init__(self, inplanes, planes):
super(ResBlock, self).__init__()
self.inplanes = inplanes
self.conv1 = nn.Conv3d(inplanes, planes, 3, bias=False)
self.bn1 = nn.BatchNorm3d(planes)
self.conv2 = nn.Conv3d(planes, planes, 3, bias=False)
self.bn2 = nn.BatchNorm3d(pl... | import torch.nn as nn
import torch.nn.functional as F
import math
import torch
import pdb
# adapt from https://github.com/Kamnitsask/deepmedic
class ResBlock(nn.Module):
| 44 | 64 | 186 | 6 | 37 | fishfishson/MeshCNN | models/deepmedic.py | Python | ResBlock | ResBlock | 10 | 26 | 10 | 10 | 6a305f3a5b17a15971826f248570de5ce5ecf6bd | bigcode/the-stack | train |
92d7b9aa01017c060bb41be6 | train | function | def repeat(x, n=3):
# nc333
b, c, h, w, t = x.shape
x = x.unsqueeze(5).unsqueeze(4).unsqueeze(3)
x = x.repeat(1, 1, 1, n, 1, n, 1, n)
return x.view(b, c, n * h, n * w, n * t)
| def repeat(x, n=3):
# nc333
| b, c, h, w, t = x.shape
x = x.unsqueeze(5).unsqueeze(4).unsqueeze(3)
x = x.repeat(1, 1, 1, n, 1, n, 1, n)
return x.view(b, c, n * h, n * w, n * t)
| conv3x3(inplanes, planes, ksize=3):
return nn.Sequential(
nn.Conv3d(inplanes, planes, ksize, bias=False),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True))
def repeat(x, n=3):
# nc333
| 64 | 64 | 91 | 13 | 51 | fishfishson/MeshCNN | models/deepmedic.py | Python | repeat | repeat | 36 | 41 | 36 | 37 | fbe9e7e49f1a8241fdfb82deca7a67208091ac4f | bigcode/the-stack | train |
97f845a7d06377b8005a7b8c | train | class | class DeepMedicNR(nn.Module):
def __init__(self, c=4, n1=30, n2=40, n3=50, m=150, up=True):
super(DeepMedicNR, self).__init__()
# n1, n2, n3 = 30, 40, 50
n = 2 * n3
self.branch1 = nn.Sequential(
conv3x3(c, n1),
conv3x3(n1, n1),
conv3x3(n1, n2),
... | class DeepMedicNR(nn.Module):
| def __init__(self, c=4, n1=30, n2=40, n3=50, m=150, up=True):
super(DeepMedicNR, self).__init__()
# n1, n2, n3 = 30, 40, 50
n = 2 * n3
self.branch1 = nn.Sequential(
conv3x3(c, n1),
conv3x3(n1, n1),
conv3x3(n1, n2),
conv3x3(n2, n2),
... | (m, nn.Conv3d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm3d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, inputs):
x1, x2 = inputs
x1 = self.bra... | 146 | 146 | 489 | 7 | 138 | fishfishson/MeshCNN | models/deepmedic.py | Python | DeepMedicNR | DeepMedicNR | 143 | 191 | 143 | 143 | 47c99490f4d8df3abe3d4a4dadab3fac07f01035 | bigcode/the-stack | train |
8e45126b654fc971898ccf0f | train | function | def conv3x3(inplanes, planes, ksize=3):
return nn.Sequential(
nn.Conv3d(inplanes, planes, ksize, bias=False),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True))
| def conv3x3(inplanes, planes, ksize=3):
| return nn.Sequential(
nn.Conv3d(inplanes, planes, ksize, bias=False),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True))
| 2(self.conv2(y))
x = x[:, :, 2:-2, 2:-2, 2:-2]
y[:, :self.inplanes] += x
y = self.relu(y)
return y
def conv3x3(inplanes, planes, ksize=3):
| 64 | 64 | 52 | 15 | 48 | fishfishson/MeshCNN | models/deepmedic.py | Python | conv3x3 | conv3x3 | 29 | 33 | 29 | 29 | 008ac4c96f4eb7bbccf5c6466b5582f06ee11f30 | bigcode/the-stack | train |
c6db8358df1fd619cd73f874 | train | class | class VDeepMedic(nn.Module):
def __init__(self, c=4, n1=30, n2=40, n3=50, m=150, up=True):
super(VDeepMedic, self).__init__()
# n1, n2, n3 = 30, 40, 50
# need 29 inputs
n = 2 * n3
self.branch1 = nn.Sequential(
conv3x3(c, n1),
conv3x3(n1, n1),
... | class VDeepMedic(nn.Module):
| def __init__(self, c=4, n1=30, n2=40, n3=50, m=150, up=True):
super(VDeepMedic, self).__init__()
# n1, n2, n3 = 30, 40, 50
# need 29 inputs
n = 2 * n3
self.branch1 = nn.Sequential(
conv3x3(c, n1),
conv3x3(n1, n1),
ResBlock(n1, n2),
... | isinstance(m, nn.Conv3d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm3d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, inputs):
x1, x2 = inputs
x1... | 142 | 142 | 474 | 7 | 134 | fishfishson/MeshCNN | models/deepmedic.py | Python | VDeepMedic | VDeepMedic | 91 | 139 | 91 | 91 | 16ba0cb28f1fe53853a10223c5480b44b016542a | bigcode/the-stack | train |
a31e22f08ec81ce515098643 | train | class | class DeepMedic(nn.Module):
def __init__(self, c=1, n1=30, n2=40, n3=50, m=150, up=True):
super(DeepMedic, self).__init__()
# n1, n2, n3 = 30, 40, 50
n = 2 * n3
self.branch1 = nn.Sequential(
conv3x3(1, n1),
conv3x3(n1, n1),
ResBlock(n1, n2),
... | class DeepMedic(nn.Module):
| def __init__(self, c=1, n1=30, n2=40, n3=50, m=150, up=True):
super(DeepMedic, self).__init__()
# n1, n2, n3 = 30, 40, 50
n = 2 * n3
self.branch1 = nn.Sequential(
conv3x3(1, n1),
conv3x3(n1, n1),
ResBlock(n1, n2),
ResBlock(n2, n2),
... | return nn.Sequential(
nn.Conv3d(inplanes, planes, ksize, bias=False),
nn.BatchNorm3d(planes),
nn.ReLU(inplace=True))
def repeat(x, n=3):
# nc333
b, c, h, w, t = x.shape
x = x.unsqueeze(5).unsqueeze(4).unsqueeze(3)
x = x.repeat(1, 1, 1, n, 1, n, 1, n)
return x.view(b, c,... | 134 | 134 | 449 | 6 | 128 | fishfishson/MeshCNN | models/deepmedic.py | Python | DeepMedic | DeepMedic | 44 | 88 | 44 | 44 | 6021b8c2346c71bc7fc33a210bb8d95fc165111c | bigcode/the-stack | train |
86c54d009bd5b93a002eaf7a | train | class | class LCDUtils(AsyncLCDUtils):
@sync_bind(AsyncLCDUtils.calculate_tax)
def calculate_tax(self, coin: Union[Coin, str, dict]) -> Coin:
pass
calculate_tax.__doc__ = AsyncLCDUtils.calculate_tax.__doc__
@sync_bind(AsyncLCDUtils.validators_with_voting_power)
async def validators_with_voting_pow... | class LCDUtils(AsyncLCDUtils):
@sync_bind(AsyncLCDUtils.calculate_tax)
| def calculate_tax(self, coin: Union[Coin, str, dict]) -> Coin:
pass
calculate_tax.__doc__ = AsyncLCDUtils.calculate_tax.__doc__
@sync_bind(AsyncLCDUtils.validators_with_voting_power)
async def validators_with_voting_power(self) -> Dict[str, dict]:
pass
validators_with_voting_power... | _address] = {
"validator_info": v,
"voting_power": int(delegate_info["voting_power"]),
"proposer_priority": int(delegate_info["proposer_priority"]),
}
return res
class LCDUtils(AsyncLCDUtils):
@sync_bind(AsyncLCDUtils.calculate_tax)
| 64 | 64 | 107 | 19 | 44 | yeeyangtee/terra-sdk-python | terra_sdk/client/lcd/lcdutils.py | Python | LCDUtils | LCDUtils | 56 | 67 | 56 | 57 | 81fc24d7fed88cabc5a2e770124066af5cda4091 | bigcode/the-stack | train |
2d32d05cad69ec27af2c1581 | train | function | def index_by_pub_key(m: Dict[str, Any], o: Any):
m[o["pub_key"]] = o
return m
| def index_by_pub_key(m: Dict[str, Any], o: Any):
| m[o["pub_key"]] = o
return m
| from functools import reduce
from math import ceil
from typing import Any, Dict, Union
from terra_sdk.core import Coin
from .api._base import BaseAsyncAPI, sync_bind
def index_by_pub_key(m: Dict[str, Any], o: Any):
| 55 | 64 | 30 | 16 | 38 | yeeyangtee/terra-sdk-python | terra_sdk/client/lcd/lcdutils.py | Python | index_by_pub_key | index_by_pub_key | 10 | 12 | 10 | 10 | cd4af192dfa24de1992f35506efa2aa96bd94f06 | bigcode/the-stack | train |
014a45ed9e4041cd4dfeac14 | train | class | class AsyncLCDUtils(BaseAsyncAPI):
async def calculate_tax(self, coin: Union[Coin, str, dict]) -> Coin:
"""Calculates the tax that would be applied for the Coin if sent.
Args:
coin (Union[Coin, str, dict]): coin to be sent
Returns:
Coin: tax to be paid
"""
... | class AsyncLCDUtils(BaseAsyncAPI):
| async def calculate_tax(self, coin: Union[Coin, str, dict]) -> Coin:
"""Calculates the tax that would be applied for the Coin if sent.
Args:
coin (Union[Coin, str, dict]): coin to be sent
Returns:
Coin: tax to be paid
"""
coin = Coin.parse(coin)
... | from functools import reduce
from math import ceil
from typing import Any, Dict, Union
from terra_sdk.core import Coin
from .api._base import BaseAsyncAPI, sync_bind
def index_by_pub_key(m: Dict[str, Any], o: Any):
m[o["pub_key"]] = o
return m
class AsyncLCDUtils(BaseAsyncAPI):
| 77 | 104 | 349 | 8 | 68 | yeeyangtee/terra-sdk-python | terra_sdk/client/lcd/lcdutils.py | Python | AsyncLCDUtils | AsyncLCDUtils | 15 | 53 | 15 | 15 | 59ec74056ee70b6b5f525ad1bce55d4aa3c1eefd | bigcode/the-stack | train |
ec47d70dff8373db1b4e09eb | train | function | def db_commit_decorator(func):
@wraps(func)
def session_commit(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
storage.error('DB operation error,here are details:{}'.format(e))
db_session.rollback()
return session_commit
| def db_commit_decorator(func):
@wraps(func)
| def session_commit(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
storage.error('DB operation error,here are details:{}'.format(e))
db_session.rollback()
return session_commit
| ('failed to crawl {url},here are details:{e}, stack is {stack}'.format(url=args[0], e=e,
stack=format_tb
(e.__traceback__)[0]))
... | 64 | 64 | 67 | 13 | 50 | dachenlian/weibospider | decorators/decorators.py | Python | db_commit_decorator | db_commit_decorator | 27 | 35 | 27 | 28 | cf06b599453106ef3f871180c768efbc77151613 | bigcode/the-stack | train |
15d3416ef776069a5860fb4a | train | function | def retry(times=-1, delay=0, exceptions=Exception, logger=other):
"""
inspired by https://github.com/invl/retry
:param times: retry times
:param delay: internals between each retry
:param exceptions: exceptions may raise in retry
:param logger: log for retry
:return: func result or None
... | def retry(times=-1, delay=0, exceptions=Exception, logger=other):
| """
inspired by https://github.com/invl/retry
:param times: retry times
:param delay: internals between each retry
:param exceptions: exceptions may raise in retry
:param logger: log for retry
:return: func result or None
"""
def _inter_retry(caller, retry_time, retry_delay, es):
... | child thread
if alive:
try:
raise Timeout('request timeout')
finally:
return ''
else:
if result:
return result[0]
else:
return ''
return wrapp... | 71 | 71 | 238 | 18 | 52 | dachenlian/weibospider | decorators/decorators.py | Python | retry | retry | 97 | 123 | 97 | 97 | 14df4312cbcf82ee09207d2b42b7eb079ca40f39 | bigcode/the-stack | train |
a836c69551fb008035edb1bc | train | function | def timeout(seconds):
def crwal_decorator(func):
def _new_func(oldfunc, result, oldfunc_args, oldfunc_kwargs):
result.append(oldfunc(*oldfunc_args, **oldfunc_kwargs))
@wraps(func)
def wrapper(*args, **kwargs):
result = []
# create new args for _new_func, ... | def timeout(seconds):
| def crwal_decorator(func):
def _new_func(oldfunc, result, oldfunc_args, oldfunc_kwargs):
result.append(oldfunc(*oldfunc_args, **oldfunc_kwargs))
@wraps(func)
def wrapper(*args, **kwargs):
result = []
# create new args for _new_func, because we want to get... | , {} is raised, here are details:{}'.format(
e, format_tb(e.__traceback__)[0]
))
return return_value
return handle_error
return page_parse
# it can be blocked when crawling pages even if we set timeout=out_time in requests.get()
def timeout(seconds):
| 66 | 66 | 222 | 4 | 62 | dachenlian/weibospider | decorators/decorators.py | Python | timeout | timeout | 60 | 94 | 60 | 60 | 63aec971bf887badbf243bd9585cc685463d225b | bigcode/the-stack | train |
163aac375b74fc3d116a5d34 | train | function | def timeout_decorator(func):
@wraps(func)
def time_limit(*args, **kargs):
try:
return func(*args, **kargs)
except Exception as e:
crawler.error('failed to crawl {url},here are details:{e}, stack is {stack}'.format(url=args[0], e=e,
... | def timeout_decorator(func):
@wraps(func)
| def time_limit(*args, **kargs):
try:
return func(*args, **kargs)
except Exception as e:
crawler.error('failed to crawl {url},here are details:{e}, stack is {stack}'.format(url=args[0], e=e,
... | import time
import collections
from functools import wraps, partial
from traceback import format_tb
from db.basic import db_session
from logger import (
parser, crawler, storage, other)
from utils import KThread
from exceptions import Timeout
def timeout_decorator(func):
@wraps(func)
| 62 | 64 | 96 | 12 | 49 | dachenlian/weibospider | decorators/decorators.py | Python | timeout_decorator | timeout_decorator | 13 | 24 | 13 | 14 | f65396f126f1c18456eaf6c636499854f6e937c1 | bigcode/the-stack | train |
a05ecb25ef976fc9462b9a34 | train | function | def parse_decorator(return_value):
"""
:param return_value: catch exceptions when parsing pages, return the default value
:return: the default value is whatever you want, usually it's 0,'',[],False,{} or None
"""
def page_parse(func):
@wraps(func)
def handle_error(*keys):
... | def parse_decorator(return_value):
| """
:param return_value: catch exceptions when parsing pages, return the default value
:return: the default value is whatever you want, usually it's 0,'',[],False,{} or None
"""
def page_parse(func):
@wraps(func)
def handle_error(*keys):
try:
return func(*... | s(func)
def session_commit(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
storage.error('DB operation error,here are details:{}'.format(e))
db_session.rollback()
return session_commit
def parse_decorator(return_value):
| 64 | 64 | 138 | 7 | 56 | dachenlian/weibospider | decorators/decorators.py | Python | parse_decorator | parse_decorator | 38 | 56 | 38 | 38 | 964dc328a20a9325eaa06ad9283ed3161443efd9 | bigcode/the-stack | train |
ae0ac7196ccd85424474da13 | train | function | def merge_subreturn(original_return, sub_return, subkey=None):
"""
Update an existing state return (`original_return`) in place
with another state return (`sub_return`), i.e. for a subresource.
Returns:
dict: The updated state return.
The existing state return does not need to have all the... | def merge_subreturn(original_return, sub_return, subkey=None):
| """
Update an existing state return (`original_return`) in place
with another state return (`sub_return`), i.e. for a subresource.
Returns:
dict: The updated state return.
The existing state return does not need to have all the required fields,
as this is meant to be called from the in... | empty and isinstance(state_result, dict) and ret:
ret = check_result(state_result, recurse=True, highstate=highstate)
# if we detect a fail, check for onfail requisites
if not ret:
# ret can be None in case of no onfail reqs, recast it to bool
ret = bool(
... | 130 | 130 | 435 | 14 | 115 | babs/salt | salt/utils/state.py | Python | merge_subreturn | merge_subreturn | 153 | 205 | 153 | 153 | 177caa46cf208203c9fcf35f2ca190559a3138f1 | bigcode/the-stack | train |
0547e4bd826a377632a1d8f4 | train | function | def check_onfail_requisites(state_id, state_result, running, highstate):
"""
When a state fail and is part of a highstate, check
if there is onfail requisites.
When we find onfail requisites, we will consider the state failed
only if at least one of those onfail requisites also failed
Returns:
... | def check_onfail_requisites(state_id, state_result, running, highstate):
| """
When a state fail and is part of a highstate, check
if there is onfail requisites.
When we find onfail requisites, we will consider the state failed
only if at least one of those onfail requisites also failed
Returns:
True: if onfail handlers succeeded
False: if one on thos... | data, dict):
continue
for knob, fvalue in fdata.items():
if knob != "onfail":
continue
for freqs in fvalue:
for fmod, fid in... | 114 | 114 | 383 | 17 | 96 | babs/salt | salt/utils/state.py | Python | check_onfail_requisites | check_onfail_requisites | 72 | 112 | 72 | 72 | 2fe2cf2651aa9f89d846cf7a9e27666d7ab43e61 | bigcode/the-stack | train |
65e63c57d292cb4c76f56659 | train | function | def search_onfail_requisites(sid, highstate):
"""
For a particular low chunk, search relevant onfail related states
"""
onfails = []
if "_|-" in sid:
st = salt.state.split_low_tag(sid)
else:
st = {"__id__": sid}
for fstate, fchunks in highstate.items():
if fstate == s... | def search_onfail_requisites(sid, highstate):
| """
For a particular low chunk, search relevant onfail related states
"""
onfails = []
if "_|-" in sid:
st = salt.state.split_low_tag(sid)
else:
st = {"__id__": sid}
for fstate, fchunks in highstate.items():
if fstate == st["__id__"]:
continue
else... | """
Utility functions for state functions
.. versionadded:: 2018.3.0
"""
import copy
import salt.state
from salt.exceptions import CommandExecutionError
_empty = object()
def gen_tag(low):
"""
Generate the running dict tag string from the low data structure
"""
return "{0[state]}_|-{0[__id__]}_|-... | 102 | 106 | 356 | 12 | 90 | babs/salt | salt/utils/state.py | Python | search_onfail_requisites | search_onfail_requisites | 23 | 69 | 23 | 23 | df230314d3cffe8dd5fb6353074cc37f2432caa1 | bigcode/the-stack | train |
908b13dca0ba7003e1040620 | train | function | def check_result(running, recurse=False, highstate=None):
"""
Check the total return value of the run and determine if the running
dict has any issues
"""
if not isinstance(running, dict):
return False
if not running:
return False
ret = True
for state_id, state_result i... | def check_result(running, recurse=False, highstate=None):
| """
Check the total return value of the run and determine if the running
dict has any issues
"""
if not isinstance(running, dict):
return False
if not running:
return False
ret = True
for state_id, state_result in running.items():
expected_type = dict
# ... | ]:
nret = ofresult
if ofresult is False:
# as soon as we find an errored onfail, we stop
break
# consider that if we parsed onfailes without changing
# the ret, that we have failed... | 88 | 88 | 294 | 13 | 74 | babs/salt | salt/utils/state.py | Python | check_result | check_result | 115 | 150 | 115 | 115 | aa0c68697dd17217eeb7d7e38e91acf4c8a34505 | bigcode/the-stack | train |
5c3e2ed1c45aba930531bbcf | train | function | def get_sls_opts(opts, **kwargs):
"""
Return a copy of the opts for use, optionally load a local config on top
"""
opts = copy.deepcopy(opts)
if "localconfig" in kwargs:
return salt.config.minion_config(kwargs["localconfig"], defaults=opts)
if "saltenv" in kwargs:
saltenv = kwa... | def get_sls_opts(opts, **kwargs):
| """
Return a copy of the opts for use, optionally load a local config on top
"""
opts = copy.deepcopy(opts)
if "localconfig" in kwargs:
return salt.config.minion_config(kwargs["localconfig"], defaults=opts)
if "saltenv" in kwargs:
saltenv = kwargs["saltenv"]
if saltenv ... |
original_return["comment"] += "\n"
original_return["comment"] += "\n".join(sub_comment)
if sub_return["changes"]: # changes always exists
original_return.setdefault("changes", {})
original_return["changes"][subkey] = sub_return["changes"]
return original_return
def get_sl... | 76 | 76 | 256 | 10 | 65 | babs/salt | salt/utils/state.py | Python | get_sls_opts | get_sls_opts | 208 | 235 | 208 | 208 | 5a4885a4d310edabd4ee6feb63eb80bef33fd1fb | bigcode/the-stack | train |
9132b8e05dd52f94759db367 | train | function | def gen_tag(low):
"""
Generate the running dict tag string from the low data structure
"""
return "{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}".format(low)
| def gen_tag(low):
| """
Generate the running dict tag string from the low data structure
"""
return "{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}".format(low)
| """
Utility functions for state functions
.. versionadded:: 2018.3.0
"""
import copy
import salt.state
from salt.exceptions import CommandExecutionError
_empty = object()
def gen_tag(low):
| 44 | 64 | 51 | 5 | 39 | babs/salt | salt/utils/state.py | Python | gen_tag | gen_tag | 16 | 20 | 16 | 16 | d9f751d480628aec78672823244902c41b2b780b | bigcode/the-stack | train |
afedf79274fc6bc4b5b9dc64 | train | function | def update_netplan():
loglevel = 'WARN' # default
for arg in sys.argv[1:]:
if arg == '-h':
print_help(0)
elif arg == '-v':
loglevel='INFO'
elif arg == '-vv':
loglevel='DEBUG'
elif not re.match('^-', arg):
# stop processing switc... | def update_netplan():
| loglevel = 'WARN' # default
for arg in sys.argv[1:]:
if arg == '-h':
print_help(0)
elif arg == '-v':
loglevel='INFO'
elif arg == '-vv':
loglevel='DEBUG'
elif not re.match('^-', arg):
# stop processing switches
break
... | ]} set_all <target_match> <target_value>
{sys.argv[0]} add <target_path> <target_value>
{sys.argv[0]} delete <target_path>
Examples:
{sys.argv[0]} search_params nameservers/search
{sys.argv[0]} get network/ethernets/eno1/mtu
{sys.argv[0]} set network/ethernets/eno1/mtu 1400
{sys.argv[0]} set ne... | 184 | 184 | 614 | 5 | 179 | YanChii/py-netplan-editor | src/netplan_editor/update_netplan_cmd.py | Python | update_netplan | update_netplan | 36 | 145 | 36 | 37 | 25b55af52a094fd3668343a13f0449e670e4a333 | bigcode/the-stack | train |
fb833ae6846c7df56b669054 | train | function | def print_help(exit_val=0, extra_msg=''):
if extra_msg:
print(f'{extra_msg}\n')
print(f'''\
Usage:
{sys.argv[0]} search_params [target_match]
{sys.argv[0]} get <target_path>
{sys.argv[0]} set <target_path> <target_value>
{sys.argv[0]} set_all <target_match> <target_value>
{sy... | def print_help(exit_val=0, extra_msg=''):
| if extra_msg:
print(f'{extra_msg}\n')
print(f'''\
Usage:
{sys.argv[0]} search_params [target_match]
{sys.argv[0]} get <target_path>
{sys.argv[0]} set <target_path> <target_value>
{sys.argv[0]} set_all <target_match> <target_value>
{sys.argv[0]} add <target_path> <t... |
import sys
import re
from argparse import ArgumentParser
import logging
from . import netplan_editor
def print_help(exit_val=0, extra_msg=''):
| 35 | 77 | 258 | 12 | 22 | YanChii/py-netplan-editor | src/netplan_editor/update_netplan_cmd.py | Python | print_help | print_help | 9 | 33 | 9 | 9 | 26fb233e1092cf92787bfc9fd4387ae0028c2066 | bigcode/the-stack | train |
72ff5063c078bdde706cfc30 | train | function | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_channel_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
categor... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_channel_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
categor... | if "Collection" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
filter_by = {tested_f... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_channel_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
categor... | 83 | 74 | 249 | 83 | 0 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_products_with_filtering_with_channel_as_staff_user | test_products_with_filtering_with_channel_as_staff_user | 195 | 231 | 195 | 209 | 007396e0f0f9983918a7a9389e6cc929e236195c | bigcode/the-stack | train |
5da500be261948cf832fe43e | train | function | @pytest.mark.parametrize(
"tested_field, attribute_count",
[
("inCategory", 0),
# Products not visible in listings should be visible in collections
("inCollection", 5),
],
)
def test_products_with_filtering_with_not_visible_in_listings_as_anonymous_client(
tested_field,
attri... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[
("inCategory", 0),
# Products not visible in listings should be visible in collections
("inCollection", 5),
],
)
def test_products_with_filtering_with_not_visible_in_listings_as_anonymous_client(
tested_field,
attri... | if "Collection" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
filter_by = {tested_f... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[
("inCategory", 0),
# Products not visible in listings should be visible in collections
("inCollection", 5),
],
)
def test_products_with_filtering_with_not_visible_in_listings_as_anonymous_client(
tested_field,
attri... | 99 | 74 | 247 | 99 | 0 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_products_with_filtering_with_not_visible_in_listings_as_anonymous_client | test_products_with_filtering_with_not_visible_in_listings_as_anonymous_client | 334 | 368 | 334 | 351 | c3dd8f2f21cfc8b8beeba67e13cbed71258826a6 | bigcode/the-stack | train |
15d33e2b17f3b470efdf765b | train | function | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_as_anonymous_client(
tested_field,
attribute_count,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
channel_USD,
):
# ... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_as_anonymous_client(
tested_field,
attribute_count,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
channel_USD,
):
# ... | if "Collection" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
filter_by = {tested_f... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_as_anonymous_client(
tested_field,
attribute_count,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
channel_USD,
):
# ... | 76 | 67 | 224 | 76 | 0 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_products_with_filtering_as_anonymous_client | test_products_with_filtering_as_anonymous_client | 262 | 292 | 262 | 275 | 49dfeedf2f24730732e4f3c691b9b7bc58d59865 | bigcode/the-stack | train |
8dd2f36f473e1ade1d5ce6b3 | train | function | @pytest.fixture
def attributes_for_filtering_with_channels(
collection, category, channel_USD, channel_PLN, other_channel_USD
):
attributes = Attribute.objects.bulk_create(
[
Attribute(
name="Attr1",
slug="attr1",
value_required=True,
... | @pytest.fixture
def attributes_for_filtering_with_channels(
collection, category, channel_USD, channel_PLN, other_channel_USD
):
| attributes = Attribute.objects.bulk_create(
[
Attribute(
name="Attr1",
slug="attr1",
value_required=True,
storefront_search_position=4,
),
Attribute(
name="AttrAttr1",
slug="at... | from decimal import Decimal
import graphene
import pytest
from .....attribute.models import Attribute, AttributeProduct, AttributeVariant
from .....product import ProductTypeKind
from .....product.models import (
Product,
ProductChannelListing,
ProductType,
ProductVariant,
ProductVariantChannelLis... | 108 | 218 | 728 | 30 | 77 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | attributes_for_filtering_with_channels | attributes_for_filtering_with_channels | 18 | 142 | 18 | 21 | c1889871101100ecc94481d3dbbf90ce6c791d65 | bigcode/the-stack | train |
87ff61d3d8b4b26abfe2e80b | train | function | def test_products_with_alternative_filtering_with_channel_as_staff_user(
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
category,
channel_USD,
):
# given
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
filter_by = {"inCateg... | def test_products_with_alternative_filtering_with_channel_as_staff_user(
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
category,
channel_USD,
):
# given
| filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
filter_by = {"inCategory": filtered_by_node_id}
filter_by["channel"] = channel_USD.slug
variables = {"filter": filter_by}
# when
response = staff_api_client.post_graphql(
QUERY_ATTRIBUTES_FILTERING,
varia... | = content["data"]["attributes"]["edges"]
assert len(attribute_nodes) == attribute_count
def test_products_with_alternative_filtering_with_channel_as_staff_user(
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
category,
channel_USD,
):
# given
| 64 | 64 | 169 | 45 | 18 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_products_with_alternative_filtering_with_channel_as_staff_user | test_products_with_alternative_filtering_with_channel_as_staff_user | 234 | 259 | 234 | 241 | 29c0058b839fec91685ac1fdb92ba8cc3b42115c | bigcode/the-stack | train |
272e3f4f28803e23343e6fe5 | train | function | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_not_published_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
c... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_not_published_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
c... | if "Collection" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
filter_by = {tested_f... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_not_published_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_channels,
c... | 86 | 75 | 253 | 86 | 0 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_products_with_filtering_with_not_published_as_staff_user | test_products_with_filtering_with_not_published_as_staff_user | 371 | 407 | 371 | 385 | 2db5eda1a8daaa8f79e6830a4872c2e2662ae6ee | bigcode/the-stack | train |
cf3cf9c7ced2ba6bbc169ef8 | train | function | @pytest.mark.parametrize(
"tested_field",
["inCategory", "inCollection"],
)
def test_products_with_filtering_not_existing_channel(
tested_field,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
):
# given
if "Collection" in tested_field:
filtered_by_n... | @pytest.mark.parametrize(
"tested_field",
["inCategory", "inCollection"],
)
def test_products_with_filtering_not_existing_channel(
tested_field,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
):
# given
| if "Collection" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
filter_by = {tested_f... | len(attribute_nodes) == attribute_count
@pytest.mark.parametrize(
"tested_field",
["inCategory", "inCollection"],
)
def test_products_with_filtering_not_existing_channel(
tested_field,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
):
# given
| 64 | 64 | 203 | 56 | 7 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_products_with_filtering_not_existing_channel | test_products_with_filtering_not_existing_channel | 443 | 471 | 443 | 454 | 259b1fffa7dc0c2c5adffeb58711e3fa281df35a | bigcode/the-stack | train |
28189bd3692b00b1768171e8 | train | function | @pytest.mark.parametrize(
"tested_field",
["inCategory", "inCollection"],
)
def test_attributes_with_filtering_without_channel(
tested_field,
staff_api_client,
permission_manage_products,
category,
collection,
):
# given
if "Collection" in tested_field:
filtered_by_node_id = ... | @pytest.mark.parametrize(
"tested_field",
["inCategory", "inCollection"],
)
def test_attributes_with_filtering_without_channel(
tested_field,
staff_api_client,
permission_manage_products,
category,
collection,
):
# given
| if "Collection" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
filter_by = {tested_f... | name
}
}
}
}
"""
@pytest.mark.parametrize(
"tested_field",
["inCategory", "inCollection"],
)
def test_attributes_with_filtering_without_channel(
tested_field,
staff_api_client,
permission_manage_products,
category,
collection,
):
# given
| 64 | 64 | 197 | 53 | 11 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_attributes_with_filtering_without_channel | test_attributes_with_filtering_without_channel | 162 | 192 | 162 | 173 | 7d75643f311bf3d743f252d14de8c8ca89ecd134 | bigcode/the-stack | train |
0f09aa8f55f5fec249557dc2 | train | function | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 0), ("inCollection", 0)],
)
def test_products_with_filtering_with_not_published_as_anonymous_client(
tested_field,
attribute_count,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
oth... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 0), ("inCollection", 0)],
)
def test_products_with_filtering_with_not_published_as_anonymous_client(
tested_field,
attribute_count,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
oth... | if "Collection" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
filter_by = {tested_f... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 0), ("inCollection", 0)],
)
def test_products_with_filtering_with_not_published_as_anonymous_client(
tested_field,
attribute_count,
api_client,
attributes_for_filtering_with_channels,
category,
collection,
oth... | 81 | 69 | 230 | 81 | 0 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_products_with_filtering_with_not_published_as_anonymous_client | test_products_with_filtering_with_not_published_as_anonymous_client | 410 | 440 | 410 | 423 | 0f6bfa60b1c8836ad0dce0bf7998e1b5ca9e7e8a | bigcode/the-stack | train |
ead9465b4911f11a68d4b77f | train | function | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_not_visible_in_listings_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_chann... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_not_visible_in_listings_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_chann... | if "Collection" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
raise AssertionError(tested_field)
filter_by = {tested_f... | @pytest.mark.parametrize(
"tested_field, attribute_count",
[("inCategory", 5), ("inCollection", 5)],
)
def test_products_with_filtering_with_not_visible_in_listings_as_staff_user(
tested_field,
attribute_count,
staff_api_client,
permission_manage_products,
attributes_for_filtering_with_chann... | 87 | 75 | 253 | 87 | 0 | fairhopeweb/saleor | saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py | Python | test_products_with_filtering_with_not_visible_in_listings_as_staff_user | test_products_with_filtering_with_not_visible_in_listings_as_staff_user | 295 | 331 | 295 | 309 | da411acfd71f1b8cd8fbaddad15cb5c57ba05f94 | bigcode/the-stack | train |
060a723fec02027e9d4193fb | train | class | class Version(Plugin):
def __init__(self):
super().__init__()
self.inner_slots = ["Component", "Product"]
self.inner_rels = ['Version']
self.inner_attrs = []
self.inner_actions = []
self.sample_slots = {
"Product": {'kind': TEXT, 'source': GRAPH,... | class Version(Plugin):
| def __init__(self):
super().__init__()
self.inner_slots = ["Component", "Product"]
self.inner_rels = ['Version']
self.inner_attrs = []
self.inner_actions = []
self.sample_slots = {
"Product": {'kind': TEXT, 'source': GRAPH, 'retrieve': ALL, 'matc... | from plugins.plugin import Plugin
from plugins.constants import TEXT, GRAPH, ALL, EXACT_MATCH, REGEX_MATCH, SHAPE, ENTITY, ATTR, REL, SOME
from spacy.matcher import Matcher, PhraseMatcher
from py2neo import Graph
import spacy
class Version(Plugin):
| 60 | 66 | 222 | 5 | 54 | javierivanov/kgb | plugins/version.py | Python | Version | Version | 7 | 35 | 7 | 7 | 2d30bedb4a8439b427f09e89d2a8254d94f08d82 | bigcode/the-stack | train |
559035be3a3f568be32aed65 | train | class | class RoomTopicTestCase(RestTestCase):
""" Tests /rooms/$room_id/topic REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserver(
... | class RoomTopicTestCase(RestTestCase):
| """ Tests /rooms/$room_id/topic REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserver(
"red",
http_client... | with custom config keys, expect new room id
(code, response) = yield self.mock_resource.trigger(
"POST",
"/createRoom",
'{"custom":"stuff"}')
self.assertEquals(200, code)
self.assertTrue("room_id" in response)
@defer.inlineCallbacks
def test_post_roo... | 256 | 256 | 902 | 9 | 247 | meharimg/swarm-im | tests/rest/client/v1/test_rooms.py | Python | RoomTopicTestCase | RoomTopicTestCase | 576 | 688 | 576 | 576 | 24ca3a3a4beb52a9751ccec14a93029c663acd02 | bigcode/the-stack | train |
cc863aa65edd289e15376106 | train | class | class RoomMessageListTestCase(RestTestCase):
""" Tests /rooms/$room_id/messages REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homese... | class RoomMessageListTestCase(RestTestCase):
| """ Tests /rooms/$room_id/messages REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserver(
"red",
http_cli... | state"]:
if "state_key" not in event:
continue
t = event["type"]
if t not in state:
state[t] = []
state[t].append(event)
self.assertTrue("m.room.create" in state)
self.assertTrue("messages" in response)
self.assert... | 162 | 163 | 544 | 10 | 152 | meharimg/swarm-im | tests/rest/client/v1/test_rooms.py | Python | RoomMessageListTestCase | RoomMessageListTestCase | 997 | 1,055 | 997 | 997 | 6b160168dfc04dd8cf27d4c0740e713ea019e30f | bigcode/the-stack | train |
b5fd94d3db76979a30f3ba43 | train | class | class RoomsCreateTestCase(RestTestCase):
""" Tests /rooms and /rooms/$room_id REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserv... | class RoomsCreateTestCase(RestTestCase):
| """ Tests /rooms and /rooms/$room_id REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserver(
"red",
http_c... | _creator = "@some_other_guy:red"
room_id = yield self.create_room_as(room_creator)
room_path = "/rooms/%s/members" % room_id
yield self.invite(room=room_id, src=room_creator,
targ=self.user_id)
# can't see list if you're just invited.
(code, response) = ... | 208 | 208 | 695 | 9 | 199 | meharimg/swarm-im | tests/rest/client/v1/test_rooms.py | Python | RoomsCreateTestCase | RoomsCreateTestCase | 484 | 573 | 484 | 484 | fe9f2d986d6455965349d0657ee312df2b0c6505 | bigcode/the-stack | train |
011045371f41002c6bb5e922 | train | class | class RoomMessagesTestCase(RestTestCase):
""" Tests /rooms/$room_id/messages/$user_id/$msg_id REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield set... | class RoomMessagesTestCase(RestTestCase):
| """ Tests /rooms/$room_id/messages/$user_id/$msg_id REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserver(
"red",
... | code, response) = yield self.mock_resource.trigger("PUT", path, content)
self.assertEquals(200, code, msg=str(response))
(code, response) = yield self.mock_resource.trigger("GET", path, None)
self.assertEquals(200, code, msg=str(response))
self.assertEquals(json.loads(content), response... | 252 | 252 | 843 | 9 | 243 | meharimg/swarm-im | tests/rest/client/v1/test_rooms.py | Python | RoomMessagesTestCase | RoomMessagesTestCase | 823 | 920 | 823 | 823 | 9a13bec74d8df9c81f8bb00f41be7dd0e3eff90a | bigcode/the-stack | train |
256338476289782baab5ee28 | train | class | class RoomMemberStateTestCase(RestTestCase):
""" Tests /rooms/$room_id/members/$user_id/state REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield set... | class RoomMemberStateTestCase(RestTestCase):
| """ Tests /rooms/$room_id/members/$user_id/state REST events. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserver(
"red",
... | (code, response) = yield self.mock_resource.trigger_get(self.path)
self.assertEquals(404, code, msg=str(response))
# valid put
content = '{"topic":"Topic name"}'
(code, response) = yield self.mock_resource.trigger(
"PUT", self.path, content
)
self.ass... | 256 | 256 | 1,132 | 10 | 246 | meharimg/swarm-im | tests/rest/client/v1/test_rooms.py | Python | RoomMemberStateTestCase | RoomMemberStateTestCase | 691 | 820 | 691 | 691 | e4aa49e9c74ee76afab81a74b1d1fb18f7a92969 | bigcode/the-stack | train |
a35daa3183e2a2d636a9653e | train | class | class RoomInitialSyncTestCase(RestTestCase):
""" Tests /rooms/$room_id/initialSync. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserver(
... | class RoomInitialSyncTestCase(RestTestCase):
| """ Tests /rooms/$room_id/initialSync. """
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
self.auth_user_id = self.user_id
hs = yield setup_test_homeserver(
"red",
http_client=None,... | code, response) = yield self.mock_resource.trigger("PUT", path, content)
self.assertEquals(200, code, msg=str(response))
# (code, response) = yield self.mock_resource.trigger("GET", path, None)
# self.assertEquals(200, code, msg=str(response))
# self.assert_dict(json.loads(content), respon... | 164 | 164 | 547 | 10 | 154 | meharimg/swarm-im | tests/rest/client/v1/test_rooms.py | Python | RoomInitialSyncTestCase | RoomInitialSyncTestCase | 923 | 994 | 923 | 923 | 3f4580c093d7f7a2585cf1eb82e16944704bebdb | bigcode/the-stack | train |
78de65dd4b44ce1bea08eab2 | train | class | class RoomPermissionsTestCase(RestTestCase):
""" Tests room permissions. """
user_id = "@sid1:red"
rmcreator_id = "@notme:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
hs = yield setup_test_homeserver(
"red",
... | class RoomPermissionsTestCase(RestTestCase):
| """ Tests room permissions. """
user_id = "@sid1:red"
rmcreator_id = "@notme:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
hs = yield setup_test_homeserver(
"red",
http_client=None,
replica... | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | 241 | 256 | 3,126 | 9 | 232 | meharimg/swarm-im | tests/rest/client/v1/test_rooms.py | Python | RoomPermissionsTestCase | RoomPermissionsTestCase | 37 | 398 | 37 | 37 | d31db4021e7b6ba6b204db3be53916d87c177231 | bigcode/the-stack | train |
b9d544642b3caa21c7c56dce | train | class | class RoomsMemberListTestCase(RestTestCase):
""" Tests /rooms/$room_id/members/list REST events."""
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
hs = yield setup_test_homeserver(
"red",
h... | class RoomsMemberListTestCase(RestTestCase):
| """ Tests /rooms/$room_id/members/list REST events."""
user_id = "@sid1:red"
@defer.inlineCallbacks
def setUp(self):
self.mock_resource = MockHttpResource(prefix=PATH_PREFIX)
hs = yield setup_test_homeserver(
"red",
http_client=None,
replication_laye... | room, user=self.user_id)
yield self.leave(room=room, user=self.user_id)
# set [invite/join/left] of self, set [invite/join/left] of other,
# expect all 403s
for usr in [self.user_id, self.rmcreator_id]:
yield self.change_membership(
room=room,
... | 209 | 209 | 697 | 10 | 199 | meharimg/swarm-im | tests/rest/client/v1/test_rooms.py | Python | RoomsMemberListTestCase | RoomsMemberListTestCase | 401 | 481 | 401 | 401 | a875adf9ea0198dbec8996f26b405dba0c407451 | bigcode/the-stack | train |
fa7f89e8a5960c328424d6f0 | train | class | class bert_attention(tf.keras.layers.Layer):
def __init__(self, **kwargs):
self.nums = 4
super(bert_attention, self).__init__(**kwargs)
def build(self, input_shape):
self.features_dim = input_shape[-1]//self.nums
self.step_dim = input_shape[1]
self.W = self.add_weight(na... | class bert_attention(tf.keras.layers.Layer):
| def __init__(self, **kwargs):
self.nums = 4
super(bert_attention, self).__init__(**kwargs)
def build(self, input_shape):
self.features_dim = input_shape[-1]//self.nums
self.step_dim = input_shape[1]
self.W = self.add_weight(name='{}_W'.format(self.name),
... | #!/usr/bin/env python
#-*-coding:utf-8-*-
import kashgari
import tensorflow as tf
from tensorflow.python import keras
from tensorflow.python.keras import backend as K
L = keras.layers
initializers = keras.initializers
regularizers = keras.regularizers
constraints = keras.constraints
#np.random.seed(2018)
class bert_a... | 82 | 201 | 673 | 8 | 74 | ericperfect/Bert_Position_BiLSTM_Attention_CRF_LSTMDecoder | kashgari/layers/bert_attention4.py | Python | bert_attention | bert_attention | 15 | 73 | 15 | 15 | f8f805568eff7901ddf702f84304c720b22e545d | bigcode/the-stack | train |
7ab3702146e10e8af964fbeb | train | function | def sqrt(x):
"""
Calculate the square root of argument x.
"""
# Check that x is positive.
if x < 0:
print("Error negative value supplied")
return -1
else:
print("Here we go..")
# Initial guess for the square root.
z = x / 2.0
# Continuously ipmrove the gues... | def sqrt(x):
| """
Calculate the square root of argument x.
"""
# Check that x is positive.
if x < 0:
print("Error negative value supplied")
return -1
else:
print("Here we go..")
# Initial guess for the square root.
z = x / 2.0
# Continuously ipmrove the guess.
# Adap... | #! /user/bin/env/python3
# Abdalla Fadul
#calculate the square root of number.
def sqrt(x):
| 27 | 64 | 141 | 4 | 23 | abdallaf/python.newton.root | calcsqrt.py | Python | sqrt | sqrt | 6 | 26 | 6 | 6 | bf26b470a8fe1233a5d7e0f5a9ca7a57aeb51512 | bigcode/the-stack | train |
f7c84ca6ca169f24e217c153 | train | function | def default_latex_use_xindy(config: Config) -> bool:
""" Better default latex_use_xindy settings for specific engines. """
return config.latex_engine in {'xelatex', 'lualatex'}
| def default_latex_use_xindy(config: Config) -> bool:
| """ Better default latex_use_xindy settings for specific engines. """
return config.latex_engine in {'xelatex', 'lualatex'}
| uplatex':
return {'manual': 'ujbook',
'howto': 'ujreport'}
else:
return {'manual': 'jsbook',
'howto': 'jreport'}
else:
return {}
def default_latex_use_xindy(config: Config) -> bool:
| 63 | 64 | 44 | 14 | 49 | stephenfin/sphinx | sphinx/builders/latex/__init__.py | Python | default_latex_use_xindy | default_latex_use_xindy | 439 | 441 | 439 | 439 | a2a913b461d5128fc49d13f485e9d2a6dd461e95 | bigcode/the-stack | train |
a40ec0ce7fe5beeeaa10d45f | train | function | def default_latex_documents(config: Config) -> List[Tuple[str, str, str, str, str]]:
""" Better default latex_documents settings. """
project = texescape.escape(config.project, config.latex_engine)
author = texescape.escape(config.author, config.latex_engine)
return [(config.master_doc,
mak... | def default_latex_documents(config: Config) -> List[Tuple[str, str, str, str, str]]:
| """ Better default latex_documents settings. """
project = texescape.escape(config.project, config.latex_engine)
author = texescape.escape(config.author, config.latex_engine)
return [(config.master_doc,
make_filename_from_project(config.project) + '.tex',
texescape.escape_abbr(... | _use_xindy(config: Config) -> bool:
""" Better default latex_use_xindy settings for specific engines. """
return config.latex_engine in {'xelatex', 'lualatex'}
def default_latex_documents(config: Config) -> List[Tuple[str, str, str, str, str]]:
| 63 | 64 | 99 | 23 | 40 | stephenfin/sphinx | sphinx/builders/latex/__init__.py | Python | default_latex_documents | default_latex_documents | 444 | 452 | 444 | 444 | eeee99015c9291a25c19440410e37c68f71151cf | bigcode/the-stack | train |
978f74cf93f704c65badbda5 | train | class | class LaTeXBuilder(Builder):
"""
Builds LaTeX output to create PDF.
"""
name = 'latex'
format = 'latex'
epilog = __('The LaTeX files are in %(outdir)s.')
if os.name == 'posix':
epilog += __("\nRun 'make' in that directory to run these through "
"(pdf)latex\n"
... | class LaTeXBuilder(Builder):
| """
Builds LaTeX output to create PDF.
"""
name = 'latex'
format = 'latex'
epilog = __('The LaTeX files are in %(outdir)s.')
if os.name == 'posix':
epilog += __("\nRun 'make' in that directory to run these through "
"(pdf)latex\n"
"(use `make... | C utf8 ',
'bg': '-L bulgarian -C utf8 ',
'mk': '-L macedonian -C utf8 ',
'mn': '-L mongolian -C cyrillic-utf8 ',
'ru': '-L russian -C utf8 ',
'sr': '-L serbian -C utf8 ',
'sh-cyrl': '-L serbian -C utf8 ',
'sh': '-L serbian -C utf8 ', # trick, no conflict
'uk': '-L ukrainian -C ut... | 256 | 256 | 2,849 | 8 | 248 | stephenfin/sphinx | sphinx/builders/latex/__init__.py | Python | LaTeXBuilder | LaTeXBuilder | 109 | 403 | 109 | 109 | 2f932296fbb98d329d42d9d82135f1b0d80e75ad | bigcode/the-stack | train |
23aefecf7ad6bf8fa2ecbd0a | train | function | def validate_config_values(app: Sphinx, config: Config) -> None:
for key in list(config.latex_elements):
if key not in DEFAULT_SETTINGS:
msg = __("Unknown configure key: latex_elements[%r]. ignored.")
logger.warning(msg % (key,))
config.latex_elements.pop(key)
| def validate_config_values(app: Sphinx, config: Config) -> None:
| for key in list(config.latex_elements):
if key not in DEFAULT_SETTINGS:
msg = __("Unknown configure key: latex_elements[%r]. ignored.")
logger.warning(msg % (key,))
config.latex_elements.pop(key)
| self.babel.get_language()
filename = path.join(package_dir, 'templates', 'latex', 'sphinxmessages.sty_t')
copy_asset_file(filename, self.outdir, context=context, renderer=LaTeXRenderer())
def validate_config_values(app: Sphinx, config: Config) -> None:
| 64 | 64 | 65 | 16 | 48 | stephenfin/sphinx | sphinx/builders/latex/__init__.py | Python | validate_config_values | validate_config_values | 406 | 411 | 406 | 406 | 42e892fc178dc296e763b77d554093e98a06c2e3 | bigcode/the-stack | train |
3f9166ccd24d3211a3776507 | train | function | def default_latex_engine(config: Config) -> str:
""" Better default latex_engine settings for specific languages. """
if config.language == 'ja':
return 'platex'
elif (config.language or '').startswith('zh'):
return 'xelatex'
elif config.language == 'el':
return 'xelatex'
els... | def default_latex_engine(config: Config) -> str:
| """ Better default latex_engine settings for specific languages. """
if config.language == 'ja':
return 'platex'
elif (config.language or '').startswith('zh'):
return 'xelatex'
elif config.language == 'el':
return 'xelatex'
else:
return 'pdflatex'
| -> None:
for key in list(config.latex_elements):
if key not in DEFAULT_SETTINGS:
msg = __("Unknown configure key: latex_elements[%r]. ignored.")
logger.warning(msg % (key,))
config.latex_elements.pop(key)
def default_latex_engine(config: Config) -> str:
| 64 | 64 | 79 | 12 | 52 | stephenfin/sphinx | sphinx/builders/latex/__init__.py | Python | default_latex_engine | default_latex_engine | 414 | 423 | 414 | 414 | ddd9591070761cebd2e52cb068d1a40b3ff851fe | bigcode/the-stack | train |
8fc3c164ea55ffa1f0eb7683 | train | function | def setup(app: Sphinx) -> Dict[str, Any]:
app.setup_extension('sphinx.builders.latex.transforms')
app.add_builder(LaTeXBuilder)
app.connect('config-inited', validate_config_values)
app.add_config_value('latex_engine', default_latex_engine, None,
ENUM('pdflatex', 'xelatex', 'lu... | def setup(app: Sphinx) -> Dict[str, Any]:
| app.setup_extension('sphinx.builders.latex.transforms')
app.add_builder(LaTeXBuilder)
app.connect('config-inited', validate_config_values)
app.add_config_value('latex_engine', default_latex_engine, None,
ENUM('pdflatex', 'xelatex', 'lualatex', 'platex', 'uplatex'))
app.add... | str, str, str]]:
""" Better default latex_documents settings. """
project = texescape.escape(config.project, config.latex_engine)
author = texescape.escape(config.author, config.latex_engine)
return [(config.master_doc,
make_filename_from_project(config.project) + '.tex',
texe... | 95 | 96 | 323 | 13 | 82 | stephenfin/sphinx | sphinx/builders/latex/__init__.py | Python | setup | setup | 455 | 482 | 455 | 455 | 47a03d9af3db6e28d527a7efe5a8e61bd77e4034 | bigcode/the-stack | train |
cd98f17e4c5430ef1c445f04 | train | function | def default_latex_docclass(config: Config) -> Dict[str, str]:
""" Better default latex_docclass settings for specific languages. """
if config.language == 'ja':
if config.latex_engine == 'uplatex':
return {'manual': 'ujbook',
'howto': 'ujreport'}
else:
... | def default_latex_docclass(config: Config) -> Dict[str, str]:
| """ Better default latex_docclass settings for specific languages. """
if config.language == 'ja':
if config.latex_engine == 'uplatex':
return {'manual': 'ujbook',
'howto': 'ujreport'}
else:
return {'manual': 'jsbook',
'howto': 'jre... | ':
return 'platex'
elif (config.language or '').startswith('zh'):
return 'xelatex'
elif config.language == 'el':
return 'xelatex'
else:
return 'pdflatex'
def default_latex_docclass(config: Config) -> Dict[str, str]:
| 64 | 64 | 94 | 16 | 48 | stephenfin/sphinx | sphinx/builders/latex/__init__.py | Python | default_latex_docclass | default_latex_docclass | 426 | 436 | 426 | 426 | be72dd870fd53bc2e0723a88e5433353271d2389 | bigcode/the-stack | train |
5e143ede0ff268e548c0b5ea | train | function | def get_recent_posts_instagram(handle):
"""Api for basic details
Arguments:
handle {str}: username
Returns:
json -- returns basic details
"""
result = None
try:
url = "https://www.instagram.com/{}/?__a=1".format(handle)
response = requests.get(url)
if (r... | def get_recent_posts_instagram(handle):
| """Api for basic details
Arguments:
handle {str}: username
Returns:
json -- returns basic details
"""
result = None
try:
url = "https://www.instagram.com/{}/?__a=1".format(handle)
response = requests.get(url)
if (response.status_code != 200):
... | from requests_oauthlib import OAuth1Session
import json
import logging
import time
import requests
def get_recent_posts_instagram(handle):
| 30 | 64 | 112 | 8 | 21 | mampilly/backend-global | app/routes/socialmedia/service/social_media_service.py | Python | get_recent_posts_instagram | get_recent_posts_instagram | 8 | 26 | 8 | 8 | 753bea9404de2a6881b11a492ccb5e57746b978e | bigcode/the-stack | train |
fa9e54be9768e0a93d78d5e5 | train | function | def get_recent_posts_twitter(handle):
"""Api for basic details
Arguments:
handle
Returns:
json -- returns basic details
"""
result = None
try:
url = "https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name={}&count=10&exclude_replies=true&include_r... | def get_recent_posts_twitter(handle):
| """Api for basic details
Arguments:
handle
Returns:
json -- returns basic details
"""
result = None
try:
url = "https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name={}&count=10&exclude_replies=true&include_rts=false".format(
handle)
... | /{}/?__a=1".format(handle)
response = requests.get(url)
if (response.status_code != 200):
return None
result = response.json()
except Exception as e:
logging.error("error is {}".format(e))
return result
def get_recent_posts_twitter(handle):
| 66 | 66 | 222 | 8 | 57 | mampilly/backend-global | app/routes/socialmedia/service/social_media_service.py | Python | get_recent_posts_twitter | get_recent_posts_twitter | 29 | 53 | 29 | 29 | eb678e97b5da32f7b7d511eb217e76ee7617eb82 | bigcode/the-stack | train |
fbd38aa8c70f6e48c2235e67 | train | class | class FeedBackStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = mod... | class FeedBackStudent(models.Model):
| id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.no... | )
leave_message = models.TextField()
leave_status = models.BooleanField(default=False)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class FeedBackStudent(models.Model):
| 64 | 64 | 85 | 7 | 57 | mipertille/OpenEscola | core/models.py | Python | FeedBackStudent | FeedBackStudent | 117 | 124 | 117 | 117 | 33fbc9ff8a8a23b3185aa993a1d78abbcd680c85 | bigcode/the-stack | train |
b968bb222f4418c17ee71dc4 | train | class | class Admin(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager... | class Admin(models.Model):
| id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
| .Manager()
class CustomUser(AbstractUser):
user_type_data = (
(1, 'HOD'),
(2, 'Staff'),
(3, 'Student')
)
user_type = models.CharField(default=1, choices=user_type_data, max_length=10)
class Admin(models.Model):
| 64 | 64 | 69 | 5 | 59 | mipertille/OpenEscola | core/models.py | Python | Admin | Admin | 33 | 38 | 33 | 33 | 63acb231c55440360c39f38adc410f0aab38c792 | bigcode/the-stack | train |
66a6d99e93de3b0902d5f0ec | train | function | @receiver(post_save, sender=CustomUser)
def create_user_profile(sender, instance, created, **kwargs):
if created:
if instance.user_type == 1:
Admin.objects.create(admin=instance)
if instance.user_type == 2:
Staffs.objects.create(admin=instance)
if instance.user_type =... | @receiver(post_save, sender=CustomUser)
def create_user_profile(sender, instance, created, **kwargs):
| if created:
if instance.user_type == 1:
Admin.objects.create(admin=instance)
if instance.user_type == 2:
Staffs.objects.create(admin=instance)
if instance.user_type == 3:
Students.objects.create(
admin=instance,
course_id=Co... | .CASCADE)
message = models.TextField()
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
@receiver(post_save, sender=CustomUser)
def create_user_profile(sender, instance, created, **kwargs):
| 64 | 64 | 112 | 23 | 41 | mipertille/OpenEscola | core/models.py | Python | create_user_profile | create_user_profile | 155 | 168 | 155 | 156 | 91c0695d704b780ac3eb0ea7f47dd85e3b76eb0a | bigcode/the-stack | train |
fc21fdaae8597df60640abdf | train | class | class AttendanceReport(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.DO_NOTHING)
attendance_id = models.ForeignKey(Attendance, on_delete=models.CASCADE)
status = models.BooleanField(default=False)
create_at = models.DateTimeField(def... | class AttendanceReport(models.Model):
| id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.DO_NOTHING)
attendance_id = models.ForeignKey(Attendance, on_delete=models.CASCADE)
status = models.BooleanField(default=False)
create_at = models.DateTimeField(default=timezone.now, editable=False)
... | _now_add=True)
session_year_id = models.ForeignKey(SessionYear, on_delete=models.CASCADE)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class AttendanceReport(models.Model):
| 64 | 64 | 95 | 6 | 58 | mipertille/OpenEscola | core/models.py | Python | AttendanceReport | AttendanceReport | 85 | 92 | 85 | 85 | c35415a610f59d6cfe32b1e9d0f8ae77b4446a6d | bigcode/the-stack | train |
9309dab457298b9972de5340 | train | class | class LeaveReportStaff(models.Model):
id = models.AutoField(primary_key=True)
staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
leave_date = models.CharField(max_length=255)
leave_message = models.TextField()
leave_status = models.BooleanField(default=False)
create_at = models.DateT... | class LeaveReportStaff(models.Model):
| id = models.AutoField(primary_key=True)
staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
leave_date = models.CharField(max_length=255)
leave_message = models.TextField()
leave_status = models.BooleanField(default=False)
create_at = models.DateTimeField(default=timezone.now, editabl... | )
leave_message = models.TextField()
leave_status = models.BooleanField(default=False)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class LeaveReportStaff(models.Model):
| 64 | 64 | 101 | 7 | 57 | mipertille/OpenEscola | core/models.py | Python | LeaveReportStaff | LeaveReportStaff | 106 | 114 | 106 | 106 | eccda3bfc322524f9219458003994ebbbc46d357 | bigcode/the-stack | train |
8d195e19387a7dfdc2a096d9 | train | class | class Courses(models.Model):
id = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=255)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
| class Courses(models.Model):
| id = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=255)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
|
from django.dispatch import receiver
from django.utils import timezone
# Create your models here.
class SessionYear(models.Model):
id = models.AutoField(primary_key=True)
session_start_year = models.DateField()
session_end_year = models.DateField()
objects = models.Manager()
class Courses(models.Mode... | 64 | 64 | 65 | 5 | 59 | mipertille/OpenEscola | core/models.py | Python | Courses | Courses | 16 | 21 | 16 | 16 | 003cfe36bd5a70cfb822f684c89d2bc663975cb3 | bigcode/the-stack | train |
445d3c6976fa3e23c3c9a00e | train | class | class Attendance(models.Model):
id = models.AutoField(primary_key=True)
subject_id = models.ForeignKey(Subject, on_delete=models.DO_NOTHING)
attendance_date = models.DateTimeField(auto_now_add=True)
session_year_id = models.ForeignKey(SessionYear, on_delete=models.CASCADE)
create_at = models.DateTim... | class Attendance(models.Model):
| id = models.AutoField(primary_key=True)
subject_id = models.ForeignKey(Subject, on_delete=models.DO_NOTHING)
attendance_date = models.DateTimeField(auto_now_add=True)
session_year_id = models.ForeignKey(SessionYear, on_delete=models.CASCADE)
create_at = models.DateTimeField(default=timezone.now, edi... | timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
# auto_now_add = True
# https://stackoverflow.com/questions/56546124/django-fixtures-and-auto-now-add-date-time-field
class Attendance(models.Model):
| 64 | 64 | 99 | 5 | 58 | mipertille/OpenEscola | core/models.py | Python | Attendance | Attendance | 75 | 82 | 75 | 75 | 39d2fdbdf6db94a7ca5608de366d4f42c9705723 | bigcode/the-stack | train |
4829e6c16333de48b5beee01 | train | class | class LeaveReportStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
leave_date = models.CharField(max_length=255)
leave_message = models.TextField()
leave_status = models.BooleanField(default=False)
create_at = models... | class LeaveReportStudent(models.Model):
| id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
leave_date = models.CharField(max_length=255)
leave_message = models.TextField()
leave_status = models.BooleanField(default=False)
create_at = models.DateTimeField(default=timezone.now, edi... | .ForeignKey(Attendance, on_delete=models.CASCADE)
status = models.BooleanField(default=False)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class LeaveReportStudent(models.Model):
| 64 | 64 | 100 | 7 | 57 | mipertille/OpenEscola | core/models.py | Python | LeaveReportStudent | LeaveReportStudent | 95 | 103 | 95 | 95 | 7d52e34c82f6a1b83e94d17f57d78318aa3fc380 | bigcode/the-stack | train |
b790a3f96d9ed35008743bce | train | class | class NotificationsStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
message = models.TextField()
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now_add=True)
objects = mode... | class NotificationsStudent(models.Model):
| id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
message = models.TextField()
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
| on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class NotificationsStudent(models.Mode... | 64 | 64 | 70 | 6 | 58 | mipertille/OpenEscola | core/models.py | Python | NotificationsStudent | NotificationsStudent | 137 | 143 | 137 | 137 | 176492bd7758ddcf1a481ec8d235b3b53654aef3 | bigcode/the-stack | train |
535b8c9b14e17799c0c3254f | train | class | class CustomUser(AbstractUser):
user_type_data = (
(1, 'HOD'),
(2, 'Staff'),
(3, 'Student')
)
user_type = models.CharField(default=1, choices=user_type_data, max_length=10)
| class CustomUser(AbstractUser):
| user_type_data = (
(1, 'HOD'),
(2, 'Staff'),
(3, 'Student')
)
user_type = models.CharField(default=1, choices=user_type_data, max_length=10)
| = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=255)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class CustomUser(AbstractUser):
| 64 | 64 | 57 | 6 | 58 | mipertille/OpenEscola | core/models.py | Python | CustomUser | CustomUser | 24 | 30 | 24 | 24 | 4234bec13548faca5300866de92d61ad8ad59167 | bigcode/the-stack | train |
9a5e77a595dab8cffe659201 | train | function | @receiver(post_save, sender=CustomUser)
def save_user_profile(sender, instance, **kwargs):
if instance.user_type == 1:
instance.admin.save()
if instance.user_type == 2:
instance.staffs.save()
if instance.user_type == 3:
instance.students.save()
| @receiver(post_save, sender=CustomUser)
def save_user_profile(sender, instance, **kwargs):
| if instance.user_type == 1:
instance.admin.save()
if instance.user_type == 2:
instance.staffs.save()
if instance.user_type == 3:
instance.students.save()
| 3:
Students.objects.create(
admin=instance,
course_id=Courses.objects.get(id=1),
session_year_id=SessionYear.objects.get(id=1),
profile_pic='',
)
@receiver(post_save, sender=CustomUser)
def save_user_profile(sender, instance, **kwar... | 64 | 64 | 64 | 21 | 43 | mipertille/OpenEscola | core/models.py | Python | save_user_profile | save_user_profile | 171 | 178 | 171 | 172 | 0cac496300535c6a8b0870f98905ac2256ab25a8 | bigcode/the-stack | train |
8317b81dbb183ce273b2b1aa | train | class | class SessionYear(models.Model):
id = models.AutoField(primary_key=True)
session_start_year = models.DateField()
session_end_year = models.DateField()
objects = models.Manager()
| class SessionYear(models.Model):
| id = models.AutoField(primary_key=True)
session_start_year = models.DateField()
session_end_year = models.DateField()
objects = models.Manager()
| from django.contrib.auth.models import AbstractUser, User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
# Create your models here.
class SessionYear(models.Model):
| 51 | 64 | 40 | 6 | 45 | mipertille/OpenEscola | core/models.py | Python | SessionYear | SessionYear | 9 | 13 | 9 | 9 | 62e019fad7dbf3df3083a3fffa6e0476f2faa13d | bigcode/the-stack | train |
9e9d6e42f15f8177d13c4a59 | train | class | class Students(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
gender = models.CharField(max_length=255)
profile_pic = models.FileField()
address = models.TextField()
course_id = models.ForeignKey(Courses, on_delete=models... | class Students(models.Model):
| id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
gender = models.CharField(max_length=255)
profile_pic = models.FileField()
address = models.TextField()
course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING)
session_year_... | = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
address = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class Students(models.Model):
| 64 | 64 | 128 | 5 | 59 | mipertille/OpenEscola | core/models.py | Python | Students | Students | 50 | 60 | 50 | 50 | 8016dc5a10fbf811e30e020b190be60f33d46446 | bigcode/the-stack | train |
2faa4515648c3c7ef5940087 | train | class | class NotificationsStaffs(models.Model):
id = models.AutoField(primary_key=True)
staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
message = models.TextField()
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now_add=True)
objects = models.Ma... | class NotificationsStaffs(models.Model):
| id = models.AutoField(primary_key=True)
staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
message = models.TextField()
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
| _key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
message = models.TextField()
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
class NotificationsStaffs(models.Model):
| 64 | 64 | 72 | 7 | 57 | mipertille/OpenEscola | core/models.py | Python | NotificationsStaffs | NotificationsStaffs | 146 | 152 | 146 | 146 | b2b8dccd93bd8c94e30c2151250f59cc3e689256 | bigcode/the-stack | train |
fa542109e303245ff686e75d | train | class | class FeedBackStaffs(models.Model):
id = models.AutoField(primary_key=True)
staffs_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.... | class FeedBackStaffs(models.Model):
| id = models.AutoField(primary_key=True)
staffs_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, ... | =models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class FeedBackStaffs(models.Model):
| 64 | 64 | 87 | 8 | 56 | mipertille/OpenEscola | core/models.py | Python | FeedBackStaffs | FeedBackStaffs | 127 | 134 | 127 | 127 | 114f0b874a9ac0fa996a51c389dac715b73cd311 | bigcode/the-stack | train |
1c19b96fcbf7f9899c80b9f8 | train | class | class Subject(models.Model):
id = models.AutoField(primary_key=True)
subject_name = models.CharField(max_length=255)
course_id = models.ForeignKey(Courses, on_delete=models.CASCADE, default=1)
staff_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
create_at = models.DateTimeField(default... | class Subject(models.Model):
| id = models.AutoField(primary_key=True)
subject_name = models.CharField(max_length=255)
course_id = models.ForeignKey(Courses, on_delete=models.CASCADE, default=1)
staff_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
create_at = models.DateTimeField(default=timezone.now, editable=False... | =models.DO_NOTHING)
session_year_id = models.ForeignKey(SessionYear, on_delete=models.CASCADE)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class Subject(models.Model):
| 64 | 64 | 99 | 5 | 59 | mipertille/OpenEscola | core/models.py | Python | Subject | Subject | 63 | 70 | 63 | 63 | ef419453daab97ea554bdb1ebc1faff10812dd6f | bigcode/the-stack | train |
da276d95d38500167c0b9a48 | train | class | class Staffs(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
address = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=F... | class Staffs(models.Model):
| id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
address = models.TextField()
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.M... | (primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
create_at = models.DateTimeField(default=timezone.now, editable=False)
update_at = models.DateTimeField(default=timezone.now, editable=False)
objects = models.Manager()
class Staffs(models.Model):
| 64 | 64 | 77 | 6 | 58 | mipertille/OpenEscola | core/models.py | Python | Staffs | Staffs | 41 | 47 | 41 | 41 | 85862473734e0bdda8444e705dcc9a0e2fcb0dab | bigcode/the-stack | train |
40d78714f537f9f4c094cb74 | train | function | def get_dependencies():
dep_file = path.join(HERE, 'requirements.in')
if not path.isfile(dep_file):
return []
with open(dep_file, encoding='utf-8') as f:
return f.readlines()
| def get_dependencies():
| dep_file = path.join(HERE, 'requirements.in')
if not path.isfile(dep_file):
return []
with open(dep_file, encoding='utf-8') as f:
return f.readlines()
| og_checks', 'php_fpm', '__about__.py')) as f:
exec(f.read(), ABOUT)
# Get the long description from the README file
with open(path.join(HERE, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
def get_dependencies():
| 64 | 64 | 48 | 4 | 60 | jfmyers9/integrations-core | php_fpm/setup.py | Python | get_dependencies | get_dependencies | 21 | 27 | 21 | 21 | fd55762dcd7054d08da86cea56ce80a8611cf4ec | bigcode/the-stack | train |
a7ec04eddeb43f0338648420 | train | function | def optimization(f, xy, tol, nmax) :
l = Log()
e = Error()
h = hessiana(f,[x,y])
j = jacobian_transpose(f,[x,y])
previous = xy
for n in range(nmax) :
hh = h(float(xy[0]), float(xy[1]))
jj = j(float(xy[0]), float(xy[1]))
L, U, _ = Matrix(hh).LUdecomposition... | def optimization(f, xy, tol, nmax) :
| l = Log()
e = Error()
h = hessiana(f,[x,y])
j = jacobian_transpose(f,[x,y])
previous = xy
for n in range(nmax) :
hh = h(float(xy[0]), float(xy[1]))
jj = j(float(xy[0]), float(xy[1]))
L, U, _ = Matrix(hh).LUdecomposition()
gauss = gauss_jor... | def optimization(f, xy, tol, nmax) :
| 12 | 86 | 289 | 12 | 0 | codinginbrazil/GA018 | report/code/nr-opt.py | Python | optimization | optimization | 1 | 33 | 1 | 1 | 9e817e48769a60e0fdb3fd3be35a89d803c82be7 | bigcode/the-stack | train |
1a11e8e552e7af53a3f80ff9 | train | function | def register_context(func):
def wrapper(self, *args, **kwargs):
return func(*args, **dict_merge(self.__options__, kwargs))
wrapper.__doc__ = func.__doc__
wrapper.__name__ = func.__name__
setattr(Context, func.__name__, wrapper)
return func
| def register_context(func):
| def wrapper(self, *args, **kwargs):
return func(*args, **dict_merge(self.__options__, kwargs))
wrapper.__doc__ = func.__doc__
wrapper.__name__ = func.__name__
setattr(Context, func.__name__, wrapper)
return func
| :
raise TypeError("a context manager expected, got %s" % other)
def __enter__(self):
raise NotImplementedError('global context')
def __exit__(self, exc_type, exc_val, exc_tb):
raise NotImplementedError('global context')
def register_context(func):
| 64 | 64 | 65 | 5 | 59 | cielavenir/sympy | py3k-sympy/sympy/polys/polycontext.py | Python | register_context | register_context | 53 | 62 | 53 | 53 | 21899bcb60412bc574f0fbb32eb21b03f877af67 | bigcode/the-stack | train |
553c74246c9508278934dfc3 | train | class | class Context(object):
__slots__ = ['__options__']
def __init__(self, dict=None, **options):
if dict is not None:
self.__options__ = dict_merget(dict, options)
else:
self.__options__ = options
def __getattribute__(self, name):
if name in __known_options__:
... | class Context(object):
| __slots__ = ['__options__']
def __init__(self, dict=None, **options):
if dict is not None:
self.__options__ = dict_merget(dict, options)
else:
self.__options__ = options
def __getattribute__(self, name):
if name in __known_options__:
try:
... | ussian', 'extension', 'field', 'greedy', 'symmetric'])
__global_options__ = []
__template__ = """\
def %(option)s(_%(option)s):
return Context(%(option)s=_%(option)s)
"""
for option in __known_options__:
exec(__template__ % { 'option': option })
class Context(object):
| 75 | 75 | 253 | 4 | 71 | cielavenir/sympy | py3k-sympy/sympy/polys/polycontext.py | Python | Context | Context | 18 | 51 | 18 | 19 | 7f386f4dc6267e5f36c08f3a0ef1eac26fa42f16 | bigcode/the-stack | train |
5db15a45f90373a8ec48066f | train | class | class Migration(migrations.Migration):
dependencies = [
('home', '0008_counter'),
]
operations = [
migrations.CreateModel(
name='PageHit',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| dependencies = [
('home', '0008_counter'),
]
operations = [
migrations.CreateModel(
name='PageHit',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('url', models.CharField(ma... | # Generated by Django 3.0.7 on 2021-05-27 12:49
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 108 | 7 | 30 | AntonBalmakov/MyResume- | my_resume/home/migrations/0009_auto_20210527_1549.py | Python | Migration | Migration | 6 | 24 | 6 | 7 | b64f3fb42171f9c90552bec498514bc0011c7388 | bigcode/the-stack | train |
74bda574546b8cce538e2c4b | train | class | @nottest
class ConnectTests(TestCase):
def testCacheStatusCanGetAToken(self):
server = Server(use_port = True)
command = connect.GetTokenCommand(server)
token = command.execute()
self.assertIsNotNone(token)
self.assertGreater(len(token), 10, "token lengt... | @nottest
class ConnectTests(TestCase):
| def testCacheStatusCanGetAToken(self):
server = Server(use_port = True)
command = connect.GetTokenCommand(server)
token = command.execute()
self.assertIsNotNone(token)
self.assertGreater(len(token), 10, "token length is too small")
def ... | from mock import Mock, patch
from agrc.caching.commands import connect
from agrc.caching.config import Server
from unittest import TestCase
from nose.tools import nottest
@nottest
class ConnectTests(TestCase):
| 47 | 64 | 165 | 9 | 37 | agrc/AutomatedCaching | tests/testConnect.py | Python | ConnectTests | ConnectTests | 7 | 28 | 7 | 8 | 382f1a879e2a17427562667401c9e8d2898ba170 | bigcode/the-stack | train |
1c559960b4339ce2f5288c5b | train | class | class PathPlanner():
def __init__(self, CP):
self.LP = LanePlanner()
self.last_cloudlog_t = 0
self.steer_rate_cost = CP.steerRateCost
self.setup_mpc()
self.solution_invalid_cnt = 0
self.lane_change_state = LaneChangeState.off
self.lane_change_direction = LaneChangeDirection.none
self... | class PathPlanner():
| def __init__(self, CP):
self.LP = LanePlanner()
self.last_cloudlog_t = 0
self.steer_rate_cost = CP.steerRateCost
self.setup_mpc()
self.solution_invalid_cnt = 0
self.lane_change_state = LaneChangeState.off
self.lane_change_direction = LaneChangeDirection.none
self.lane_change_timer = ... | State.laneChangeStarting: log.PathPlan.Desire.none,
LaneChangeState.laneChangeFinishing: log.PathPlan.Desire.none,
},
LaneChangeDirection.left: {
LaneChangeState.off: log.PathPlan.Desire.none,
LaneChangeState.preLaneChange: log.PathPlan.Desire.none,
LaneChangeState.laneChangeStarting: log.PathPlan.D... | 256 | 256 | 2,047 | 4 | 251 | l03ie/Gernby | selfdrive/controls/lib/pathplanner.py | Python | PathPlanner | PathPlanner | 47 | 221 | 47 | 47 | 3dcdf794db5fbdfe4f88bf334fef6dbaf97f214f | bigcode/the-stack | train |
73d67c3777f161c17447fa8f | train | function | def calc_states_after_delay(states, v_ego, steer_angle, curvature_factor, steer_ratio, delay):
states[0].x = v_ego * delay
states[0].psi = v_ego * curvature_factor * math.radians(steer_angle) / steer_ratio * delay
return states
| def calc_states_after_delay(states, v_ego, steer_angle, curvature_factor, steer_ratio, delay):
| states[0].x = v_ego * delay
states[0].psi = v_ego * curvature_factor * math.radians(steer_angle) / steer_ratio * delay
return states
| LaneChangeState.laneChangeStarting: log.PathPlan.Desire.laneChangeRight,
LaneChangeState.laneChangeFinishing: log.PathPlan.Desire.laneChangeRight,
},
}
def calc_states_after_delay(states, v_ego, steer_angle, curvature_factor, steer_ratio, delay):
| 64 | 64 | 67 | 22 | 42 | l03ie/Gernby | selfdrive/controls/lib/pathplanner.py | Python | calc_states_after_delay | calc_states_after_delay | 41 | 44 | 41 | 41 | d4c6ffa024425b0b1be697b1bf0d7a9cd1d34117 | bigcode/the-stack | train |
d06faa05db9ace629eda3cc9 | train | class | class NASNetSearchCell(nn.Module):
def __init__(self, space, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev, affine, track_running_stats):
super(NASNetSearchCell, self).__init__()
self.reduction = reduction
self.op_names = deepcopy(space)
if reduction_prev: self.preprocess0 = O... | class NASNetSearchCell(nn.Module):
| def __init__(self, space, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev, affine, track_running_stats):
super(NASNetSearchCell, self).__init__()
self.reduction = reduction
self.op_names = deepcopy(space)
if reduction_prev: self.preprocess0 = OPS['skip_connect'](C_prev_prev, C, 2... | (nn.Module):
def __init__(self, space, C, stride, affine, track_running_stats):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
for primitive in space:
op = OPS[primitive](C, C, stride, affine, track_running_stats)
self._ops.append(op)
def forward(self, x, weights, index):
... | 144 | 144 | 480 | 8 | 135 | liamcli/AutoDL-Projects | lib/models/cell_searchs/search_cells.py | Python | NASNetSearchCell | NASNetSearchCell | 154 | 193 | 154 | 155 | 98680767d921d45f48f355dd83ca06c97f97bd83 | bigcode/the-stack | train |
237d31e83c3fe64a4151eff1 | train | class | class NAS201SearchCell(nn.Module):
def __init__(self, C_in, C_out, stride, max_nodes, op_names, affine=False, track_running_stats=True):
super(NAS201SearchCell, self).__init__()
self.op_names = deepcopy(op_names)
self.edges = nn.ModuleDict()
self.max_nodes = max_nodes
self.in_dim = C_in
... | class NAS201SearchCell(nn.Module):
| def __init__(self, C_in, C_out, stride, max_nodes, op_names, affine=False, track_running_stats=True):
super(NAS201SearchCell, self).__init__()
self.op_names = deepcopy(op_names)
self.edges = nn.ModuleDict()
self.max_nodes = max_nodes
self.in_dim = C_in
self.out_dim = C_out
for i... | ##################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019 #
##################################################
import math, random, torch
import warnings
import torch.nn as nn
import torch.nn.functional as F
from copy import deepcopy
from ..cell_operations import OPS
# This m... | 88 | 256 | 1,317 | 8 | 79 | liamcli/AutoDL-Projects | lib/models/cell_searchs/search_cells.py | Python | NAS201SearchCell | NAS201SearchCell | 13 | 135 | 13 | 14 | ff1c0efd8746c7c0286349a04e8cc60de632370c | bigcode/the-stack | train |
8ea36e917e5d56053bdd5747 | train | class | class MixedOp(nn.Module):
def __init__(self, space, C, stride, affine, track_running_stats):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
for primitive in space:
op = OPS[primitive](C, C, stride, affine, track_running_stats)
self._ops.append(op)
def forward(self, x, weights,... | class MixedOp(nn.Module):
| def __init__(self, space, C, stride, affine, track_running_stats):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
for primitive in space:
op = OPS[primitive](C, C, stride, affine, track_running_stats)
self._ops.append(op)
def forward(self, x, weights, index):
#return sum(w ... | = '{:}<-{:}'.format(i, j)
op_index = self.op_names.index( op_name )
inter_nodes.append( self.edges[node_str][op_index]( nodes[j] ) )
nodes.append( sum(inter_nodes) )
return nodes[-1]
class MixedOp(nn.Module):
| 63 | 64 | 121 | 6 | 57 | liamcli/AutoDL-Projects | lib/models/cell_searchs/search_cells.py | Python | MixedOp | MixedOp | 139 | 150 | 139 | 140 | 46e5590ae639650cedfed8090c25a8446e90359e | bigcode/the-stack | train |
61cbbd0bb2edfd5a5e9f2d12 | train | function | @mock_ec2_deprecated
def test_instance_attribute_source_dest_check():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
# Default value is true
instance.sourceDestCheck.should.equal("true")
instance_attribute =... | @mock_ec2_deprecated
def test_instance_attribute_source_dest_check():
| conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID)
instance = reservation.instances[0]
# Default value is true
instance.sourceDestCheck.should.equal("true")
instance_attribute = instance.get_attribute("sourceDestCheck")
instance_attribute.shou... | (
"An error occurred (DryRunOperation) when calling the ModifyUserData operation: Request would have succeeded, but DryRun flag is set"
)
instance.modify_attribute("userData", "this is my user data")
instance_attribute = instance.get_attribute("userData")
instance_attribute.should.be.a(Instanc... | 101 | 101 | 337 | 15 | 86 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_attribute_source_dest_check | test_instance_attribute_source_dest_check | 902 | 942 | 902 | 903 | 5fe825cd00820bee1c70c6b6c2f7c1933ecd1524 | bigcode/the-stack | train |
198a9e159aaf7355ab88b463 | train | function | def add_servers(ami_id, count):
conn = boto.connect_ec2()
for index in range(count):
conn.run_instances(ami_id)
| def add_servers(ami_id, count):
| conn = boto.connect_ec2()
for index in range(count):
conn.run_instances(ami_id)
| import sure # noqa
from moto import mock_ec2_deprecated, mock_ec2, settings
from tests import EXAMPLE_AMI_ID
from tests.helpers import requires_boto_gte
decode_method = base64.decodebytes
################ Test Readme ###############
def add_servers(ami_id, count):
| 64 | 64 | 32 | 9 | 55 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | add_servers | add_servers | 26 | 29 | 26 | 26 | b2bff99696ed38e4428767bfd5901550b8a89ac7 | bigcode/the-stack | train |
aa1fef06a861758d5035a3ce | train | function | @mock_ec2
def test_describe_instance_status_with_instance_filter():
conn = boto3.client("ec2", region_name="us-west-1")
# We want to filter based on this one
reservation = conn.run_instances(ImageId=EXAMPLE_AMI_ID, MinCount=3, MaxCount=3)
instance1 = reservation["Instances"][0]
instance2 = reservat... | @mock_ec2
def test_describe_instance_status_with_instance_filter():
| conn = boto3.client("ec2", region_name="us-west-1")
# We want to filter based on this one
reservation = conn.run_instances(ImageId=EXAMPLE_AMI_ID, MinCount=3, MaxCount=3)
instance1 = reservation["Instances"][0]
instance2 = reservation["Instances"][1]
instance3 = reservation["Instances"][2]
... | _status with a bad id should raise an error
with pytest.raises(EC2ResponseError) as cm:
conn.get_all_instance_status(instance_ids=[instance.id, "i-1234abcd"])
cm.value.code.should.equal("InvalidInstanceID.NotFound")
cm.value.status.should.equal(400)
cm.value.request_id.should_not.be.none
@mock... | 211 | 211 | 704 | 15 | 196 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_describe_instance_status_with_instance_filter | test_describe_instance_status_with_instance_filter | 1,476 | 1,542 | 1,476 | 1,477 | 04902a88c7e29981e23e6382cc66cc248cb877ec | bigcode/the-stack | train |
7a58202103ca147c47ef3cca | train | function | @mock_ec2_deprecated
def test_user_data_with_run_instance():
user_data = b"some user data"
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, user_data=user_data)
instance = reservation.instances[0]
instance_attribute = instance.get_attribute("userData... | @mock_ec2_deprecated
def test_user_data_with_run_instance():
| user_data = b"some user data"
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances(EXAMPLE_AMI_ID, user_data=user_data)
instance = reservation.instances[0]
instance_attribute = instance.get_attribute("userData")
instance_attribute.should.be.a(InstanceAttribute)
... | instance.update()
instance.sourceDestCheck.should.equal("true")
instance_attribute = instance.get_attribute("sourceDestCheck")
instance_attribute.should.be.a(InstanceAttribute)
instance_attribute.get("sourceDestCheck").should.equal(True)
@mock_ec2_deprecated
def test_user_data_with_run_instance():
| 64 | 64 | 129 | 15 | 49 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_user_data_with_run_instance | test_user_data_with_run_instance | 945 | 956 | 945 | 946 | db40b956bc0ec0a612a9be51032dc254f106620e | bigcode/the-stack | train |
0e2f31c2a084b934220aafe9 | train | function | @mock_ec2_deprecated
def test_get_instances_filtering_by_vpc_id():
conn = boto.connect_vpc("the_key", "the_secret")
vpc1 = conn.create_vpc("10.0.0.0/16")
subnet1 = conn.create_subnet(vpc1.id, "10.0.0.0/27")
reservation1 = conn.run_instances(EXAMPLE_AMI_ID, min_count=1, subnet_id=subnet1.id)
instance... | @mock_ec2_deprecated
def test_get_instances_filtering_by_vpc_id():
| conn = boto.connect_vpc("the_key", "the_secret")
vpc1 = conn.create_vpc("10.0.0.0/16")
subnet1 = conn.create_subnet(vpc1.id, "10.0.0.0/27")
reservation1 = conn.run_instances(EXAMPLE_AMI_ID, min_count=1, subnet_id=subnet1.id)
instance1 = reservation1.instances[0]
vpc2 = conn.create_vpc("10.1.0.0... | false"}
)
source_dest_check_true = conn.get_all_reservations(
filters={"source-dest-check": "true"}
)
source_dest_check_false[0].instances.should.have.length_of(1)
source_dest_check_false[0].instances[0].id.should.equal(instance1.id)
source_dest_check_true[0].instances.should.have.leng... | 118 | 118 | 395 | 18 | 100 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_filtering_by_vpc_id | test_get_instances_filtering_by_vpc_id | 512 | 537 | 512 | 513 | d2c868e6d0b42532e63a70a599da49fcfe765736 | bigcode/the-stack | train |
d11a3b7f1ab7009b32ecd2db | train | function | @mock_ec2_deprecated
def test_get_instances_by_id():
conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=2)
instance1, instance2 = reservation.instances
reservations = conn.get_all_reservations(instance_ids=[instance1.id])
reservations.should.have.length_of(1)
r... | @mock_ec2_deprecated
def test_get_instances_by_id():
| conn = boto.connect_ec2()
reservation = conn.run_instances(EXAMPLE_AMI_ID, min_count=2)
instance1, instance2 = reservation.instances
reservations = conn.get_all_reservations(instance_ids=[instance1.id])
reservations.should.have.length_of(1)
reservation = reservations[0]
reservation.instance... | (instance.id)
# can do due to freeze_time decorator.
v.attach_data.attach_time.should.equal(instance.launch_time)
# can do due to freeze_time decorator.
v.create_time.should.equal(instance.launch_time)
v.region.name.should.equal(instance.region.name)
v.status.should.equal... | 78 | 78 | 260 | 14 | 64 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_get_instances_by_id | test_get_instances_by_id | 267 | 291 | 267 | 268 | e4f56f6e3294fbd1df9b910f24d3d62dafb560d0 | bigcode/the-stack | train |
adf5587e8cb09c0fc35cdd55 | train | function | @mock_ec2
def test_run_instance_with_block_device_mappings_missing_ebs():
ec2_client = boto3.client("ec2", region_name="us-east-1")
kwargs = {
"MinCount": 1,
"MaxCount": 1,
"ImageId": EXAMPLE_AMI_ID,
"KeyName": "the_key",
"InstanceType": "t1.micro",
"BlockDeviceM... | @mock_ec2
def test_run_instance_with_block_device_mappings_missing_ebs():
| ec2_client = boto3.client("ec2", region_name="us-east-1")
kwargs = {
"MinCount": 1,
"MaxCount": 1,
"ImageId": EXAMPLE_AMI_ID,
"KeyName": "the_key",
"InstanceType": "t1.micro",
"BlockDeviceMappings": [{"DeviceName": "/dev/sda2"}],
}
with pytest.raises(Clie... | Mappings"][0][
"Ebs"
]
volumes = ec2_client.describe_volumes(VolumeIds=[volume["VolumeId"]])
volumes["Volumes"][0]["Size"].should.equal(50)
@mock_ec2
def test_run_instance_with_block_device_mappings_missing_ebs():
| 64 | 64 | 184 | 19 | 45 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_block_device_mappings_missing_ebs | test_run_instance_with_block_device_mappings_missing_ebs | 1,339 | 1,358 | 1,339 | 1,340 | ada0e84b290679800b06b4b8080dd877ac40d193 | bigcode/the-stack | train |
484a5a84cb1c03b9b81a5837 | train | function | @freeze_time("2014-01-01 05:00:00")
@mock_ec2_deprecated
def test_instance_launch_and_terminate():
conn = boto.ec2.connect_to_region("us-east-1")
with pytest.raises(EC2ResponseError) as ex:
reservation = conn.run_instances(EXAMPLE_AMI_ID, dry_run=True)
ex.value.error_code.should.equal("DryRunOperat... | @freeze_time("2014-01-01 05:00:00")
@mock_ec2_deprecated
def test_instance_launch_and_terminate():
| conn = boto.ec2.connect_to_region("us-east-1")
with pytest.raises(EC2ResponseError) as ex:
reservation = conn.run_instances(EXAMPLE_AMI_ID, dry_run=True)
ex.value.error_code.should.equal("DryRunOperation")
ex.value.status.should.equal(400)
ex.value.message.should.equal(
"An error oc... |
################ Test Readme ###############
def add_servers(ami_id, count):
conn = boto.connect_ec2()
for index in range(count):
conn.run_instances(ami_id)
@mock_ec2_deprecated
def test_add_servers():
add_servers(EXAMPLE_AMI_ID, 2)
conn = boto.connect_ec2()
reservations = conn.get_all_... | 153 | 153 | 512 | 32 | 120 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_instance_launch_and_terminate | test_instance_launch_and_terminate | 46 | 98 | 46 | 48 | 2daf7e21fe1511d3b2e130c52b55cda6f463335e | bigcode/the-stack | train |
05e13f485422d9a960c44752 | train | function | @mock_ec2
def test_run_instance_mapped_public_ipv4():
client = boto3.client("ec2", region_name="eu-central-1")
vpc_cidr = ipaddress.ip_network("192.168.42.0/24")
subnet_cidr = ipaddress.ip_network("192.168.42.0/25")
resp = client.create_vpc(
CidrBlock=str(vpc_cidr),
AmazonProvidedIpv6C... | @mock_ec2
def test_run_instance_mapped_public_ipv4():
| client = boto3.client("ec2", region_name="eu-central-1")
vpc_cidr = ipaddress.ip_network("192.168.42.0/24")
subnet_cidr = ipaddress.ip_network("192.168.42.0/25")
resp = client.create_vpc(
CidrBlock=str(vpc_cidr),
AmazonProvidedIpv6CidrBlock=False,
DryRun=False,
Instance... | 1,
MinCount=1,
SubnetId=subnet_id,
PrivateIpAddress="192.168.42.5",
)
instance = resp["Instances"][0]
instance["SubnetId"].should.equal(subnet_id)
instance["PrivateIpAddress"].should.equal("192.168.42.5")
@mock_ec2
def test_run_instance_mapped_public_ipv4():
| 85 | 85 | 286 | 15 | 70 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_mapped_public_ipv4 | test_run_instance_mapped_public_ipv4 | 1,083 | 1,111 | 1,083 | 1,084 | d694c99751f7818562b2774dd2ddb01139108358 | bigcode/the-stack | train |
ba5b15573c4f2cb244eb63f9 | train | function | @mock_ec2_deprecated
def test_run_instance_with_security_group_name():
conn = boto.connect_ec2("the_key", "the_secret")
with pytest.raises(EC2ResponseError) as ex:
group = conn.create_security_group("group1", "some description", dry_run=True)
ex.value.error_code.should.equal("DryRunOperation")
... | @mock_ec2_deprecated
def test_run_instance_with_security_group_name():
| conn = boto.connect_ec2("the_key", "the_secret")
with pytest.raises(EC2ResponseError) as ex:
group = conn.create_security_group("group1", "some description", dry_run=True)
ex.value.error_code.should.equal("DryRunOperation")
ex.value.status.should.equal(400)
ex.value.message.should.equal(
... | .a(InstanceAttribute)
retrieved_user_data = instance_attribute.get("userData").encode("utf-8")
decoded_user_data = decode_method(retrieved_user_data)
decoded_user_data.should.equal(b"some user data")
@mock_ec2_deprecated
def test_run_instance_with_security_group_name():
| 64 | 64 | 189 | 16 | 48 | mhihasan/moto | tests/test_ec2/test_instances.py | Python | test_run_instance_with_security_group_name | test_run_instance_with_security_group_name | 959 | 977 | 959 | 960 | 3869b389b36f259db9beebeca33d5d5cec060870 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.