before stringlengths 0 955k | after stringlengths 0 877k | repo stringlengths 1 74 | type stringclasses 1
value |
|---|---|---|---|
def _malloc(self, size):
i = bisect.bisect_left(self._lengths, size)
if i == len(self._lengths):
<DeepExtract>
mask = mmap.PAGESIZE - 1
length = max(self._size, size) + mask & ~mask
</DeepExtract>
self._size *= 2
info('allocating a new mmap of length %d', length)
arena = ... | def _malloc(self, size):
i = bisect.bisect_left(self._lengths, size)
if i == len(self._lengths):
mask = mmap.PAGESIZE - 1
length = max(self._size, size) + mask & ~mask
self._size *= 2
info('allocating a new mmap of length %d', length)
arena = Arena(length)
self._a... | 3DFasterRCNN_LungNoduleDetector | positive |
def build_temp_dir(prefix='test-attributecode-'):
"""
Create and return a new unique empty directory created in base_dir.
"""
location = tempfile.mkdtemp(prefix=prefix)
<DeepExtract>
if not os.path.exists(location):
os.makedirs(location)
os.chmod(location, stat.S_IRWXU | stat.S_IRWXG... | def build_temp_dir(prefix='test-attributecode-'):
"""
Create and return a new unique empty directory created in base_dir.
"""
location = tempfile.mkdtemp(prefix=prefix)
if not os.path.exists(location):
os.makedirs(location)
os.chmod(location, stat.S_IRWXU | stat.S_IRWXG | stat.S_IROT... | aboutcode-toolkit | positive |
def slot_tabview_change(self, index):
if index not in (0, 1):
return
status_prev: str = self.view_status_label.text()
if index == 0:
<DeepExtract>
self.view_status_label.setText(self.view_status_label_analysis_cache)
</DeepExtract>
self.view_status_label_rulegen_cache = status_prev
... | def slot_tabview_change(self, index):
if index not in (0, 1):
return
status_prev: str = self.view_status_label.text()
if index == 0:
self.view_status_label.setText(self.view_status_label_analysis_cache)
self.view_status_label_rulegen_cache = status_prev
self.view_reset_button... | capa | positive |
def read_input():
ncases = int(input())
for case in range(1, ncases + 1):
n = int(input())
way = input()
<DeepExtract>
if way[0] == way[-1]:
if way[0] == 'E':
for (i, char) in enumerate(way):
if way[i] == way[i + 1] and way[i] == 'S':
... | def read_input():
ncases = int(input())
for case in range(1, ncases + 1):
n = int(input())
way = input()
if way[0] == way[-1]:
if way[0] == 'E':
for (i, char) in enumerate(way):
if way[i] == way[i + 1] and way[i] == 'S':
... | algorithms | positive |
def _batch_action(self):
async def batch_action(settings: ModelView.schemes.BatchSettings, user: ModelView.schemes.User=Security(utils.authorization.auth_dependency, scopes=self.scopes['batch_action'])):
<DeepExtract>
if settings.command in self.custom_commands:
query = self.custom_commands[set... | def _batch_action(self):
async def batch_action(settings: ModelView.schemes.BatchSettings, user: ModelView.schemes.User=Security(utils.authorization.auth_dependency, scopes=self.scopes['batch_action'])):
if settings.command in self.custom_commands:
query = self.custom_commands[settings.command]... | bitcart | positive |
def __init__(self, parameter):
"""
:param parameter: the parts of a tplarg.
"""
<DeepExtract>
sep = '|'
parameters = []
cur = 0
for (s, e) in findMatchingBraces(parameter):
par = parameter[cur:s].split(sep)
if par:
if parameters:
parameters... | def __init__(self, parameter):
"""
:param parameter: the parts of a tplarg.
"""
sep = '|'
parameters = []
cur = 0
for (s, e) in findMatchingBraces(parameter):
par = parameter[cur:s].split(sep)
if par:
if parameters:
parameters[-1] += par[0]... | DistillBERT | positive |
def unpack_directory(data):
<DeepExtract>
header = struct_unpack(HEADER_FORMAT, data)[0]
</DeepExtract>
numTables = header['numTables']
data = data[HEADER_SIZE:]
directory = []
for index in range(numTables):
<DeepExtract>
(keys, format_string) = _struct_get_format(DIRECTORY_FORMAT)
s... | def unpack_directory(data):
header = struct_unpack(HEADER_FORMAT, data)[0]
numTables = header['numTables']
data = data[HEADER_SIZE:]
directory = []
for index in range(numTables):
(keys, format_string) = _struct_get_format(DIRECTORY_FORMAT)
size = struct.calcsize(format_string)
... | django-gateone | positive |
def format_json(lib):
import json
summary = lib.summarize()
non_users = []
for u in summary['non_users']:
non_users.append(u.to_dict())
non_users.sort(key=lambda x: x['path'])
users = []
for (u, usage) in summary['users']:
symbols = [s.to_dict() for s in usage]
symbol... | def format_json(lib):
import json
summary = lib.summarize()
non_users = []
for u in summary['non_users']:
non_users.append(u.to_dict())
non_users.sort(key=lambda x: x['path'])
users = []
for (u, usage) in summary['users']:
symbols = [s.to_dict() for s in usage]
symbol... | barbieri-playground | positive |
def test_delete_question_with_essay_question(self):
EssayQuestion.objects.create(question_id=1, assignment=Assignment.objects.get(assignment_id=1), title='Evolvers', description='Write an essay about the Evolvers.')
kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
<DeepExtract>
client = Client()
cli... | def test_delete_question_with_essay_question(self):
EssayQuestion.objects.create(question_id=1, assignment=Assignment.objects.get(assignment_id=1), title='Evolvers', description='Write an essay about the Evolvers.')
kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
client = Client()
client.login(user... | academicstoday-django | positive |
def findPathsUtil(maze, m, n, i, j, path, indx):
global allPaths
global storePaths
if i == m - 1:
for k in range(j, n):
path[indx + k - j] = maze[i][k]
storePaths += ''.join(path) + '|'
allPaths.append(path)
return
if j == n - 1:
for k in range(i, m):
... | def findPathsUtil(maze, m, n, i, j, path, indx):
global allPaths
global storePaths
if i == m - 1:
for k in range(j, n):
path[indx + k - j] = maze[i][k]
storePaths += ''.join(path) + '|'
allPaths.append(path)
return
if j == n - 1:
for k in range(i, m):
... | Competitive-Coding-Platforms | positive |
@pytest.mark.parametrize('n, shape, grid', [([0], (1, 1, 1), (3, 4, 1)), ([1, 14], (10, 20, 30), (3, 1, 5)), ([14, 14, 14], (10, 20, 30), (1, 4, 5))])
def test_getDiscretisation_bools(n, shape, grid):
<DeepExtract>
coords = np.concatenate([np.linspace(0, s, len(n)).reshape(-1, 1) for s in shape], axis=1)
specie... | @pytest.mark.parametrize('n, shape, grid', [([0], (1, 1, 1), (3, 4, 1)), ([1, 14], (10, 20, 30), (3, 1, 5)), ([14, 14, 14], (10, 20, 30), (1, 4, 5))])
def test_getDiscretisation_bools(n, shape, grid):
coords = np.concatenate([np.linspace(0, s, len(n)).reshape(-1, 1) for s in shape], axis=1)
species = np.array(n... | diffsims | positive |
def start_lock_delay(self):
"""
Setup the lock delay timer based on user prefs - if there is
no delay, or if idle locking isn't enabled, we run the callback
immediately, or simply return, respectively.
"""
if not settings.get_idle_lock_enabled():
return
if not utils.u... | def start_lock_delay(self):
"""
Setup the lock delay timer based on user prefs - if there is
no delay, or if idle locking isn't enabled, we run the callback
immediately, or simply return, respectively.
"""
if not settings.get_idle_lock_enabled():
return
if not utils.u... | cinnamon-screensaver | positive |
def __init__(self, data):
"""
Initialise the DataHfProvider class with the `data` being a supported
data container (currently python dictionary or HDF5 file).
Let `nf` denote the number of Fock spin orbitals (i.e. the sum of both
the alpha and the beta orbitals) and `nb` the number o... | def __init__(self, data):
"""
Initialise the DataHfProvider class with the `data` being a supported
data container (currently python dictionary or HDF5 file).
Let `nf` denote the number of Fock spin orbitals (i.e. the sum of both
the alpha and the beta orbitals) and `nb` the number o... | adcc | positive |
def dpMain(*args):
""" Main function.
Check existen nodes and call the scripted function.
"""
callAction = False
<DeepExtract>
selList = cmds.ls(selection=True)
if selList:
for item in selList:
if self.dpCheckAllGrp(item):
self.allGrp = item
... | def dpMain(*args):
""" Main function.
Check existen nodes and call the scripted function.
"""
callAction = False
selList = cmds.ls(selection=True)
if selList:
for item in selList:
if self.dpCheckAllGrp(item):
self.allGrp = item
for item in ... | dpAutoRigSystem | positive |
def _core_network(self, l_p, h_p, x_t):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
h_p - 256x1 vector
Returns:
h_t, 256x1 vector
"""
<DeepExtract>
sensor_output = self._refined_glimpse_sensor(x_t, l_p)
sensor_output = T.fl... | def _core_network(self, l_p, h_p, x_t):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
h_p - 256x1 vector
Returns:
h_t, 256x1 vector
"""
sensor_output = self._refined_glimpse_sensor(x_t, l_p)
sensor_output = T.flatten(sensor_o... | deepy | positive |
def check_device_state(self, device_id, state_name):
<DeepExtract>
devices = requests.get('https://{host_uri}/{device_list_endpoint}'.format(host_uri=self.HOST_URI, device_list_endpoint=self.DEVICE_LIST_ENDPOINT), headers={'MyQApplicationId': self.APP_ID, 'SecurityToken': self.myq_security_token})
devices = dev... | def check_device_state(self, device_id, state_name):
devices = requests.get('https://{host_uri}/{device_list_endpoint}'.format(host_uri=self.HOST_URI, device_list_endpoint=self.DEVICE_LIST_ENDPOINT), headers={'MyQApplicationId': self.APP_ID, 'SecurityToken': self.myq_security_token})
devices = devices.json()['D... | Alexa-MyQGarage | positive |
def test():
<DeepExtract>
cfg = {'out_planes': [200, 400, 800], 'num_blocks': [4, 8, 4], 'groups': 2}
net = ShuffleNet(cfg)
</DeepExtract>
x = torch.randn(1, 3, 32, 32)
y = net(x)
print(y) | def test():
cfg = {'out_planes': [200, 400, 800], 'num_blocks': [4, 8, 4], 'groups': 2}
net = ShuffleNet(cfg)
x = torch.randn(1, 3, 32, 32)
y = net(x)
print(y) | dhp | positive |
def next(self):
"""
Default implementation for built-in backtrader method.
Defines one step environment routine;
Handles order execution logic according to action received.
Note that orders can only be submitted for data_lines in action_space (assets).
`self.action` attr. is ... | def next(self):
"""
Default implementation for built-in backtrader method.
Defines one step environment routine;
Handles order execution logic according to action received.
Note that orders can only be submitted for data_lines in action_space (assets).
`self.action` attr. is ... | btgym | positive |
def tree_is_perfect_match(self):
"""
Returns True if self.trees is a singleton that perfectly matches
the words in the utterances (with certain simplifactions to each
to accommodate different notation and information).
"""
if len(self.trees) != 1:
return False
<DeepExtrac... | def tree_is_perfect_match(self):
"""
Returns True if self.trees is a singleton that perfectly matches
the words in the utterances (with certain simplifactions to each
to accommodate different notation and information).
"""
if len(self.trees) != 1:
return False
tree_le... | dialog-processing | positive |
def mergeSort(alist):
length = len(alist)
mid = length // 2
if length > 1:
left = alist[:mid]
right = alist[mid:]
<DeepExtract>
length = len(left)
mid = length // 2
if length > 1:
left = left[:mid]
right = left[mid:]
mergeSort(left)... | def mergeSort(alist):
length = len(alist)
mid = length // 2
if length > 1:
left = alist[:mid]
right = alist[mid:]
length = len(left)
mid = length // 2
if length > 1:
left = left[:mid]
right = left[mid:]
mergeSort(left)
m... | 168206 | positive |
def test_epoch_end(self, outputs: List[Any]) -> None:
averaged_epoch_loss = sum([output['loss'] for output in outputs]) / len(outputs)
self.log(f'{self.TEST_METRICS_PREFIX}_loss', averaged_epoch_loss, on_step=False, prog_bar=True, on_epoch=True)
<DeepExtract>
metrics = self._head.get_metrics(True)
</DeepExt... | def test_epoch_end(self, outputs: List[Any]) -> None:
averaged_epoch_loss = sum([output['loss'] for output in outputs]) / len(outputs)
self.log(f'{self.TEST_METRICS_PREFIX}_loss', averaged_epoch_loss, on_step=False, prog_bar=True, on_epoch=True)
metrics = self._head.get_metrics(True)
for (key, val) in m... | biome-text | positive |
@cache_page(1800)
def by_arch(request):
<DeepExtract>
qs = Package.objects.select_related().values('arch__name', 'repo__name').annotate(count=Count('pk'), csize=Sum('compressed_size'), isize=Sum('installed_size'), flagged=Count('flag_date')).order_by()
arches = Arch.objects.values_list('name', flat=True)
re... | @cache_page(1800)
def by_arch(request):
qs = Package.objects.select_related().values('arch__name', 'repo__name').annotate(count=Count('pk'), csize=Sum('compressed_size'), isize=Sum('installed_size'), flagged=Count('flag_date')).order_by()
arches = Arch.objects.values_list('name', flat=True)
repos = Repo.obj... | archweb | positive |
def enum_host_info(self):
<DeepExtract>
try:
ldapConnection = ldap_impacket.LDAPConnection('ldap://%s' % self.host)
resp = ldapConnection.search(scope=ldapasn1_impacket.Scope('baseObject'), attributes=['defaultNamingContext', 'dnsHostName'], sizeLimit=0)
for item in resp:
if isin... | def enum_host_info(self):
try:
ldapConnection = ldap_impacket.LDAPConnection('ldap://%s' % self.host)
resp = ldapConnection.search(scope=ldapasn1_impacket.Scope('baseObject'), attributes=['defaultNamingContext', 'dnsHostName'], sizeLimit=0)
for item in resp:
if isinstance(item, l... | CrackMapExec | positive |
def run(self):
self.buffer += 'digraph G {'
self.buffer += DOT_STYLE
if isinstance(self.g, DiGraph):
for edge in self.g.edges:
<DeepExtract>
labels = ''
if edge.kind is not None:
data = '' if edge.data is None else str(edge.data)
labels = '[lab... | def run(self):
self.buffer += 'digraph G {'
self.buffer += DOT_STYLE
if isinstance(self.g, DiGraph):
for edge in self.g.edges:
labels = ''
if edge.kind is not None:
data = '' if edge.data is None else str(edge.data)
labels = '[label="%s - %s"]'... | equip | positive |
@force_fp32(apply_to='cls_score')
def _merge_score(self, cls_score):
"""
Do softmax in each bin. Decay the score of normal classes
with the score of fg.
From v1.
"""
num_proposals = cls_score.shape[0]
<DeepExtract>
new_preds = []
num_bins = self.pred_slice.shape[0]
fo... | @force_fp32(apply_to='cls_score')
def _merge_score(self, cls_score):
"""
Do softmax in each bin. Decay the score of normal classes
with the score of fg.
From v1.
"""
num_proposals = cls_score.shape[0]
new_preds = []
num_bins = self.pred_slice.shape[0]
for i in range(n... | BalancedGroupSoftmax | positive |
def __init__(self, kvs, delete_on_exit=True):
<DeepExtract>
(fd, fname) = tempfile.mkstemp('.mat', prefix='ao_', dir=dir)
os.close(fd)
if contents is not None:
make_file(fname, contents)
self.fname = os.path.abspath(fname)
</DeepExtract>
self.delete_on_exit = delete_on_exit
scipy.io.save... | def __init__(self, kvs, delete_on_exit=True):
(fd, fname) = tempfile.mkstemp('.mat', prefix='ao_', dir=dir)
os.close(fd)
if contents is not None:
make_file(fname, contents)
self.fname = os.path.abspath(fname)
self.delete_on_exit = delete_on_exit
scipy.io.savemat(self.fname, kvs) | avobjects | positive |
def train_step(self, data):
"""One training step
Arguments:
data {dict of data} -- required keys and values:
'X' {LongTensor [batch_size, history_len, max_x_sent_len]} -- token ids of sentences
'X_floor' {LongTensor [batch_size, history_len]} -- floors of sentenc... | def train_step(self, data):
"""One training step
Arguments:
data {dict of data} -- required keys and values:
'X' {LongTensor [batch_size, history_len, max_x_sent_len]} -- token ids of sentences
'X_floor' {LongTensor [batch_size, history_len]} -- floors of sentenc... | dialog-processing | positive |
def metadata_action(args: argparse.Namespace) -> int:
try:
r = acd_client.get_metadata(args.node, args.assets)
<DeepExtract>
print(json.dumps(r, indent=4, sort_keys=True))
</DeepExtract>
except RequestError as e:
print(e)
return INVALID_ARG_RETVAL | def metadata_action(args: argparse.Namespace) -> int:
try:
r = acd_client.get_metadata(args.node, args.assets)
print(json.dumps(r, indent=4, sort_keys=True))
except RequestError as e:
print(e)
return INVALID_ARG_RETVAL | acd_cli | positive |
def scalar_jacfunc(vs, obj, obj_scalar, free_variables):
if not hasattr(scalar_jacfunc, 'vs'):
scalar_jacfunc.vs = vs * 0 + 1e+16
if np.max(np.abs(vs - scalar_jacfunc.vs)) == 0:
return scalar_jacfunc.J
<DeepExtract>
cur = 0
changed = False
for (idx, freevar) in enumerate(free_variabl... | def scalar_jacfunc(vs, obj, obj_scalar, free_variables):
if not hasattr(scalar_jacfunc, 'vs'):
scalar_jacfunc.vs = vs * 0 + 1e+16
if np.max(np.abs(vs - scalar_jacfunc.vs)) == 0:
return scalar_jacfunc.J
cur = 0
changed = False
for (idx, freevar) in enumerate(free_variables):
s... | chumpy | positive |
def dispatch_admin_message(self, msg):
"""Dispatches a message originating from an admin to all handlers."""
if msg.command == 'PRIVMSG':
<DeepExtract>
pass
</DeepExtract>
if self.is_command(msg):
<DeepExtract>
cmd_name = msg.params[-1].split(' ')[0]
cmd_name = cmd_name.s... | def dispatch_admin_message(self, msg):
"""Dispatches a message originating from an admin to all handlers."""
if msg.command == 'PRIVMSG':
pass
if self.is_command(msg):
cmd_name = msg.params[-1].split(' ')[0]
cmd_name = cmd_name.strip(self.get_command_prefix())
... | botnet | positive |
def _init_modules(self):
assert cfg.RESNETS.FREEZE_AT in [0, 2, 3, 4, 5]
assert cfg.RESNETS.FREEZE_AT <= self.convX
for i in range(1, cfg.RESNETS.FREEZE_AT + 1):
<DeepExtract>
for p in getattr(self, 'res%d' % i).parameters():
p.requires_grad = False
</DeepExtract>
self.apply(lambda m... | def _init_modules(self):
assert cfg.RESNETS.FREEZE_AT in [0, 2, 3, 4, 5]
assert cfg.RESNETS.FREEZE_AT <= self.convX
for i in range(1, cfg.RESNETS.FREEZE_AT + 1):
for p in getattr(self, 'res%d' % i).parameters():
p.requires_grad = False
self.apply(lambda m: freeze_params(m) if isinsta... | DIoU-pytorch-detectron | positive |
def forward_train(self):
<DeepExtract>
self.d0 = self.net.forward(self.var_ref, self.var_p0, retPerLayer=retPerLayer)
</DeepExtract>
<DeepExtract>
self.d1 = self.net.forward(self.var_ref, self.var_p1, retPerLayer=retPerLayer)
</DeepExtract>
<DeepExtract>
d1_lt_d0 = (self.d1 < self.d0).cpu().data.numpy().fla... | def forward_train(self):
self.d0 = self.net.forward(self.var_ref, self.var_p0, retPerLayer=retPerLayer)
self.d1 = self.net.forward(self.var_ref, self.var_p1, retPerLayer=retPerLayer)
d1_lt_d0 = (self.d1 < self.d0).cpu().data.numpy().flatten()
judge_per = self.input_judge.cpu().numpy().flatten()
self... | DASR | positive |
def load_by_order(self, path):
hdf5_dict = read_hdf5(path)
assigned_params = 0
kernel_idx = 0
sigma_idx = 0
mu_idx = 0
gamma_idx = 0
beta_idx = 0
for (k, v) in self.state.model.named_parameters():
if k in hdf5_dict:
value = hdf5_dict[k]
else:
if 'c... | def load_by_order(self, path):
hdf5_dict = read_hdf5(path)
assigned_params = 0
kernel_idx = 0
sigma_idx = 0
mu_idx = 0
gamma_idx = 0
beta_idx = 0
for (k, v) in self.state.model.named_parameters():
if k in hdf5_dict:
value = hdf5_dict[k]
else:
if 'c... | AOFP | positive |
def forward(self, output, mask, ind, rotbin, rotres):
pred = _tranpose_and_gather_feat(output, ind)
<DeepExtract>
pred = pred.view(-1, 8)
rotbin = rotbin.view(-1, 2)
rotres = rotres.view(-1, 2)
mask = mask.view(-1, 1)
loss_bin1 = compute_bin_loss(pred[:, 0:2], rotbin[:, 0], mask)
loss_bin2 =... | def forward(self, output, mask, ind, rotbin, rotres):
pred = _tranpose_and_gather_feat(output, ind)
pred = pred.view(-1, 8)
rotbin = rotbin.view(-1, 2)
rotres = rotres.view(-1, 2)
mask = mask.view(-1, 1)
loss_bin1 = compute_bin_loss(pred[:, 0:2], rotbin[:, 0], mask)
loss_bin2 = compute_bin_l... | centerNet-deep-sort | positive |
def test_clean(self):
<DeepExtract>
self.project.item.allow_overlapping = False
self.project.item.save()
</DeepExtract>
self.spans.clean(self.project.item)
self.assertEqual(len(self.spans), 2) | def test_clean(self):
self.project.item.allow_overlapping = False
self.project.item.save()
self.spans.clean(self.project.item)
self.assertEqual(len(self.spans), 2) | doccano | positive |
def put(self, put_data, resource=None, id=None):
url = '%s://%s/%s' % (self._module.params['nitro_protocol'], self._module.params['nsip'], self.api_path)
if resource is not None:
url = '%s/%s' % (url, resource)
if id is not None:
url = '%s/%s' % (url, id)
data = self._module.jsonify(put_... | def put(self, put_data, resource=None, id=None):
url = '%s://%s/%s' % (self._module.params['nitro_protocol'], self._module.params['nsip'], self.api_path)
if resource is not None:
url = '%s/%s' % (url, resource)
if id is not None:
url = '%s/%s' % (url, id)
data = self._module.jsonify(put_... | citrix-adc-ansible-modules | positive |
def forward(self, x):
<DeepExtract>
kernel_size_effective = self.kernel_size + (self.kernel_size - 1) * (self.dilation - 1)
pad_total = kernel_size_effective - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
padded_inputs = F.pad(x, (pad_beg, pad_end, pad_beg, pad_end))
x_pad = padded_i... | def forward(self, x):
kernel_size_effective = self.kernel_size + (self.kernel_size - 1) * (self.dilation - 1)
pad_total = kernel_size_effective - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
padded_inputs = F.pad(x, (pad_beg, pad_end, pad_beg, pad_end))
x_pad = padded_inputs
if s... | CVPR2020_MANet | positive |
def accuracy(predict, label, pre_pro):
predict = np.array(predict)
label = np.array(label)
if len(predict) == 0:
return None
if pre_pro == 'sm':
<DeepExtract>
orig_shape = predict.shape
if len(predict.shape) > 1:
exp_minmax = lambda x: np.exp(predict - np.max(predict)... | def accuracy(predict, label, pre_pro):
predict = np.array(predict)
label = np.array(label)
if len(predict) == 0:
return None
if pre_pro == 'sm':
orig_shape = predict.shape
if len(predict.shape) > 1:
exp_minmax = lambda x: np.exp(predict - np.max(predict))
... | Deep-RNN-Framework | positive |
def test(self):
benji_obj = self.benji_open()
store = BenjiStore(benji_obj)
addr = ('127.0.0.1', self.SERVER_PORT)
read_only = False
discard_changes = False
self.nbd_server = NbdServer(addr, store, read_only, discard_changes)
logger.info('Starting to serve NBD on %s:%s' % (addr[0], addr[1]))... | def test(self):
benji_obj = self.benji_open()
store = BenjiStore(benji_obj)
addr = ('127.0.0.1', self.SERVER_PORT)
read_only = False
discard_changes = False
self.nbd_server = NbdServer(addr, store, read_only, discard_changes)
logger.info('Starting to serve NBD on %s:%s' % (addr[0], addr[1]))... | benji | positive |
def one_hot(x, num_classes, *, dtype=None, axis=-1):
"""One-hot encodes the given indicies.
Each index in the input ``x`` is encoded as a vector of zeros of length
``num_classes`` with the element at ``index`` set to one::
>>> import jax.numpy as jnp
>>> one_hot(jnp.array([0, 1, 2]), 3)
Array([[1.... | def one_hot(x, num_classes, *, dtype=None, axis=-1):
"""One-hot encodes the given indicies.
Each index in the input ``x`` is encoded as a vector of zeros of length
``num_classes`` with the element at ``index`` set to one::
>>> import jax.numpy as jnp
>>> one_hot(jnp.array([0, 1, 2]), 3)
Array([[1.... | BrainPy | positive |
def got_ops_callback(self, ops):
for (op, blockheader, block_index, txs) in ops:
if op == 'add':
<DeepExtract>
with self._lock:
self.set_last_block_index(block_index)
for tx in txs:
self._process_confirmed_tx(tx, blockheader, block_index)
</Dee... | def got_ops_callback(self, ops):
for (op, blockheader, block_index, txs) in ops:
if op == 'add':
with self._lock:
self.set_last_block_index(block_index)
for tx in txs:
self._process_confirmed_tx(tx, blockheader, block_index)
elif op == ... | dashman | positive |
def autojoin_cb(data, buffer, args):
"""Old behaviour: doesn't save empty channel list"""
"In fact should also save open buffers with a /part'ed channel"
"But I can't believe somebody would want that behaviour"
<DeepExtract>
items = {}
infolist = w.infolist_get('irc_server', '', '')
while w.info... | def autojoin_cb(data, buffer, args):
"""Old behaviour: doesn't save empty channel list"""
"In fact should also save open buffers with a /part'ed channel"
"But I can't believe somebody would want that behaviour"
items = {}
infolist = w.infolist_get('irc_server', '', '')
while w.infolist_next(info... | dotfiles | positive |
def simple_test(self, img, img_meta, rescale=True):
"""Simple test with single image."""
<DeepExtract>
assert self.test_cfg.mode in ['slide', 'whole']
ori_shape = img_meta[0]['ori_shape']
assert all((_['ori_shape'] == ori_shape for _ in img_meta))
if self.test_cfg.mode == 'slide':
seg_logit ... | def simple_test(self, img, img_meta, rescale=True):
"""Simple test with single image."""
assert self.test_cfg.mode in ['slide', 'whole']
ori_shape = img_meta[0]['ori_shape']
assert all((_['ori_shape'] == ori_shape for _ in img_meta))
if self.test_cfg.mode == 'slide':
seg_logit = self.slide_i... | BPR | positive |
def test_geo_value(self):
"""test whether geo values are valid for specific geo types"""
<DeepExtract>
rows = [CovidcastTestRow.make_default_row(geo_type='msa', geo_value=MSA[i - 1], value=i * 1.0, stderr=i * 10.0, sample_size=i * 100.0) for i in [1, 2, 3]] + [CovidcastTestRow.make_default_row(geo_type='fips', ... | def test_geo_value(self):
"""test whether geo values are valid for specific geo types"""
rows = [CovidcastTestRow.make_default_row(geo_type='msa', geo_value=MSA[i - 1], value=i * 1.0, stderr=i * 10.0, sample_size=i * 100.0) for i in [1, 2, 3]] + [CovidcastTestRow.make_default_row(geo_type='fips', geo_value=FIPS... | delphi-epidata | positive |
def build_fasttree(aln_file, out_file, clean_up=True, nthreads=1, tree_builder_args=None):
"""
build tree using fasttree
"""
log_file = out_file + '.log'
<DeepExtract>
exe = next(filter(shutil.which, ['FastTreeDblMP', 'FastTreeDbl', 'FastTreeMP', 'fasttreeMP', 'FastTree', 'fasttree']), default)
... | def build_fasttree(aln_file, out_file, clean_up=True, nthreads=1, tree_builder_args=None):
"""
build tree using fasttree
"""
log_file = out_file + '.log'
exe = next(filter(shutil.which, ['FastTreeDblMP', 'FastTreeDbl', 'FastTreeMP', 'fasttreeMP', 'FastTree', 'fasttree']), default)
if exe is None... | augur | positive |
def get_query_model(name, *args, random_state=None, **kwargs):
"""Get an instance of the query strategy.
Arguments
---------
name: str
Name of the query strategy.
*args:
Arguments for the model.
**kwargs:
Keyword arguments for the model.
Returns
-------
asre... | def get_query_model(name, *args, random_state=None, **kwargs):
"""Get an instance of the query strategy.
Arguments
---------
name: str
Name of the query strategy.
*args:
Arguments for the model.
**kwargs:
Keyword arguments for the model.
Returns
-------
asre... | asreview | positive |
def _install_tools(env, tools_conf=None):
"""
Install tools needed for Galaxy along with tool configuration
directories needed by Galaxy.
"""
if not tools_conf:
<DeepExtract>
with open(_tools_conf_path(env)) as in_handle:
full_data = yaml.safe_load(in_handle)
tools_conf =... | def _install_tools(env, tools_conf=None):
"""
Install tools needed for Galaxy along with tool configuration
directories needed by Galaxy.
"""
if not tools_conf:
with open(_tools_conf_path(env)) as in_handle:
full_data = yaml.safe_load(in_handle)
tools_conf = full_data
... | cloudbiolinux | positive |
def gather_options(self):
if not self.initialized:
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
<DeepExtract>
parser.add_argument('--dataroot', type=str, default='.', help='path to images (should have subfolders train, test etc)')
parser.add_argume... | def gather_options(self):
if not self.initialized:
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataroot', type=str, default='.', help='path to images (should have subfolders train, test etc)')
parser.add_argument('--batch_si... | dualFace | positive |
def esd_pnms(esd, pnms_thresh):
scores = []
dets = []
for ele in esd:
score = ele['score']
quad = ele['ke_quad']
det = np.array([[quad[0][0], quad[0][1]], [quad[1][0], quad[1][1]], [quad[2][0], quad[2][1]], [quad[3][0], quad[3][1]]])
scores.append(score)
dets.append(d... | def esd_pnms(esd, pnms_thresh):
scores = []
dets = []
for ele in esd:
score = ele['score']
quad = ele['ke_quad']
det = np.array([[quad[0][0], quad[0][1]], [quad[1][0], quad[1][1]], [quad[2][0], quad[2][1]], [quad[3][0], quad[3][1]]])
scores.append(score)
dets.append(d... | Box_Discretization_Network | positive |
def Max(self, k):
"""Computes the CDF of the maximum of k selections from this dist.
k: int
returns: new Cdf
"""
<DeepExtract>
new = copy.copy(self)
new.d = copy.copy(self.d)
new.label = label if label is not None else self.label
cdf = new
</DeepExtract>
cdf.ps **= k
... | def Max(self, k):
"""Computes the CDF of the maximum of k selections from this dist.
k: int
returns: new Cdf
"""
new = copy.copy(self)
new.d = copy.copy(self.d)
new.label = label if label is not None else self.label
cdf = new
cdf.ps **= k
return cdf | data-science-ipython-notebooks | positive |
def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None):
data = [] if data is None else data
files = [] if files is None else files
headers = {} if headers is None else headers
params = {} if params is None else params
... | def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None):
data = [] if data is None else data
files = [] if files is None else files
headers = {} if headers is None else headers
params = {} if params is None else params
... | alexa-sky-hd | positive |
def flatten_sequence(self, sequence, gold_snippets=False):
if sequence[-1] == vocab.EOS_TOK:
sequence = sequence[:-1]
if gold_snippets:
no_snippets_sequence = self.interaction.expand_snippets(sequence)
else:
<DeepExtract>
if sequence[-1] == vocab.EOS_TOK:
sequence = seque... | def flatten_sequence(self, sequence, gold_snippets=False):
if sequence[-1] == vocab.EOS_TOK:
sequence = sequence[:-1]
if gold_snippets:
no_snippets_sequence = self.interaction.expand_snippets(sequence)
else:
if sequence[-1] == vocab.EOS_TOK:
sequence = sequence[:-1]
... | editsql | positive |
def get_children(parent, tag_name):
if parent is None:
return []
<DeepExtract>
if parent is None:
parent = self.root
ret = parent.findall('.//' + self.ns + tag_name)
</DeepExtract>
if not ret:
<DeepExtract>
if parent is None:
parent = self.root
ret_list = pare... | def get_children(parent, tag_name):
if parent is None:
return []
if parent is None:
parent = self.root
ret = parent.findall('.//' + self.ns + tag_name)
if not ret:
if parent is None:
parent = self.root
ret_list = parent.findall('.//' + self.ns + tag_name + '-R... | canmatrix | positive |
@ddt.data(*CourseSamples.course_ids)
def test_any_activity(self, course_id):
<DeepExtract>
raise NotImplementedError
</DeepExtract>
<DeepExtract>
response = self.authenticated_get('/api/v0/courses/{}/recent_activity?activity_type={}'.format(course_id, 'ANY'))
self.assertEqual(response.status_code, 200)
... | @ddt.data(*CourseSamples.course_ids)
def test_any_activity(self, course_id):
raise NotImplementedError
response = self.authenticated_get('/api/v0/courses/{}/recent_activity?activity_type={}'.format(course_id, 'ANY'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, self.get_ac... | edx-analytics-data-api | positive |
def regularization(self, train_targets, train_features, coef=None, featselect_featvar=False):
"""Generate the omgea2 and coef value's.
Parameters
----------
train_targets : array
Dependent data used for training.
train_features : array
Independent data used ... | def regularization(self, train_targets, train_features, coef=None, featselect_featvar=False):
"""Generate the omgea2 and coef value's.
Parameters
----------
train_targets : array
Dependent data used for training.
train_features : array
Independent data used ... | CatLearn | positive |
def main():
parser = argparse.ArgumentParser(description='PyTorch Object Detection Training')
parser.add_argument('--config-file', default='', metavar='FILE', help='path to config file', type=str)
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument('--skip-test', dest='skip_test... | def main():
parser = argparse.ArgumentParser(description='PyTorch Object Detection Training')
parser.add_argument('--config-file', default='', metavar='FILE', help='path to config file', type=str)
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument('--skip-test', dest='skip_test... | AE-WTN | positive |
def start_proxy_process(self):
<DeepExtract>
out = [_PROXY_EXE, '-address', self.address, '-tcp-address', self.tcp_address, '-api-url', self.gateway_url + '/api/v1/routes', '-log-level', self.log_level]
if is_child_process:
out.append('-is-child-process')
if bool(self.tls_cert) != bool(self.tls_key)... | def start_proxy_process(self):
out = [_PROXY_EXE, '-address', self.address, '-tcp-address', self.tcp_address, '-api-url', self.gateway_url + '/api/v1/routes', '-log-level', self.log_level]
if is_child_process:
out.append('-is-child-process')
if bool(self.tls_cert) != bool(self.tls_key):
rais... | dask-gateway | positive |
@model.methodwrap(va=SVa, pid=SPid)
def munmap(self, va, pid):
<DeepExtract>
if str(pid).startswith('a.'):
simsym.assume(pid == False)
</DeepExtract>
del self.getproc(pid).va_map[va]
return {'r': 0} | @model.methodwrap(va=SVa, pid=SPid)
def munmap(self, va, pid):
if str(pid).startswith('a.'):
simsym.assume(pid == False)
del self.getproc(pid).va_map[va]
return {'r': 0} | commuter | positive |
def testBatchGradientDescentNormalizedBacktrackF7PL0(self):
epsilon = 12
attack = attacks.batch_gradient_descent.BatchGradientDescent()
attack.max_iterations = 10
attack.base_lr = 100
attack.momentum = 0
attack.c = 0
attack.lr_factor = 1.5
attack.normalized = True
attack.backtrack = ... | def testBatchGradientDescentNormalizedBacktrackF7PL0(self):
epsilon = 12
attack = attacks.batch_gradient_descent.BatchGradientDescent()
attack.max_iterations = 10
attack.base_lr = 100
attack.momentum = 0
attack.c = 0
attack.lr_factor = 1.5
attack.normalized = True
attack.backtrack = ... | confidence-calibrated-adversarial-training | positive |
def __init__(self, path, conf):
self.filename = path
self.tzinfo = conf.get('tzinfo', None)
self.defaultcopywildcard = conf.get('copy_wildcard', '_[0-9]*.*')
with io.open(path, 'r', encoding='utf-8', errors='replace') as fp:
peak = lchop(fp.read(512), BOM_UTF8)
fp.seek(0)
if peak... | def __init__(self, path, conf):
self.filename = path
self.tzinfo = conf.get('tzinfo', None)
self.defaultcopywildcard = conf.get('copy_wildcard', '_[0-9]*.*')
with io.open(path, 'r', encoding='utf-8', errors='replace') as fp:
peak = lchop(fp.read(512), BOM_UTF8)
fp.seek(0)
if peak... | acrylamid | positive |
def __call__(self, batch, output, attns, normalization=1.0, shard_size=0, trunc_start=0, trunc_size=None):
"""Compute the forward loss, possibly in shards in which case this
method also runs the backward pass and returns ``None`` as the loss
value.
Also supports truncated BPTT for long sequ... | def __call__(self, batch, output, attns, normalization=1.0, shard_size=0, trunc_start=0, trunc_size=None):
"""Compute the forward loss, possibly in shards in which case this
method also runs the backward pass and returns ``None`` as the loss
value.
Also supports truncated BPTT for long sequ... | DDAMS | positive |
def _get_connection_spec(self):
if self._connection_addr is None:
<DeepExtract>
pidfile = os.path.join(self._data_dir, 'postmaster.pid')
try:
with open(pidfile, 'rt') as f:
piddata = f.read()
except FileNotFoundError:
self._connection_addr = None
... | def _get_connection_spec(self):
if self._connection_addr is None:
pidfile = os.path.join(self._data_dir, 'postmaster.pid')
try:
with open(pidfile, 'rt') as f:
piddata = f.read()
except FileNotFoundError:
self._connection_addr = None
lines = pid... | asyncpg | positive |
def createFolders(uid):
"""Create the folder structure and copy code files"""
<DeepExtract>
src = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'html')
</DeepExtract>
<DeepExtract>
safeFolder = self.model.outputFolder
if self.isWindows() == True:
safeFolder = self.model.outputFolder.... | def createFolders(uid):
"""Create the folder structure and copy code files"""
src = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'html')
safeFolder = self.model.outputFolder
if self.isWindows() == True:
safeFolder = self.model.outputFolder.encode('ascii', 'ignore')
dest = os.pat... | d3MapRenderer | positive |
def test_exists_non_existent(self):
<DeepExtract>
filename = ''.join([random.choice(string.ascii_uppercase + string.digits) for x in range(length)]).lower()
</DeepExtract>
assert not self._storage.exists(filename) | def test_exists_non_existent(self):
filename = ''.join([random.choice(string.ascii_uppercase + string.digits) for x in range(length)]).lower()
assert not self._storage.exists(filename) | docker-registry | positive |
def _get_description(ioc: Element) -> Optional[str]:
<DeepExtract>
tag = _tag(_NS_OPENIOC, 'description')
</DeepExtract>
description = ioc.find(tag)
if description is None:
return None
return description.text | def _get_description(ioc: Element) -> Optional[str]:
tag = _tag(_NS_OPENIOC, 'description')
description = ioc.find(tag)
if description is None:
return None
return description.text | connectors | positive |
def test_eval_files(self):
run_predict(predict_args(data=FileDataParams(images=sorted(glob_all([os.path.join(this_dir, 'data', 'uw3_50lines', 'test', '*.png')])))))
r = run_eval(eval_args(gt_data=FileDataParams(texts=sorted(glob_all([os.path.join(this_dir, 'data', 'uw3_50lines', 'test', '*.gt.txt')])))))
se... | def test_eval_files(self):
run_predict(predict_args(data=FileDataParams(images=sorted(glob_all([os.path.join(this_dir, 'data', 'uw3_50lines', 'test', '*.png')])))))
r = run_eval(eval_args(gt_data=FileDataParams(texts=sorted(glob_all([os.path.join(this_dir, 'data', 'uw3_50lines', 'test', '*.gt.txt')])))))
se... | calamari | positive |
def _init_sem_data_gen(graph: nx.DiGraph, schema: Dict, n_samples: int, default_type: str, distributions: Dict[str, str], seed: int):
np.random.seed(seed)
if not nx.algorithms.is_directed_acyclic_graph(graph):
raise ValueError('Provided graph is not a DAG.')
<DeepExtract>
default_distributions = {'c... | def _init_sem_data_gen(graph: nx.DiGraph, schema: Dict, n_samples: int, default_type: str, distributions: Dict[str, str], seed: int):
np.random.seed(seed)
if not nx.algorithms.is_directed_acyclic_graph(graph):
raise ValueError('Provided graph is not a DAG.')
default_distributions = {'continuous': 'g... | causalnex | positive |
def test_bbox_head_loss():
"""
Tests bbox head loss when truth is empty and non-empty
"""
self = BBoxHead(in_channels=8, roi_feat_size=3)
num_imgs = 1
feat = torch.rand(1, 1, 3, 3)
proposal_list = [torch.Tensor([[23.6667, 23.8757, 228.6326, 153.8874]])]
target_cfg = mmcv.Config({'pos_wei... | def test_bbox_head_loss():
"""
Tests bbox head loss when truth is empty and non-empty
"""
self = BBoxHead(in_channels=8, roi_feat_size=3)
num_imgs = 1
feat = torch.rand(1, 1, 3, 3)
proposal_list = [torch.Tensor([[23.6667, 23.8757, 228.6326, 153.8874]])]
target_cfg = mmcv.Config({'pos_wei... | D2Det | positive |
def decode_seg_map_sequence(label_masks):
if label_masks.ndim == 2:
label_masks = label_masks[None, :, :]
rgb_masks = []
for label_mask in label_masks:
<DeepExtract>
n_classes = 21
label_colours = get_pascal_labels()
r = label_mask.copy()
g = label_mask.copy()
... | def decode_seg_map_sequence(label_masks):
if label_masks.ndim == 2:
label_masks = label_masks[None, :, :]
rgb_masks = []
for label_mask in label_masks:
n_classes = 21
label_colours = get_pascal_labels()
r = label_mask.copy()
g = label_mask.copy()
b = label_mas... | DRS | positive |
def compute_pvalues(iteration_result, num_motifs, force):
"""Compute motif scores.
The result is a dictionary from cluster -> (feature_id, pvalue)
containing a sparse gene-to-pvalue mapping for each cluster
In order to influence the sequences
that go into meme, the user can specify ... | def compute_pvalues(iteration_result, num_motifs, force):
"""Compute motif scores.
The result is a dictionary from cluster -> (feature_id, pvalue)
containing a sparse gene-to-pvalue mapping for each cluster
In order to influence the sequences
that go into meme, the user can specify ... | cmonkey2 | positive |
def train(self, inputs: List[Vector]) -> None:
assignments = [random.randrange(self.k) for _ in inputs]
with tqdm.tqdm(itertools.count()) as t:
for _ in t:
<DeepExtract>
clusters = [[] for i in range(self.k)]
for (input, assignment) in zip(inputs, assignments):
cl... | def train(self, inputs: List[Vector]) -> None:
assignments = [random.randrange(self.k) for _ in inputs]
with tqdm.tqdm(itertools.count()) as t:
for _ in t:
clusters = [[] for i in range(self.k)]
for (input, assignment) in zip(inputs, assignments):
clusters[assignm... | data-science-from-scratch | positive |
def forward(self, *inputs, **kwargs):
if not self.device_ids:
return self.module(*inputs, **kwargs)
<DeepExtract>
(inputs, kwargs) = scatter_kwargs(inputs, kwargs, self.device_ids, dim=self.dim, chunk_sizes=self.chunk_sizes)
</DeepExtract>
if len(self.device_ids) == 1:
return self.module(*in... | def forward(self, *inputs, **kwargs):
if not self.device_ids:
return self.module(*inputs, **kwargs)
(inputs, kwargs) = scatter_kwargs(inputs, kwargs, self.device_ids, dim=self.dim, chunk_sizes=self.chunk_sizes)
if len(self.device_ids) == 1:
return self.module(*inputs[0], **kwargs[0])
rep... | CenterNet-CondInst | positive |
def test_ignore_url():
from aws_xray_sdk.ext.httplib import add_ignored
path = '/status/200'
url = 'https://{}{}'.format(BASE_URL, path)
add_ignored(urls=[path])
<DeepExtract>
parts = urlparse(url)
(host, _, port) = parts.netloc.partition(':')
if port == '':
port = None
if True:
... | def test_ignore_url():
from aws_xray_sdk.ext.httplib import add_ignored
path = '/status/200'
url = 'https://{}{}'.format(BASE_URL, path)
add_ignored(urls=[path])
parts = urlparse(url)
(host, _, port) = parts.netloc.partition(':')
if port == '':
port = None
if True:
conn =... | aws-xray-sdk-python | positive |
@property
def ecus(self):
if not self._ecus:
<DeepExtract>
ecus = []
ecu_names = []
for matrixName in self:
for ecu in self[matrixName].ecus:
if ecu.name not in ecu_names:
ecu_names.append(ecu.name)
ecus.append(ecu)
... | @property
def ecus(self):
if not self._ecus:
ecus = []
ecu_names = []
for matrixName in self:
for ecu in self[matrixName].ecus:
if ecu.name not in ecu_names:
ecu_names.append(ecu.name)
ecus.append(ecu)
self._ecus = e... | canmatrix | positive |
def reshape_input(input_tensor, *args):
<DeepExtract>
if name is None:
name = input_tensor.name
if 3 is not None:
assert_rank(input_tensor, 3, name)
shape = input_tensor.shape.as_list()
non_static_indexes = []
for (index, dim) in enumerate(shape):
if dim is None:
... | def reshape_input(input_tensor, *args):
if name is None:
name = input_tensor.name
if 3 is not None:
assert_rank(input_tensor, 3, name)
shape = input_tensor.shape.as_list()
non_static_indexes = []
for (index, dim) in enumerate(shape):
if dim is None:
non_static_ind... | DAPPLE | positive |
def matmul(a: Array, b: Array, transpose_a=False, transpose_b=False):
""" Matrix multiplication with a possible transpose of the input.
Parameters
----------
a : ds-array
First matrix.
b : ds-array
Second matrix.
transpose_a : bool
Transpo... | def matmul(a: Array, b: Array, transpose_a=False, transpose_b=False):
""" Matrix multiplication with a possible transpose of the input.
Parameters
----------
a : ds-array
First matrix.
b : ds-array
Second matrix.
transpose_a : bool
Transpo... | dislib | positive |
@parse_debug
def parse_constant_declarators_rest(self):
<DeepExtract>
array_dimension = self.parse_array_dimension()
self.accept('=')
initializer = self.parse_variable_initializer()
(array_dimension, initializer) = (array_dimension, initializer)
</DeepExtract>
declarators = [tree.VariableDeclarator(... | @parse_debug
def parse_constant_declarators_rest(self):
array_dimension = self.parse_array_dimension()
self.accept('=')
initializer = self.parse_variable_initializer()
(array_dimension, initializer) = (array_dimension, initializer)
declarators = [tree.VariableDeclarator(dimensions=array_dimension, i... | code-transformer | positive |
def main():
check_suite = CheckSuite()
check_suite.load_all_available_checkers()
parser = argparse.ArgumentParser()
parser.add_argument('--test', '-t', '--test=', '-t=', default=[], action='append', help='Select the Checks you want to perform. Defaults to \'acdd\' if unspecified. Versions of standards ... | def main():
check_suite = CheckSuite()
check_suite.load_all_available_checkers()
parser = argparse.ArgumentParser()
parser.add_argument('--test', '-t', '--test=', '-t=', default=[], action='append', help='Select the Checks you want to perform. Defaults to \'acdd\' if unspecified. Versions of standards ... | compliance-checker | positive |
def mousePressEvent(self, event):
if event.button() != Qt.LeftButton and event.button() != Qt.RightButton:
return
if not self.isMouseEventInBlock(event):
self.scroll_base_x = event.x()
self.scroll_base_y = event.y()
self.scroll_mode = True
self.viewport().grabMouse()
... | def mousePressEvent(self, event):
if event.button() != Qt.LeftButton and event.button() != Qt.RightButton:
return
if not self.isMouseEventInBlock(event):
self.scroll_base_x = event.x()
self.scroll_base_y = event.y()
self.scroll_mode = True
self.viewport().grabMouse()
... | deprecated-binaryninja-python | positive |
def test_can_be_used_to_implement_auth_example():
roles = ['UNKNOWN', 'USER', 'REVIEWER', 'ADMIN']
class User:
def __init__(self, token: str):
self.token_index = roles.index(token)
def has_role(self, role: str):
role_index = roles.index(role)
return self.to... | def test_can_be_used_to_implement_auth_example():
roles = ['UNKNOWN', 'USER', 'REVIEWER', 'ADMIN']
class User:
def __init__(self, token: str):
self.token_index = roles.index(token)
def has_role(self, role: str):
role_index = roles.index(role)
return self.to... | ariadne | positive |
def sample(self, N):
"""Sample N realizations. Returns N-by-M (ndim) sample matrix.
Example
-------
>>> plt.scatter(*(UniRV(C=randcov(2)).sample(10**4).T)) # doctest: +SKIP
"""
if self.C == 0:
D = np.zeros((N, self.M))
else:
<DeepExtract>
raise NotImplemente... | def sample(self, N):
"""Sample N realizations. Returns N-by-M (ndim) sample matrix.
Example
-------
>>> plt.scatter(*(UniRV(C=randcov(2)).sample(10**4).T)) # doctest: +SKIP
"""
if self.C == 0:
D = np.zeros((N, self.M))
else:
raise NotImplementedError('Must b... | DAPPER | positive |
def test_terraform_get_node(create_terraform, create_temp_dir):
from processor.connector.snapshot_custom import get_node
data = {'type': 'terraform', 'snapshotId': '1', 'path': 'a/b/c'}
terr_data = ['name="azrcterrafstr02"', 'locatio="neastus2"', 'resourceGroup="core-terraf-auto-rg"', 'containerName="states... | def test_terraform_get_node(create_terraform, create_temp_dir):
from processor.connector.snapshot_custom import get_node
data = {'type': 'terraform', 'snapshotId': '1', 'path': 'a/b/c'}
terr_data = ['name="azrcterrafstr02"', 'locatio="neastus2"', 'resourceGroup="core-terraf-auto-rg"', 'containerName="states... | cloud-validation-framework | positive |
def refreshOrgList():
global ORG_LIST
print('INFO: Starting org list refresh at %s...' % datetime.datetime.now())
flag_firstorg = True
<DeepExtract>
merakirequestthrottler()
try:
r = requests.get('https://api.meraki.com/api/v0/organizations', headers={'X-Cisco-Meraki-API-Key': ARG_APIKEY, 'C... | def refreshOrgList():
global ORG_LIST
print('INFO: Starting org list refresh at %s...' % datetime.datetime.now())
flag_firstorg = True
merakirequestthrottler()
try:
r = requests.get('https://api.meraki.com/api/v0/organizations', headers={'X-Cisco-Meraki-API-Key': ARG_APIKEY, 'Content-Type': ... | automation-scripts | positive |
def get_matrix(self):
for entry in (self.tp, self.fp, self.tn, self.fn):
if entry is None:
<DeepExtract>
if self.test is None or self.reference is None:
raise ValueError("'test' and 'reference' must both be set to compute confusion matrix.")
assert_shape(self.test, se... | def get_matrix(self):
for entry in (self.tp, self.fp, self.tn, self.fn):
if entry is None:
if self.test is None or self.reference is None:
raise ValueError("'test' and 'reference' must both be set to compute confusion matrix.")
assert_shape(self.test, self.reference)
... | CoTr | positive |
def preprocess(self, data: Dict[str, torch.Tensor]) -> torch.Tensor:
if 'batch' in data:
batch = data['batch']
else:
batch = data['pos'].new_zeros(data['pos'].shape[0], dtype=torch.long)
if 'edge_src' in data and 'edge_dst' in data:
edge_src = data['edge_src']
edge_dst = data... | def preprocess(self, data: Dict[str, torch.Tensor]) -> torch.Tensor:
if 'batch' in data:
batch = data['batch']
else:
batch = data['pos'].new_zeros(data['pos'].shape[0], dtype=torch.long)
if 'edge_src' in data and 'edge_dst' in data:
edge_src = data['edge_src']
edge_dst = data... | e3nn | positive |
@patch('decorators.s3')
@patch('decorators.uuid4', MagicMock(side_effect=['a']))
def test_it_overrides_default_bucket_and_prefix(mock_s3):
with patch.dict(os.environ, {'StateBucket': 'bucket'}):
@s3_state_store(offload_keys=['Dict'], should_load=False, prefix='custom/', bucket='otherbucket')
def my... | @patch('decorators.s3')
@patch('decorators.uuid4', MagicMock(side_effect=['a']))
def test_it_overrides_default_bucket_and_prefix(mock_s3):
with patch.dict(os.environ, {'StateBucket': 'bucket'}):
@s3_state_store(offload_keys=['Dict'], should_load=False, prefix='custom/', bucket='otherbucket')
def my... | amazon-s3-find-and-forget | positive |
def visit_Forall(self, expression: Forall) -> Union[Constant, Or, Symbol]:
<DeepExtract>
if self._top_level:
expression.expression = expression.expression.propagate_constants()
expression.expression = SubstituteCalls().visit(expression.expression)
expression.expression = expression.expressio... | def visit_Forall(self, expression: Forall) -> Union[Constant, Or, Symbol]:
if self._top_level:
expression.expression = expression.expression.propagate_constants()
expression.expression = SubstituteCalls().visit(expression.expression)
expression.expression = expression.expression.propagate_co... | DNNV | positive |
def evse_phase(self, station_id: str) -> float:
""" Returns the phase angle of the EVSE.
Args:
station_id (str): The ID of the station for which the allowable rates
should be returned.
Returns:
float: phase angle of the EVSE. [degrees]
"""
<DeepExtra... | def evse_phase(self, station_id: str) -> float:
""" Returns the phase angle of the EVSE.
Args:
station_id (str): The ID of the station for which the allowable rates
should be returned.
Returns:
float: phase angle of the EVSE. [degrees]
"""
if 'in... | acnportal | positive |
@pytest.mark.skipif('ethereum_optimized.london.state_db' not in sys.modules, reason="missing dependency (use `pip install 'ethereum[optimized]'`)")
def test_storage_key() -> None:
def actions(impl: Any) -> Any:
obj = impl.State()
impl.set_account(obj, ADDRESS_FOO, EMPTY_ACCOUNT)
impl.set_st... | @pytest.mark.skipif('ethereum_optimized.london.state_db' not in sys.modules, reason="missing dependency (use `pip install 'ethereum[optimized]'`)")
def test_storage_key() -> None:
def actions(impl: Any) -> Any:
obj = impl.State()
impl.set_account(obj, ADDRESS_FOO, EMPTY_ACCOUNT)
impl.set_st... | eth1.0-specs | positive |
def _read_config_categories(self):
"""Read and parse log configurations"""
self._log_configs = {'Default': []}
log_path = os.path.join(cfclient.config_path, 'log')
for cathegory in os.listdir(log_path):
cathegory_path = os.path.join(log_path, cathegory)
try:
if os.path.isdir(... | def _read_config_categories(self):
"""Read and parse log configurations"""
self._log_configs = {'Default': []}
log_path = os.path.join(cfclient.config_path, 'log')
for cathegory in os.listdir(log_path):
cathegory_path = os.path.join(log_path, cathegory)
try:
if os.path.isdir(... | crazyflie-clients-python | positive |
def PlotCdf(self, label=None):
"""Draws a Cdf with vertical lines at the observed test stat.
"""
def VertLine(x):
"""Draws a vertical line at x."""
thinkplot.Plot([x, x], [0, 1], color='0.8')
<DeepExtract>
thinkplot.Plot([self.actual, self.actual], [0, 1], color='0.8')
</DeepExtract... | def PlotCdf(self, label=None):
"""Draws a Cdf with vertical lines at the observed test stat.
"""
def VertLine(x):
"""Draws a vertical line at x."""
thinkplot.Plot([x, x], [0, 1], color='0.8')
thinkplot.Plot([self.actual, self.actual], [0, 1], color='0.8')
thinkplot.Cdf(self.test... | bayesianGameofThrones | positive |
@filter_hook
def get_field_attrs(db_field, **kwargs):
if db_field.name in self.style_fields:
<DeepExtract>
if self.style_fields[db_field.name] in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
attrs = {'widget': widgets.AdminRadioSelect(attrs={'inlin... | @filter_hook
def get_field_attrs(db_field, **kwargs):
if db_field.name in self.style_fields:
if self.style_fields[db_field.name] in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
attrs = {'widget': widgets.AdminRadioSelect(attrs={'inline': 'inline' i... | Django_Blog | positive |
def __init__(self, initial_amount=1000000.0, max_stock=100.0, cost_pct=0.001, gamma=0.99, beg_idx=0, end_idx=1113):
self.df_pwd = './elegantrl/envs/China_A_shares.pandas.dataframe'
self.npz_pwd = './elegantrl/envs/China_A_shares.numpy.npz'
<DeepExtract>
tech_id_list = ['macd', 'boll_ub', 'boll_lb', 'rsi_30'... | def __init__(self, initial_amount=1000000.0, max_stock=100.0, cost_pct=0.001, gamma=0.99, beg_idx=0, end_idx=1113):
self.df_pwd = './elegantrl/envs/China_A_shares.pandas.dataframe'
self.npz_pwd = './elegantrl/envs/China_A_shares.numpy.npz'
tech_id_list = ['macd', 'boll_ub', 'boll_lb', 'rsi_30', 'cci_30', 'd... | ElegantRL | positive |
def __init__(self, content, depot_name=None):
super(DepotFileInfo, self).__init__()
<DeepExtract>
object.__setattr__(self, '_frozen', False)
</DeepExtract>
if isinstance(content, dict):
object.__setattr__(self, 'original_content', None)
self.update(content)
else:
object.__setattr... | def __init__(self, content, depot_name=None):
super(DepotFileInfo, self).__init__()
object.__setattr__(self, '_frozen', False)
if isinstance(content, dict):
object.__setattr__(self, 'original_content', None)
self.update(content)
else:
object.__setattr__(self, 'original_content', ... | depot | positive |
def _infer(self, mix: th.Tensor, mode: str) -> Union[th.Tensor, List[th.Tensor]]:
"""
Return time signals or frequency TF masks
"""
(stft, _) = self.enh_transform.encode(mix, None)
feats = self.enh_transform(stft)
<DeepExtract>
x = self.proj(feats)
x = self.conv(x)
masks = self.n... | def _infer(self, mix: th.Tensor, mode: str) -> Union[th.Tensor, List[th.Tensor]]:
"""
Return time signals or frequency TF masks
"""
(stft, _) = self.enh_transform.encode(mix, None)
feats = self.enh_transform(stft)
x = self.proj(feats)
x = self.conv(x)
masks = self.non_linear(self... | aps | positive |
def is_not_inf(self):
"""Asserts that val is real number and is *not* ``Inf`` (infinity).
Examples:
Usage::
assert_that(0).is_not_inf()
assert_that(123.4).is_not_inf()
assert_that(float('nan')).is_not_inf()
Returns:
Assertion... | def is_not_inf(self):
"""Asserts that val is real number and is *not* ``Inf`` (infinity).
Examples:
Usage::
assert_that(0).is_not_inf()
assert_that(123.4).is_not_inf()
assert_that(float('nan')).is_not_inf()
Returns:
Assertion... | assertpy | positive |
def setup_method(self, method):
<DeepExtract>
(fd, fqfn) = tempfile.mkstemp(prefix='TestSlicer7x7In_')
fp = os.fdopen(fd, 'wt')
fp.write('0-0,0-1,0-2,0-3,0-4,0-5,0-6\n')
fp.write('1-0,1-1,1-2,1-3,1-4,1-5,1-6\n')
fp.write('2-0,2-1,2-2,2-3,2-4,2-5,2-6\n')
fp.write('3-0,3-1,3-2,3-3,3-4,3-5,3-6\n')
... | def setup_method(self, method):
(fd, fqfn) = tempfile.mkstemp(prefix='TestSlicer7x7In_')
fp = os.fdopen(fd, 'wt')
fp.write('0-0,0-1,0-2,0-3,0-4,0-5,0-6\n')
fp.write('1-0,1-1,1-2,1-3,1-4,1-5,1-6\n')
fp.write('2-0,2-1,2-2,2-3,2-4,2-5,2-6\n')
fp.write('3-0,3-1,3-2,3-3,3-4,3-5,3-6\n')
fp.write('... | DataGristle | positive |
def make(self, *, initializer=default_initializer) -> Graph:
graph = Graph()
<DeepExtract>
raise NotImplementedError()
</DeepExtract>
return graph | def make(self, *, initializer=default_initializer) -> Graph:
graph = Graph()
raise NotImplementedError()
return graph | autogoal | positive |
def gen_test_df() -> pd.DataFrame:
rand = np.random.RandomState(0)
nrows = 30
data = {}
data[0] = gen_random_dataframe(nrows=nrows, ncols=10, random_state=rand).reset_index(drop=True)
data[1] = gen_random_dataframe(nrows=nrows, ncols=10, na_ratio=0.1, random_state=rand).reset_index(drop=True)
da... | def gen_test_df() -> pd.DataFrame:
rand = np.random.RandomState(0)
nrows = 30
data = {}
data[0] = gen_random_dataframe(nrows=nrows, ncols=10, random_state=rand).reset_index(drop=True)
data[1] = gen_random_dataframe(nrows=nrows, ncols=10, na_ratio=0.1, random_state=rand).reset_index(drop=True)
da... | dataprep | positive |
def axes_limits_set(data):
""" Set the axes limits """
xmax = self.calcs.iterations - 1 if self.calcs.iterations > 1 else 1
if data:
<DeepExtract>
(ymin, ymax) = (list(), list())
for item in data:
dataset = list(filter(lambda x: x is not None, item))
if not dataset:
... | def axes_limits_set(data):
""" Set the axes limits """
xmax = self.calcs.iterations - 1 if self.calcs.iterations > 1 else 1
if data:
(ymin, ymax) = (list(), list())
for item in data:
dataset = list(filter(lambda x: x is not None, item))
if not dataset:
... | DeepFakeTutorial | positive |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.