before
stringlengths 0
955k
| after
stringlengths 0
877k
| repo
stringlengths 1
74
| type
stringclasses 1
value |
|---|---|---|---|
@unittest.expectedFailure
def test_673_centos8_cntlm_dockerfile(self):
""" WHEN using a dockerfile for systemd-enabled CentOS 8,
THEN we can create an image with an cntlm service
being installed and enabled.
Addtionally we do check an example application"""
if not os.path.exists(DOCKER_SOCKET):
self.skipTest('docker-based test')
if not os.path.exists(PSQL_TOOL):
self.skipTest('postgres tools missing on host')
docker = _docker
curl = _curl
max4 = _curl_timeout4
python = _python or _python2
if python.endswith('python3'):
self.skipTest('no python3 on centos:7')
<DeepExtract>
name = self.caller_testname()
if suffix:
testname = name + '_' + suffix
testname = name
</DeepExtract>
<DeepExtract>
testname = testname or self.caller_testname()
newdir = 'tmp/tmp.' + testname
if os.path.isdir(newdir):
shutil.rmtree(newdir)
os.makedirs(newdir)
testdir = newdir
</DeepExtract>
dockerfile = 'centos8-cntlm.dockerfile'
<DeepExtract>
image = ''
for line in open(dockerfile):
m = re.match('[Ff][Rr][Oo][Mm] *"([^"]*)"', line)
if m:
image = m.group(1)
break
m = re.match('[Ff][Rr][Oo][Mm] *(\\w[^ ]*)', line)
if m:
image = m.group(1).strip()
break
logg.debug("--\n-- '%s' FROM '%s'", dockerfile, image)
if image:
addhosts = self.start_mirror(image, extras)
addhosts = ''
</DeepExtract>
<DeepExtract>
savename = os.path.splitext(os.path.basename(dockerfile))[0]
</DeepExtract>
saveto = SAVETO
images = IMAGES
psql = PSQL_TOOL
cmd = '{docker} build . -f {dockerfile} {addhosts} --tag {images}:{testname}'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
</DeepExtract>
cmd = '{docker} rm --force {testname}'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.call(cmd.format(**locals()), shell=shell)
</DeepExtract>
cmd = '{docker} run -d --name {testname} {images}:{testname}'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
</DeepExtract>
<DeepExtract>
docker = _docker
cmd = '{docker} inspect {name}'
values = output(cmd.format(**locals()))
values = json.loads(values)
if not values or 'NetworkSettings' not in values[0]:
logg.critical(' docker inspect %s => %s ', testname, values)
container = values[0]['NetworkSettings']['IPAddress']
</DeepExtract>
for attempt in xrange(9):
cmd = '{docker} exec {testname} /usr/bin/systemctl is-active cntlm'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
run = subprocess.Popen(cmd.format(**locals()), shell=shell, stdout=subprocess.PIPE)
(out, err) = run.communicate()
(out, end) = (decodes(out), run.returncode)
</DeepExtract>
logg.info('is-active => %s', out)
time.sleep(1)
if not end:
break
cmd = 'http_proxy={container}:3128 {curl} {max4} -o {testdir}/{testname}.txt http://www.google.com'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
</DeepExtract>
cmd = "grep '<img alt=.Google.' {testdir}/{testname}.txt"
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
</DeepExtract>
cmd = '{docker} stop {testname}'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
</DeepExtract>
cmd = '{docker} rm --force {testname}'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
</DeepExtract>
cmd = '{docker} rmi {saveto}/{savename}:latest'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.call(cmd.format(**locals()), shell=shell)
</DeepExtract>
cmd = '{docker} tag {images}:{testname} {saveto}/{savename}:latest'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
</DeepExtract>
cmd = '{docker} rmi {images}:{testname}'
<DeepExtract>
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.call(cmd.format(**locals()), shell=shell)
</DeepExtract>
<DeepExtract>
testname = testname or self.caller_testname()
newdir = 'tmp/tmp.' + testname
if os.path.isdir(newdir):
shutil.rmtree(newdir)
return newdir
</DeepExtract>
|
@unittest.expectedFailure
def test_673_centos8_cntlm_dockerfile(self):
""" WHEN using a dockerfile for systemd-enabled CentOS 8,
THEN we can create an image with an cntlm service
being installed and enabled.
Addtionally we do check an example application"""
if not os.path.exists(DOCKER_SOCKET):
self.skipTest('docker-based test')
if not os.path.exists(PSQL_TOOL):
self.skipTest('postgres tools missing on host')
docker = _docker
curl = _curl
max4 = _curl_timeout4
python = _python or _python2
if python.endswith('python3'):
self.skipTest('no python3 on centos:7')
name = self.caller_testname()
if suffix:
testname = name + '_' + suffix
testname = name
testname = testname or self.caller_testname()
newdir = 'tmp/tmp.' + testname
if os.path.isdir(newdir):
shutil.rmtree(newdir)
os.makedirs(newdir)
testdir = newdir
dockerfile = 'centos8-cntlm.dockerfile'
image = ''
for line in open(dockerfile):
m = re.match('[Ff][Rr][Oo][Mm] *"([^"]*)"', line)
if m:
image = m.group(1)
break
m = re.match('[Ff][Rr][Oo][Mm] *(\\w[^ ]*)', line)
if m:
image = m.group(1).strip()
break
logg.debug("--\n-- '%s' FROM '%s'", dockerfile, image)
if image:
addhosts = self.start_mirror(image, extras)
addhosts = ''
savename = os.path.splitext(os.path.basename(dockerfile))[0]
saveto = SAVETO
images = IMAGES
psql = PSQL_TOOL
cmd = '{docker} build . -f {dockerfile} {addhosts} --tag {images}:{testname}'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
cmd = '{docker} rm --force {testname}'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.call(cmd.format(**locals()), shell=shell)
cmd = '{docker} run -d --name {testname} {images}:{testname}'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
docker = _docker
cmd = '{docker} inspect {name}'
values = output(cmd.format(**locals()))
values = json.loads(values)
if not values or 'NetworkSettings' not in values[0]:
logg.critical(' docker inspect %s => %s ', testname, values)
container = values[0]['NetworkSettings']['IPAddress']
for attempt in xrange(9):
cmd = '{docker} exec {testname} /usr/bin/systemctl is-active cntlm'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
run = subprocess.Popen(cmd.format(**locals()), shell=shell, stdout=subprocess.PIPE)
(out, err) = run.communicate()
(out, end) = (decodes(out), run.returncode)
logg.info('is-active => %s', out)
time.sleep(1)
if not end:
break
cmd = 'http_proxy={container}:3128 {curl} {max4} -o {testdir}/{testname}.txt http://www.google.com'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
cmd = "grep '<img alt=.Google.' {testdir}/{testname}.txt"
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
cmd = '{docker} stop {testname}'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
cmd = '{docker} rm --force {testname}'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
cmd = '{docker} rmi {saveto}/{savename}:latest'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.call(cmd.format(**locals()), shell=shell)
cmd = '{docker} tag {images}:{testname} {saveto}/{savename}:latest'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.check_call(cmd.format(**locals()), shell=shell)
cmd = '{docker} rmi {images}:{testname}'
if isinstance(cmd.format(**locals()), basestring):
logg.info(': %s', cmd.format(**locals()))
else:
logg.info(': %s', ' '.join(["'%s'" % item for item in cmd.format(**locals())]))
return subprocess.call(cmd.format(**locals()), shell=shell)
testname = testname or self.caller_testname()
newdir = 'tmp/tmp.' + testname
if os.path.isdir(newdir):
shutil.rmtree(newdir)
return newdir
</DeepExtract>
|
docker-systemctl-images
|
positive
|
def im_detect_mask_aspect_ratio(model, im, aspect_ratio, boxes, hflip=False):
"""Computes mask detections at the given width-relative aspect ratio"""
im_ar = image_utils.aspect_ratio_rel(im, aspect_ratio)
boxes_ar = box_utils.aspect_ratio(boxes, aspect_ratio)
if hflip:
<DeepExtract>
im_hf = im_ar[:, ::-1, :]
boxes_hf = box_utils.flip_boxes(boxes_ar, im_ar.shape[1])
(blob_conv_hf, im_scale_hf) = im_conv_body_only(model, im_hf, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE)
masks_hf = im_detect_mask(model, im_scale_hf, boxes_hf, blob_conv_hf)
masks_inv = masks_hf[:, :, :, ::-1]
masks_ar = masks_inv
</DeepExtract>
else:
<DeepExtract>
boxes = None
(inputs, im_scale) = _get_blobs(im, boxes, target_scale, target_max_size)
conv_body_only = np.ones(1, dtype=np.int)
if cfg.PYTORCH_VERSION_LESS_THAN_040:
inputs['data'] = [Variable(torch.from_numpy(inputs['data']), volatile=True)]
inputs['im_info'] = [Variable(torch.from_numpy(inputs['im_info']), volatile=True)]
inputs['conv_body_only'] = [Variable(torch.from_numpy(conv_body_only), volatile=True)]
else:
inputs['data'] = [Variable(torch.from_numpy(inputs['data']))]
inputs['im_info'] = [Variable(torch.from_numpy(inputs['im_info']))]
inputs['conv_body_only'] = [Variable(torch.from_numpy(conv_body_only))]
blob_conv = model(**inputs)
(blob_conv_ar, im_scale_ar) = (blob_conv, im_scale)
</DeepExtract>
<DeepExtract>
M = cfg.MRCNN.RESOLUTION
if boxes_ar.shape[0] == 0:
pred_masks = np.zeros((0, M, M), np.float32)
masks_ar = pred_masks
inputs = {'mask_rois': _get_rois_blob(boxes_ar, im_scale_ar)}
if cfg.FPN.MULTILEVEL_ROIS:
_add_multilevel_rois_for_test(inputs, 'mask_rois')
if not cfg.MODEL.INMODAL_ON:
pred_masks = model.module.mask_net(blob_conv_ar, inputs)
pred_masks = pred_masks.data.cpu().numpy().squeeze()
if cfg.MRCNN.CLS_SPECIFIC_MASK:
pred_masks = pred_masks.reshape([-1, cfg.MODEL.NUM_CLASSES, M, M])
else:
pred_masks = pred_masks.reshape([-1, 1, M, M])
masks_ar = pred_masks
else:
(pred_amodals, pred_inmodals) = model.module.mask_net(blob_conv_ar, inputs)
pred_amodals = pred_amodals.data.cpu().numpy().squeeze()
pred_inmodals = pred_inmodals.data.cpu().numpy().squeeze()
if cfg.MRCNN.CLS_SPECIFIC_MASK:
pred_amodals = pred_amodals.reshape([-1, cfg.MODEL.NUM_CLASSES, M, M])
pred_inmodals = pred_inmodals.reshape([-1, cfg.MODEL.NUM_CLASSES, M, M])
else:
pred_amodals = pred_amodals.reshape([-1, 1, M, M])
pred_inmodals = pred_inmodals.reshape([-1, 1, M, M])
masks_ar = (pred_amodals, pred_inmodals)
</DeepExtract>
return masks_ar
|
def im_detect_mask_aspect_ratio(model, im, aspect_ratio, boxes, hflip=False):
"""Computes mask detections at the given width-relative aspect ratio"""
im_ar = image_utils.aspect_ratio_rel(im, aspect_ratio)
boxes_ar = box_utils.aspect_ratio(boxes, aspect_ratio)
if hflip:
im_hf = im_ar[:, ::-1, :]
boxes_hf = box_utils.flip_boxes(boxes_ar, im_ar.shape[1])
(blob_conv_hf, im_scale_hf) = im_conv_body_only(model, im_hf, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE)
masks_hf = im_detect_mask(model, im_scale_hf, boxes_hf, blob_conv_hf)
masks_inv = masks_hf[:, :, :, ::-1]
masks_ar = masks_inv
else:
boxes = None
(inputs, im_scale) = _get_blobs(im, boxes, target_scale, target_max_size)
conv_body_only = np.ones(1, dtype=np.int)
if cfg.PYTORCH_VERSION_LESS_THAN_040:
inputs['data'] = [Variable(torch.from_numpy(inputs['data']), volatile=True)]
inputs['im_info'] = [Variable(torch.from_numpy(inputs['im_info']), volatile=True)]
inputs['conv_body_only'] = [Variable(torch.from_numpy(conv_body_only), volatile=True)]
else:
inputs['data'] = [Variable(torch.from_numpy(inputs['data']))]
inputs['im_info'] = [Variable(torch.from_numpy(inputs['im_info']))]
inputs['conv_body_only'] = [Variable(torch.from_numpy(conv_body_only))]
blob_conv = model(**inputs)
(blob_conv_ar, im_scale_ar) = (blob_conv, im_scale)
M = cfg.MRCNN.RESOLUTION
if boxes_ar.shape[0] == 0:
pred_masks = np.zeros((0, M, M), np.float32)
masks_ar = pred_masks
inputs = {'mask_rois': _get_rois_blob(boxes_ar, im_scale_ar)}
if cfg.FPN.MULTILEVEL_ROIS:
_add_multilevel_rois_for_test(inputs, 'mask_rois')
if not cfg.MODEL.INMODAL_ON:
pred_masks = model.module.mask_net(blob_conv_ar, inputs)
pred_masks = pred_masks.data.cpu().numpy().squeeze()
if cfg.MRCNN.CLS_SPECIFIC_MASK:
pred_masks = pred_masks.reshape([-1, cfg.MODEL.NUM_CLASSES, M, M])
else:
pred_masks = pred_masks.reshape([-1, 1, M, M])
masks_ar = pred_masks
else:
(pred_amodals, pred_inmodals) = model.module.mask_net(blob_conv_ar, inputs)
pred_amodals = pred_amodals.data.cpu().numpy().squeeze()
pred_inmodals = pred_inmodals.data.cpu().numpy().squeeze()
if cfg.MRCNN.CLS_SPECIFIC_MASK:
pred_amodals = pred_amodals.reshape([-1, cfg.MODEL.NUM_CLASSES, M, M])
pred_inmodals = pred_inmodals.reshape([-1, cfg.MODEL.NUM_CLASSES, M, M])
else:
pred_amodals = pred_amodals.reshape([-1, 1, M, M])
pred_inmodals = pred_inmodals.reshape([-1, 1, M, M])
masks_ar = (pred_amodals, pred_inmodals)
return masks_ar
|
Amodal-Instance-Segmentation-through-KINS-Dataset
|
positive
|
def batch_encode_plus(self, batch_text_or_text_pairs=None, add_special_tokens=False, max_length=None, stride=0, truncation_strategy='longest_first', return_tensors=None, return_input_lengths=False, return_attention_masks=False, **kwargs):
"""
Returns a dictionary containing the encoded sequence or sequence pair and additional information:
the mask for sequence classification and the overflowing elements if a ``max_length`` is specified.
Args:
batch_text_or_text_pairs: Batch of sequences or pair of sequences to be encoded.
This can be a list of string/string-sequences/int-sequences or a list of pair of
string/string-sequences/int-sequence (see details in encode_plus)
add_special_tokens: if set to ``True``, the sequences will be encoded with the special tokens relative
to their model.
max_length: if set to a number, will limit the total sequence returned so that it has a maximum length.
If there are overflowing tokens, those will be added to the returned dictionary`
stride: if set to a number along with max_length, the overflowing tokens returned will contain some tokens
from the main sequence returned. The value of this argument defines the number of additional tokens.
truncation_strategy: string selected in the following options:
- 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
starting from the longest one at each token (when there is a pair of input sequences)
- 'only_first': Only truncate the first sequence
- 'only_second': Only truncate the second sequence
- 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length)
return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant
or PyTorch torch.Tensor instead of a list of python integers.
**kwargs: passed to the `self.tokenize()` method
"""
batch_outputs = {}
for ids_or_pair_ids in batch_text_or_text_pairs:
if isinstance(ids_or_pair_ids, (list, tuple)):
assert len(ids_or_pair_ids) == 2
(ids, pair_ids) = ids_or_pair_ids
else:
(ids, pair_ids) = (ids_or_pair_ids, None)
<DeepExtract>
def get_input_ids(text):
if isinstance(ids, str):
outputs = self.convert_tokens_to_ids(self.tokenize(ids, **kwargs))
elif isinstance(ids, (list, tuple)) and len(ids) > 0 and isinstance(ids[0], str):
outputs = self.convert_tokens_to_ids(ids)
elif isinstance(ids, (list, tuple)) and len(ids) > 0 and isinstance(ids[0], int):
outputs = ids
else:
raise ValueError('Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers.')
first_ids = get_input_ids(ids)
second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
outputs = self.prepare_for_model(first_ids, pair_ids=second_ids, max_length=max_length, pad_to_max_length=pad_to_max_length, add_special_tokens=add_special_tokens, stride=stride, truncation_strategy=truncation_strategy, return_tensors=None, return_attention_mask=return_attention_mask, return_token_type_ids=return_token_type_ids, return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask)
</DeepExtract>
if return_input_lengths:
outputs['input_len'] = len(outputs['input_ids'])
for (key, value) in outputs.items():
if key not in batch_outputs:
batch_outputs[key] = []
batch_outputs[key].append(value)
max_seq_len = max(map(len, batch_outputs['input_ids']))
if return_attention_masks:
batch_outputs['attention_mask'] = [[0] * len(v) for v in batch_outputs['input_ids']]
if return_tensors is not None:
for (key, value) in batch_outputs.items():
padded_value = value
if key != 'input_len' and self._pad_token is not None:
padded_value = [v + [self.pad_token_id if key == 'input_ids' else 1] * (max_seq_len - len(v)) for v in padded_value]
if return_tensors == 'tf' and is_tf_available():
batch_outputs[key] = tf.constant(padded_value)
elif return_tensors == 'pt' and is_torch_available():
batch_outputs[key] = torch.tensor(padded_value)
elif return_tensors is not None:
logger.warning('Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.'.format(return_tensors))
if return_attention_masks:
if is_tf_available():
batch_outputs['attention_mask'] = tf.abs(batch_outputs['attention_mask'] - 1)
else:
batch_outputs['attention_mask'] = torch.abs(batch_outputs['attention_mask'] - 1)
return batch_outputs
|
def batch_encode_plus(self, batch_text_or_text_pairs=None, add_special_tokens=False, max_length=None, stride=0, truncation_strategy='longest_first', return_tensors=None, return_input_lengths=False, return_attention_masks=False, **kwargs):
"""
Returns a dictionary containing the encoded sequence or sequence pair and additional information:
the mask for sequence classification and the overflowing elements if a ``max_length`` is specified.
Args:
batch_text_or_text_pairs: Batch of sequences or pair of sequences to be encoded.
This can be a list of string/string-sequences/int-sequences or a list of pair of
string/string-sequences/int-sequence (see details in encode_plus)
add_special_tokens: if set to ``True``, the sequences will be encoded with the special tokens relative
to their model.
max_length: if set to a number, will limit the total sequence returned so that it has a maximum length.
If there are overflowing tokens, those will be added to the returned dictionary`
stride: if set to a number along with max_length, the overflowing tokens returned will contain some tokens
from the main sequence returned. The value of this argument defines the number of additional tokens.
truncation_strategy: string selected in the following options:
- 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
starting from the longest one at each token (when there is a pair of input sequences)
- 'only_first': Only truncate the first sequence
- 'only_second': Only truncate the second sequence
- 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length)
return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant
or PyTorch torch.Tensor instead of a list of python integers.
**kwargs: passed to the `self.tokenize()` method
"""
batch_outputs = {}
for ids_or_pair_ids in batch_text_or_text_pairs:
if isinstance(ids_or_pair_ids, (list, tuple)):
assert len(ids_or_pair_ids) == 2
(ids, pair_ids) = ids_or_pair_ids
else:
(ids, pair_ids) = (ids_or_pair_ids, None)
def get_input_ids(text):
if isinstance(ids, str):
outputs = self.convert_tokens_to_ids(self.tokenize(ids, **kwargs))
elif isinstance(ids, (list, tuple)) and len(ids) > 0 and isinstance(ids[0], str):
outputs = self.convert_tokens_to_ids(ids)
elif isinstance(ids, (list, tuple)) and len(ids) > 0 and isinstance(ids[0], int):
outputs = ids
else:
raise ValueError('Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers.')
first_ids = get_input_ids(ids)
second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
outputs = self.prepare_for_model(first_ids, pair_ids=second_ids, max_length=max_length, pad_to_max_length=pad_to_max_length, add_special_tokens=add_special_tokens, stride=stride, truncation_strategy=truncation_strategy, return_tensors=None, return_attention_mask=return_attention_mask, return_token_type_ids=return_token_type_ids, return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask)
if return_input_lengths:
outputs['input_len'] = len(outputs['input_ids'])
for (key, value) in outputs.items():
if key not in batch_outputs:
batch_outputs[key] = []
batch_outputs[key].append(value)
max_seq_len = max(map(len, batch_outputs['input_ids']))
if return_attention_masks:
batch_outputs['attention_mask'] = [[0] * len(v) for v in batch_outputs['input_ids']]
if return_tensors is not None:
for (key, value) in batch_outputs.items():
padded_value = value
if key != 'input_len' and self._pad_token is not None:
padded_value = [v + [self.pad_token_id if key == 'input_ids' else 1] * (max_seq_len - len(v)) for v in padded_value]
if return_tensors == 'tf' and is_tf_available():
batch_outputs[key] = tf.constant(padded_value)
elif return_tensors == 'pt' and is_torch_available():
batch_outputs[key] = torch.tensor(padded_value)
elif return_tensors is not None:
logger.warning('Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.'.format(return_tensors))
if return_attention_masks:
if is_tf_available():
batch_outputs['attention_mask'] = tf.abs(batch_outputs['attention_mask'] - 1)
else:
batch_outputs['attention_mask'] = torch.abs(batch_outputs['attention_mask'] - 1)
return batch_outputs
|
BERT-Relation-Extraction
|
positive
|
def generate_ring_pattern(image_size, mask=False, mask_radius=10, scale=100, amplitude=1000, spread=2, direct_beam_amplitude=500, asymmetry=1, rotation=0):
"""Calculate a set of rings to model a polycrystalline gold diffraction
pattern for use in fitting for diffraction pattern calibration.
It is suggested that the function generate_ring_pattern is used to
find initial values (initial guess) for the parameters used in
the function fit_ring_pattern.
This function is written expecting a single 2D diffraction pattern
with equal dimensions (e.g. 256x256).
Parameters
----------
mask : bool
Choice of whether to use mask or not (mask=True will return a
specified circular mask setting a region around
the direct beam to zero)
mask_radius : int
The radius in pixels for a mask over the direct beam disc
(the direct beam disc within given radius will be excluded
from the fit)
scale : float
An initial guess for the diffraction calibration
in 1/Angstrom units
image_size : int
Size of the diffraction pattern to be generated in pixels.
amplitude : float
An initial guess for the amplitude of the polycrystalline rings
in arbitrary units
spread : float
An initial guess for the spread within each ring (Gaussian width)
direct_beam_amplitude : float
An initial guess for the background intensity from the
direct beam disc in arbitrary units
asymmetry : float
An initial guess for any elliptical asymmetry in the pattern
(for a perfectly circular pattern asymmetry=1)
rotation : float
An initial guess for the rotation of the (elliptical) pattern
in radians.
Returns
-------
image : np.array()
Simulated ring pattern with the same dimensions as self.data
"""
xi = np.linspace(0, image_size - 1, image_size)
yi = np.linspace(0, image_size - 1, image_size)
(x, y) = np.meshgrid(xi, yi)
pts = np.array([x.ravel(), y.ravel()]).ravel()
xcenter = (image_size - 1) / 2
ycenter = (image_size - 1) / 2
<DeepExtract>
def ring_pattern(pts, scale, amplitude, spread, direct_beam_amplitude, asymmetry, rotation):
"""Calculates a polycrystalline gold diffraction pattern given a set of
pixel coordinates (points). It uses tabulated values of the spacings
(in reciprocal Angstroms) and relative intensities of rings derived from
X-ray scattering factors.
Parameters
-----------
pts : 1D array
One-dimensional array of points (first half as first-dimension
coordinates, second half as second-dimension coordinates)
scale : float
An initial guess for the diffraction calibration
in 1/Angstrom units
amplitude : float
An initial guess for the amplitude of the polycrystalline rings
in arbitrary units
spread : float
An initial guess for the spread within each ring (Gaussian width)
direct_beam_amplitude : float
An initial guess for the background intensity from
the direct beam disc in arbitrary units
asymmetry : float
An initial guess for any elliptical asymmetry in the pattern
(for a perfectly circular pattern asymmetry=1)
rotation : float
An initial guess for the rotation of the (elliptical) pattern
in radians.
Returns
-------
ring_pattern : np.array()
A one-dimensional array of the intensities of the ring pattern
at the supplied points.
"""
rings = [0.4247, 0.4904, 0.6935, 0.8132, 0.8494, 0.9808, 1.0688, 1.0966]
rings = np.multiply(rings, scale)
amps = [1, 0.44, 0.19, 0.16, 0.04, 0.014, 0.038, 0.036]
x = pts[:round(np.size(pts, 0) / 2)]
y = pts[round(np.size(pts, 0) / 2):]
Ri = calc_radius_with_distortion(x, y, xcenter, ycenter, asymmetry, rotation)
v = []
denom = 2 * spread ** 2
v.append(direct_beam_amplitude * Ri ** (-2))
for i in [0, 1, 2, 3, 4, 5, 6, 7]:
v.append(amps[i] * np.exp(-1 * (Ri - rings[i]) * (Ri - rings[i]) / denom))
ring_pattern = amplitude * (v[0] + v[1] + v[2] + v[3] + v[4] + v[5] + v[6] + v[7] + v[8]).ravel()
ring_pattern = ring_pattern
</DeepExtract>
<DeepExtract>
rings = [0.4247, 0.4904, 0.6935, 0.8132, 0.8494, 0.9808, 1.0688, 1.0966]
rings = np.multiply(rings, scale)
amps = [1, 0.44, 0.19, 0.16, 0.04, 0.014, 0.038, 0.036]
x = pts[:round(np.size(pts, 0) / 2)]
y = pts[round(np.size(pts, 0) / 2):]
Ri = calc_radius_with_distortion(x, y, xcenter, ycenter, asymmetry, rotation)
v = []
denom = 2 * spread ** 2
v.append(direct_beam_amplitude * Ri ** (-2))
for i in [0, 1, 2, 3, 4, 5, 6, 7]:
v.append(amps[i] * np.exp(-1 * (Ri - rings[i]) * (Ri - rings[i]) / denom))
generated_pattern = amplitude * (v[0] + v[1] + v[2] + v[3] + v[4] + v[5] + v[6] + v[7] + v[8]).ravel()
</DeepExtract>
generated_pattern = np.reshape(generated_pattern, (image_size, image_size))
if mask == True:
<DeepExtract>
xp = x * np.cos(0) - y * np.sin(0)
yp = x * np.sin(0) + y * np.cos(0)
xcp = (image_size - 1) / 2 * np.cos(0) - (image_size - 1) / 2 * np.sin(0)
ycp = (image_size - 1) / 2 * np.sin(0) + (image_size - 1) / 2 * np.cos(0)
maskROI = np.sqrt((xp - xcp) ** 2 + 1 * (yp - ycp) ** 2)
</DeepExtract>
maskROI[maskROI > mask_radius] = 0
generated_pattern[maskROI > 0] *= 0
return generated_pattern
|
def generate_ring_pattern(image_size, mask=False, mask_radius=10, scale=100, amplitude=1000, spread=2, direct_beam_amplitude=500, asymmetry=1, rotation=0):
"""Calculate a set of rings to model a polycrystalline gold diffraction
pattern for use in fitting for diffraction pattern calibration.
It is suggested that the function generate_ring_pattern is used to
find initial values (initial guess) for the parameters used in
the function fit_ring_pattern.
This function is written expecting a single 2D diffraction pattern
with equal dimensions (e.g. 256x256).
Parameters
----------
mask : bool
Choice of whether to use mask or not (mask=True will return a
specified circular mask setting a region around
the direct beam to zero)
mask_radius : int
The radius in pixels for a mask over the direct beam disc
(the direct beam disc within given radius will be excluded
from the fit)
scale : float
An initial guess for the diffraction calibration
in 1/Angstrom units
image_size : int
Size of the diffraction pattern to be generated in pixels.
amplitude : float
An initial guess for the amplitude of the polycrystalline rings
in arbitrary units
spread : float
An initial guess for the spread within each ring (Gaussian width)
direct_beam_amplitude : float
An initial guess for the background intensity from the
direct beam disc in arbitrary units
asymmetry : float
An initial guess for any elliptical asymmetry in the pattern
(for a perfectly circular pattern asymmetry=1)
rotation : float
An initial guess for the rotation of the (elliptical) pattern
in radians.
Returns
-------
image : np.array()
Simulated ring pattern with the same dimensions as self.data
"""
xi = np.linspace(0, image_size - 1, image_size)
yi = np.linspace(0, image_size - 1, image_size)
(x, y) = np.meshgrid(xi, yi)
pts = np.array([x.ravel(), y.ravel()]).ravel()
xcenter = (image_size - 1) / 2
ycenter = (image_size - 1) / 2
def ring_pattern(pts, scale, amplitude, spread, direct_beam_amplitude, asymmetry, rotation):
"""Calculates a polycrystalline gold diffraction pattern given a set of
pixel coordinates (points). It uses tabulated values of the spacings
(in reciprocal Angstroms) and relative intensities of rings derived from
X-ray scattering factors.
Parameters
-----------
pts : 1D array
One-dimensional array of points (first half as first-dimension
coordinates, second half as second-dimension coordinates)
scale : float
An initial guess for the diffraction calibration
in 1/Angstrom units
amplitude : float
An initial guess for the amplitude of the polycrystalline rings
in arbitrary units
spread : float
An initial guess for the spread within each ring (Gaussian width)
direct_beam_amplitude : float
An initial guess for the background intensity from
the direct beam disc in arbitrary units
asymmetry : float
An initial guess for any elliptical asymmetry in the pattern
(for a perfectly circular pattern asymmetry=1)
rotation : float
An initial guess for the rotation of the (elliptical) pattern
in radians.
Returns
-------
ring_pattern : np.array()
A one-dimensional array of the intensities of the ring pattern
at the supplied points.
"""
rings = [0.4247, 0.4904, 0.6935, 0.8132, 0.8494, 0.9808, 1.0688, 1.0966]
rings = np.multiply(rings, scale)
amps = [1, 0.44, 0.19, 0.16, 0.04, 0.014, 0.038, 0.036]
x = pts[:round(np.size(pts, 0) / 2)]
y = pts[round(np.size(pts, 0) / 2):]
Ri = calc_radius_with_distortion(x, y, xcenter, ycenter, asymmetry, rotation)
v = []
denom = 2 * spread ** 2
v.append(direct_beam_amplitude * Ri ** (-2))
for i in [0, 1, 2, 3, 4, 5, 6, 7]:
v.append(amps[i] * np.exp(-1 * (Ri - rings[i]) * (Ri - rings[i]) / denom))
ring_pattern = amplitude * (v[0] + v[1] + v[2] + v[3] + v[4] + v[5] + v[6] + v[7] + v[8]).ravel()
ring_pattern = ring_pattern
rings = [0.4247, 0.4904, 0.6935, 0.8132, 0.8494, 0.9808, 1.0688, 1.0966]
rings = np.multiply(rings, scale)
amps = [1, 0.44, 0.19, 0.16, 0.04, 0.014, 0.038, 0.036]
x = pts[:round(np.size(pts, 0) / 2)]
y = pts[round(np.size(pts, 0) / 2):]
Ri = calc_radius_with_distortion(x, y, xcenter, ycenter, asymmetry, rotation)
v = []
denom = 2 * spread ** 2
v.append(direct_beam_amplitude * Ri ** (-2))
for i in [0, 1, 2, 3, 4, 5, 6, 7]:
v.append(amps[i] * np.exp(-1 * (Ri - rings[i]) * (Ri - rings[i]) / denom))
generated_pattern = amplitude * (v[0] + v[1] + v[2] + v[3] + v[4] + v[5] + v[6] + v[7] + v[8]).ravel()
generated_pattern = np.reshape(generated_pattern, (image_size, image_size))
if mask == True:
xp = x * np.cos(0) - y * np.sin(0)
yp = x * np.sin(0) + y * np.cos(0)
xcp = (image_size - 1) / 2 * np.cos(0) - (image_size - 1) / 2 * np.sin(0)
ycp = (image_size - 1) / 2 * np.sin(0) + (image_size - 1) / 2 * np.cos(0)
maskROI = np.sqrt((xp - xcp) ** 2 + 1 * (yp - ycp) ** 2)
maskROI[maskROI > mask_radius] = 0
generated_pattern[maskROI > 0] *= 0
return generated_pattern
|
diffsims
|
positive
|
@multi_score_ex.named_config
def noise_adversary_actions(score):
score = dict(score)
<DeepExtract>
score['index_keys'] = ['noisy_agent_magnitude', 'noisy_agent_index']
spec = {'num_samples': 25, 'config': {'noisy_agent_magnitude': tune.sample_from(lambda spec: np.random.lognormal(mean=0.5, sigma=1.5))}}
</DeepExtract>
spec['config']['noisy_agent_index'] = tune.sample_from(lambda spec: 1 - VICTIM_INDEX[spec.config[PATHS_AND_TYPES][0]])
exp_prefix = {'adversary_action_noise': None}
|
@multi_score_ex.named_config
def noise_adversary_actions(score):
score = dict(score)
score['index_keys'] = ['noisy_agent_magnitude', 'noisy_agent_index']
spec = {'num_samples': 25, 'config': {'noisy_agent_magnitude': tune.sample_from(lambda spec: np.random.lognormal(mean=0.5, sigma=1.5))}}
spec['config']['noisy_agent_index'] = tune.sample_from(lambda spec: 1 - VICTIM_INDEX[spec.config[PATHS_AND_TYPES][0]])
exp_prefix = {'adversary_action_noise': None}
|
adversarial-policies
|
positive
|
def _get_data(self):
"""Load frame paths and annotations. """
list_filenames = [os.path.join(cfg.EPIC.FRAME_LIST_DIR, filename) for filename in (cfg.EPIC.TRAIN_LISTS if self._is_train or cfg.GET_TRAIN_LFB else cfg.EPIC.TEST_LISTS)]
(self._image_paths, self._image_labels, self._video_idx_to_name, self._video_name_to_idx) = dataset_helper.load_image_lists(list_filenames, return_dict=True)
if self._lfb_infer_only:
<DeepExtract>
annotations = []
sample_freq = FPS // cfg.EPIC.VERB_LFB_CLIPS_PER_SECOND
for video_name in self._image_paths.keys():
for img_path in self._image_paths[video_name]:
frame = filename_to_frame_id(img_path)
if frame % sample_freq == 0:
annotations.append((video_name[:3], video_name, frame, frame, 0, 0))
self._annotations = annotations
</DeepExtract>
logger.info('Inferring LFB from %d clips in %d videos.' % (len(self._annotations), len(self._image_paths)))
else:
<DeepExtract>
annotations = []
verb_set = set()
noun_set = set()
filename = os.path.join(cfg.EPIC.ANNOTATION_DIR, cfg.EPIC.ANNOTATIONS)
with open(filename, 'rb') as f:
f.readline()
reader = csv.reader(f)
for row in reader:
person = row[1]
if self._is_train:
if int(person[1:]) not in TRAIN_PERSON_INDICES:
continue
elif int(person[1:]) in TRAIN_PERSON_INDICES:
continue
video_name = row[2]
start_frame = sec_to_frame(time_to_sec(row[4]))
stop_frame = sec_to_frame(time_to_sec(row[5]))
verb = int(row[-5])
noun = int(row[-3])
assert verb < NUM_CLASSES_VERB, verb
assert verb >= 0, verb
assert noun < NUM_CLASSES_NOUN, noun
assert noun >= 0, noun
annotations.append((person, video_name, start_frame, stop_frame, verb, noun))
verb_set.add(verb)
noun_set.add(noun)
logger.info('See %d verbs and %d nouns in the dataset loaded.' % (len(verb_set), len(noun_set)))
cur_label_set = verb_set if cfg.EPIC.CLASS_TYPE == 'verb' else noun_set
if len(cur_label_set) != cfg.MODEL.NUM_CLASSES:
logger.warn('# classes seen (%d) != MODEL.NUM_CLASSES' % len(cur_label_set))
assert len(annotations) == (cfg.TRAIN.DATASET_SIZE if self._is_train else cfg.TEST.DATASET_SIZE)
self._annotations = annotations
</DeepExtract>
<DeepExtract>
logger.info('=== EPIC Kitchens dataset summary ===')
logger.info('Split: {}'.format(self._split))
logger.info('Use LFB? {}'.format(self._lfb_enabled))
logger.info('Spatial shift position: {}'.format(self._shift))
logger.info('Number of videos: {}'.format(len(self._image_paths)))
total_frames = sum((len(video_img_paths) for video_img_paths in self._image_paths.values()))
logger.info('Number of frames: {}'.format(total_frames))
logger.info('Number of annotations: {}'.format(len(self._annotations)))
</DeepExtract>
|
def _get_data(self):
"""Load frame paths and annotations. """
list_filenames = [os.path.join(cfg.EPIC.FRAME_LIST_DIR, filename) for filename in (cfg.EPIC.TRAIN_LISTS if self._is_train or cfg.GET_TRAIN_LFB else cfg.EPIC.TEST_LISTS)]
(self._image_paths, self._image_labels, self._video_idx_to_name, self._video_name_to_idx) = dataset_helper.load_image_lists(list_filenames, return_dict=True)
if self._lfb_infer_only:
annotations = []
sample_freq = FPS // cfg.EPIC.VERB_LFB_CLIPS_PER_SECOND
for video_name in self._image_paths.keys():
for img_path in self._image_paths[video_name]:
frame = filename_to_frame_id(img_path)
if frame % sample_freq == 0:
annotations.append((video_name[:3], video_name, frame, frame, 0, 0))
self._annotations = annotations
logger.info('Inferring LFB from %d clips in %d videos.' % (len(self._annotations), len(self._image_paths)))
else:
annotations = []
verb_set = set()
noun_set = set()
filename = os.path.join(cfg.EPIC.ANNOTATION_DIR, cfg.EPIC.ANNOTATIONS)
with open(filename, 'rb') as f:
f.readline()
reader = csv.reader(f)
for row in reader:
person = row[1]
if self._is_train:
if int(person[1:]) not in TRAIN_PERSON_INDICES:
continue
elif int(person[1:]) in TRAIN_PERSON_INDICES:
continue
video_name = row[2]
start_frame = sec_to_frame(time_to_sec(row[4]))
stop_frame = sec_to_frame(time_to_sec(row[5]))
verb = int(row[-5])
noun = int(row[-3])
assert verb < NUM_CLASSES_VERB, verb
assert verb >= 0, verb
assert noun < NUM_CLASSES_NOUN, noun
assert noun >= 0, noun
annotations.append((person, video_name, start_frame, stop_frame, verb, noun))
verb_set.add(verb)
noun_set.add(noun)
logger.info('See %d verbs and %d nouns in the dataset loaded.' % (len(verb_set), len(noun_set)))
cur_label_set = verb_set if cfg.EPIC.CLASS_TYPE == 'verb' else noun_set
if len(cur_label_set) != cfg.MODEL.NUM_CLASSES:
logger.warn('# classes seen (%d) != MODEL.NUM_CLASSES' % len(cur_label_set))
assert len(annotations) == (cfg.TRAIN.DATASET_SIZE if self._is_train else cfg.TEST.DATASET_SIZE)
self._annotations = annotations
logger.info('=== EPIC Kitchens dataset summary ===')
logger.info('Split: {}'.format(self._split))
logger.info('Use LFB? {}'.format(self._lfb_enabled))
logger.info('Spatial shift position: {}'.format(self._shift))
logger.info('Number of videos: {}'.format(len(self._image_paths)))
total_frames = sum((len(video_img_paths) for video_img_paths in self._image_paths.values()))
logger.info('Number of frames: {}'.format(total_frames))
logger.info('Number of annotations: {}'.format(len(self._annotations)))
</DeepExtract>
|
CRCNN-Action
|
positive
|
def forward(self, x=None, ref_scribble_label=None, previous_frame_mask=None, normalize_nearest_neighbor_distances=True, use_local_map=True, seq_names=None, gt_ids=None, k_nearest_neighbors=1, global_map_tmp_dic=None, local_map_dics=None, interaction_num=None, start_annotated_frame=None, frame_num=None):
<DeepExtract>
x = self.feature_extracter(x)
x = self.semantic_embedding(x)
x = x
</DeepExtract>
(ref_frame_embedding, previous_frame_embedding, current_frame_embedding) = torch.split(x, split_size_or_sections=int(x.size(0) / 3), dim=0)
<DeepExtract>
global_map_tmp_dic = global_map_tmp_dic
dic_tmp = {}
(bs, c, h, w) = current_frame_embedding.size()
scale_ref_scribble_label = torch.nn.functional.interpolate(ref_scribble_label.float(), size=(h, w), mode='nearest')
scale_ref_scribble_label = scale_ref_scribble_label.int()
scale_previous_frame_label = torch.nn.functional.interpolate(previous_frame_mask.float(), size=(h, w), mode='nearest')
scale_previous_frame_label = scale_previous_frame_label.int()
if USE_CORRELATION_COST:
n_chunks = 20
else:
n_chunks = 500
for n in range(bs):
seq_current_frame_embedding = current_frame_embedding[n]
seq_ref_frame_embedding = ref_frame_embedding[n]
seq_prev_frame_embedding = previous_frame_embedding[n]
seq_ref_frame_embedding = seq_ref_frame_embedding.permute(1, 2, 0)
seq_current_frame_embedding = seq_current_frame_embedding.permute(1, 2, 0)
seq_ref_scribble_label = scale_ref_scribble_label[n].permute(1, 2, 0)
(nn_features_n, ref_obj_ids) = nearest_neighbor_features_per_object(reference_embeddings=seq_ref_frame_embedding, query_embeddings=seq_current_frame_embedding, reference_labels=seq_ref_scribble_label, k_nearest_neighbors=k_nearest_neighbors, gt_ids=gt_ids[n], n_chunks=20)
if normalize_nearest_neighbor_distances:
nn_features_n = (torch.sigmoid(nn_features_n) - 0.5) * 2
if seq_names[n] not in global_map_tmp_dic:
global_map_tmp_dic[seq_names[n]] = torch.ones_like(nn_features_n).repeat(104, 1, 1, 1, 1)
if torch.cuda.is_available():
global_map_tmp_dic[seq_names[n]] = global_map_tmp_dic[seq_names[n]].cuda()
nn_features_n = torch.where(nn_features_n <= global_map_tmp_dic[seq_names[n]][frame_num[n]].unsqueeze(0), nn_features_n, global_map_tmp_dic[seq_names[n]][frame_num[n]].unsqueeze(0))
global_map_tmp_dic[seq_names[n]][frame_num[n]] = nn_features_n.detach()
seq_prev_frame_embedding = seq_prev_frame_embedding.permute(1, 2, 0)
seq_previous_frame_label = scale_previous_frame_label[n].permute(1, 2, 0)
if use_local_map:
prev_frame_nn_features_n = local_previous_frame_nearest_neighbor_features_per_object(prev_frame_embedding=seq_prev_frame_embedding, query_embedding=seq_current_frame_embedding, prev_frame_labels=seq_previous_frame_label, gt_ids=ref_obj_ids, max_distance=15)
else:
(prev_frame_nn_features_n, _) = nearest_neighbor_features_per_object(reference_embeddings=seq_prev_frame_embedding, query_embeddings=seq_current_frame_embedding, reference_labels=seq_previous_frame_label, k_nearest_neighbors=k_nearest_neighbors, gt_ids=gt_ids[n], n_chunks=20)
prev_frame_nn_features_n = (torch.sigmoid(prev_frame_nn_features_n) - 0.5) * 2
if local_map_dics is not None:
(local_map_tmp_dic, local_map_dist_dic) = local_map_dics
if seq_names[n] not in local_map_dist_dic:
local_map_dist_dic[seq_names[n]] = torch.zeros(104, 9)
if torch.cuda.is_available():
local_map_dist_dic[seq_names[n]] = local_map_dist_dic[seq_names[n]].cuda()
if seq_names[n] not in local_map_tmp_dic:
local_map_tmp_dic[seq_names[n]] = torch.zeros_like(prev_frame_nn_features_n).unsqueeze(0).repeat(104, 9, 1, 1, 1, 1)
if torch.cuda.is_available():
local_map_tmp_dic[seq_names[n]] = local_map_tmp_dic[seq_names[n]].cuda()
local_map_dist_dic[seq_names[n]][frame_num[n]][interaction_num - 1] = 1.0 / abs(frame_num[n] - start_annotated_frame)
local_map_tmp_dic[seq_names[n]][frame_num[n]][interaction_num - 1] = prev_frame_nn_features_n.squeeze(0).detach()
if interaction_num == 1:
prev_frame_nn_features_n = local_map_tmp_dic[seq_names[n]][frame_num[n]][interaction_num - 1]
prev_frame_nn_features_n = prev_frame_nn_features_n.unsqueeze(0)
elif local_map_dist_dic[seq_names[n]][frame_num[n]][interaction_num - 1] > local_map_dist_dic[seq_names[n]][frame_num[n]][interaction_num - 2]:
prev_frame_nn_features_n = local_map_tmp_dic[seq_names[n]][frame_num[n]][interaction_num - 1]
prev_frame_nn_features_n = prev_frame_nn_features_n.unsqueeze(0)
else:
prev_frame_nn_features_n = local_map_tmp_dic[seq_names[n]][frame_num[n]][interaction_num - 2]
prev_frame_nn_features_n = prev_frame_nn_features_n.unsqueeze(0)
local_map_dics = (local_map_tmp_dic, local_map_dist_dic)
previous_frame_to_cat = seq_previous_frame_label.float() == ref_obj_ids.float()
to_cat_current_frame_embedding = current_frame_embedding[n].unsqueeze(0).repeat((ref_obj_ids.size(0), 1, 1, 1))
to_cat_nn_feature_n = nn_features_n.squeeze(0).permute(2, 3, 0, 1)
to_cat_previous_frame = previous_frame_to_cat.unsqueeze(-1).permute(2, 3, 0, 1).float()
to_cat_prev_frame_nn_feature_n = prev_frame_nn_features_n.squeeze(0).permute(2, 3, 0, 1)
to_cat = torch.cat((to_cat_current_frame_embedding, to_cat_nn_feature_n, to_cat_prev_frame_nn_feature_n, to_cat_previous_frame), 1)
pred_ = self.dynamic_seghead(to_cat)
pred_ = pred_.permute(1, 0, 2, 3)
dic_tmp[seq_names[n]] = pred_
if local_map_dics is None:
(dic, global_map_tmp_dic) = (dic_tmp, global_map_tmp_dic)
else:
(dic, global_map_tmp_dic) = (dic_tmp, global_map_tmp_dic, local_map_dics)
</DeepExtract>
return (dic, global_map_tmp_dic)
|
def forward(self, x=None, ref_scribble_label=None, previous_frame_mask=None, normalize_nearest_neighbor_distances=True, use_local_map=True, seq_names=None, gt_ids=None, k_nearest_neighbors=1, global_map_tmp_dic=None, local_map_dics=None, interaction_num=None, start_annotated_frame=None, frame_num=None):
x = self.feature_extracter(x)
x = self.semantic_embedding(x)
x = x
(ref_frame_embedding, previous_frame_embedding, current_frame_embedding) = torch.split(x, split_size_or_sections=int(x.size(0) / 3), dim=0)
global_map_tmp_dic = global_map_tmp_dic
dic_tmp = {}
(bs, c, h, w) = current_frame_embedding.size()
scale_ref_scribble_label = torch.nn.functional.interpolate(ref_scribble_label.float(), size=(h, w), mode='nearest')
scale_ref_scribble_label = scale_ref_scribble_label.int()
scale_previous_frame_label = torch.nn.functional.interpolate(previous_frame_mask.float(), size=(h, w), mode='nearest')
scale_previous_frame_label = scale_previous_frame_label.int()
if USE_CORRELATION_COST:
n_chunks = 20
else:
n_chunks = 500
for n in range(bs):
seq_current_frame_embedding = current_frame_embedding[n]
seq_ref_frame_embedding = ref_frame_embedding[n]
seq_prev_frame_embedding = previous_frame_embedding[n]
seq_ref_frame_embedding = seq_ref_frame_embedding.permute(1, 2, 0)
seq_current_frame_embedding = seq_current_frame_embedding.permute(1, 2, 0)
seq_ref_scribble_label = scale_ref_scribble_label[n].permute(1, 2, 0)
(nn_features_n, ref_obj_ids) = nearest_neighbor_features_per_object(reference_embeddings=seq_ref_frame_embedding, query_embeddings=seq_current_frame_embedding, reference_labels=seq_ref_scribble_label, k_nearest_neighbors=k_nearest_neighbors, gt_ids=gt_ids[n], n_chunks=20)
if normalize_nearest_neighbor_distances:
nn_features_n = (torch.sigmoid(nn_features_n) - 0.5) * 2
if seq_names[n] not in global_map_tmp_dic:
global_map_tmp_dic[seq_names[n]] = torch.ones_like(nn_features_n).repeat(104, 1, 1, 1, 1)
if torch.cuda.is_available():
global_map_tmp_dic[seq_names[n]] = global_map_tmp_dic[seq_names[n]].cuda()
nn_features_n = torch.where(nn_features_n <= global_map_tmp_dic[seq_names[n]][frame_num[n]].unsqueeze(0), nn_features_n, global_map_tmp_dic[seq_names[n]][frame_num[n]].unsqueeze(0))
global_map_tmp_dic[seq_names[n]][frame_num[n]] = nn_features_n.detach()
seq_prev_frame_embedding = seq_prev_frame_embedding.permute(1, 2, 0)
seq_previous_frame_label = scale_previous_frame_label[n].permute(1, 2, 0)
if use_local_map:
prev_frame_nn_features_n = local_previous_frame_nearest_neighbor_features_per_object(prev_frame_embedding=seq_prev_frame_embedding, query_embedding=seq_current_frame_embedding, prev_frame_labels=seq_previous_frame_label, gt_ids=ref_obj_ids, max_distance=15)
else:
(prev_frame_nn_features_n, _) = nearest_neighbor_features_per_object(reference_embeddings=seq_prev_frame_embedding, query_embeddings=seq_current_frame_embedding, reference_labels=seq_previous_frame_label, k_nearest_neighbors=k_nearest_neighbors, gt_ids=gt_ids[n], n_chunks=20)
prev_frame_nn_features_n = (torch.sigmoid(prev_frame_nn_features_n) - 0.5) * 2
if local_map_dics is not None:
(local_map_tmp_dic, local_map_dist_dic) = local_map_dics
if seq_names[n] not in local_map_dist_dic:
local_map_dist_dic[seq_names[n]] = torch.zeros(104, 9)
if torch.cuda.is_available():
local_map_dist_dic[seq_names[n]] = local_map_dist_dic[seq_names[n]].cuda()
if seq_names[n] not in local_map_tmp_dic:
local_map_tmp_dic[seq_names[n]] = torch.zeros_like(prev_frame_nn_features_n).unsqueeze(0).repeat(104, 9, 1, 1, 1, 1)
if torch.cuda.is_available():
local_map_tmp_dic[seq_names[n]] = local_map_tmp_dic[seq_names[n]].cuda()
local_map_dist_dic[seq_names[n]][frame_num[n]][interaction_num - 1] = 1.0 / abs(frame_num[n] - start_annotated_frame)
local_map_tmp_dic[seq_names[n]][frame_num[n]][interaction_num - 1] = prev_frame_nn_features_n.squeeze(0).detach()
if interaction_num == 1:
prev_frame_nn_features_n = local_map_tmp_dic[seq_names[n]][frame_num[n]][interaction_num - 1]
prev_frame_nn_features_n = prev_frame_nn_features_n.unsqueeze(0)
elif local_map_dist_dic[seq_names[n]][frame_num[n]][interaction_num - 1] > local_map_dist_dic[seq_names[n]][frame_num[n]][interaction_num - 2]:
prev_frame_nn_features_n = local_map_tmp_dic[seq_names[n]][frame_num[n]][interaction_num - 1]
prev_frame_nn_features_n = prev_frame_nn_features_n.unsqueeze(0)
else:
prev_frame_nn_features_n = local_map_tmp_dic[seq_names[n]][frame_num[n]][interaction_num - 2]
prev_frame_nn_features_n = prev_frame_nn_features_n.unsqueeze(0)
local_map_dics = (local_map_tmp_dic, local_map_dist_dic)
previous_frame_to_cat = seq_previous_frame_label.float() == ref_obj_ids.float()
to_cat_current_frame_embedding = current_frame_embedding[n].unsqueeze(0).repeat((ref_obj_ids.size(0), 1, 1, 1))
to_cat_nn_feature_n = nn_features_n.squeeze(0).permute(2, 3, 0, 1)
to_cat_previous_frame = previous_frame_to_cat.unsqueeze(-1).permute(2, 3, 0, 1).float()
to_cat_prev_frame_nn_feature_n = prev_frame_nn_features_n.squeeze(0).permute(2, 3, 0, 1)
to_cat = torch.cat((to_cat_current_frame_embedding, to_cat_nn_feature_n, to_cat_prev_frame_nn_feature_n, to_cat_previous_frame), 1)
pred_ = self.dynamic_seghead(to_cat)
pred_ = pred_.permute(1, 0, 2, 3)
dic_tmp[seq_names[n]] = pred_
if local_map_dics is None:
(dic, global_map_tmp_dic) = (dic_tmp, global_map_tmp_dic)
else:
(dic, global_map_tmp_dic) = (dic_tmp, global_map_tmp_dic, local_map_dics)
return (dic, global_map_tmp_dic)
|
CVPR2020_MANet
|
positive
|
def link_objects_to_collection(ref, col):
<DeepExtract>
objref = []
if ref is None:
objref = so()
elif isinstance(ref, list):
if len(ref) > 0:
if isinstance(ref[0], bpy.types.Object):
objref = ref
elif isinstance(ref[0], str):
for ob_name in ref:
if object_exists(ob_name):
objref.append(bpy.data.objects[ob_name])
elif is_string(ref):
if object_exists(ref):
objref.append(bpy.data.objects[ref])
elif isinstance(ref, bpy.types.Object):
objref.append(ref)
objs = objref
</DeepExtract>
if is_string(col):
for o in objs:
bpy.data.collections[col].objects.link(o)
else:
for o in objs:
col.objects.link(o)
|
def link_objects_to_collection(ref, col):
objref = []
if ref is None:
objref = so()
elif isinstance(ref, list):
if len(ref) > 0:
if isinstance(ref[0], bpy.types.Object):
objref = ref
elif isinstance(ref[0], str):
for ob_name in ref:
if object_exists(ob_name):
objref.append(bpy.data.objects[ob_name])
elif is_string(ref):
if object_exists(ref):
objref.append(bpy.data.objects[ref])
elif isinstance(ref, bpy.types.Object):
objref.append(ref)
objs = objref
if is_string(col):
for o in objs:
bpy.data.collections[col].objects.link(o)
else:
for o in objs:
col.objects.link(o)
|
EasyBPY
|
positive
|
def validate(self, bug: Bug, verbose: bool=True) -> bool:
"""
Checks that a given bug successfully builds, and that it produces an
expected set of test suite outcomes.
Parameters:
verbose: toggles verbosity of output. If set to `True`, the
outcomes of each test will be printed to the standard output.
Returns:
`True` if bug behaves as expected, else `False`.
"""
try:
<DeepExtract>
self.__installation.build.build(bug.image, force=True, quiet=True)
</DeepExtract>
except docker.errors.BuildError:
print('failed to build bug: {}'.format(self.identifier))
return False
validated = True
try:
c = None
c = self.__installation.containers.provision(bug)
print_task_start('Compiling')
self.__installation.containers.compile(c)
print_task_end('Compiling', 'OK')
for t in bug.tests:
if t.expected_outcome is True:
task = 'Running test: {}'.format(t.name)
print_task_start(task)
outcome = self.__installation.containers.execute(c, t, verbose=verbose)
if not outcome.passed:
validated = False
print_task_end(task, 'UNEXPECTED: FAIL')
response = textwrap.indent(outcome.response.output, ' ' * 4)
print('\n' + response)
else:
print_task_end(task, 'OK')
if t.expected_outcome is False:
task = 'Running test: {}'.format(t.name)
print_task_start(task)
outcome = self.__installation.containers.execute(c, t, verbose=verbose)
if outcome.passed:
validated = False
print_task_end(task, 'UNEXPECTED: PASS')
response = textwrap.indent(outcome.response.output, ' ' * 4)
print('\n' + response)
else:
print_task_end(task, 'OK')
finally:
if c:
del self.__installation.containers[c.uid]
return validated
|
def validate(self, bug: Bug, verbose: bool=True) -> bool:
"""
Checks that a given bug successfully builds, and that it produces an
expected set of test suite outcomes.
Parameters:
verbose: toggles verbosity of output. If set to `True`, the
outcomes of each test will be printed to the standard output.
Returns:
`True` if bug behaves as expected, else `False`.
"""
try:
self.__installation.build.build(bug.image, force=True, quiet=True)
except docker.errors.BuildError:
print('failed to build bug: {}'.format(self.identifier))
return False
validated = True
try:
c = None
c = self.__installation.containers.provision(bug)
print_task_start('Compiling')
self.__installation.containers.compile(c)
print_task_end('Compiling', 'OK')
for t in bug.tests:
if t.expected_outcome is True:
task = 'Running test: {}'.format(t.name)
print_task_start(task)
outcome = self.__installation.containers.execute(c, t, verbose=verbose)
if not outcome.passed:
validated = False
print_task_end(task, 'UNEXPECTED: FAIL')
response = textwrap.indent(outcome.response.output, ' ' * 4)
print('\n' + response)
else:
print_task_end(task, 'OK')
if t.expected_outcome is False:
task = 'Running test: {}'.format(t.name)
print_task_start(task)
outcome = self.__installation.containers.execute(c, t, verbose=verbose)
if outcome.passed:
validated = False
print_task_end(task, 'UNEXPECTED: PASS')
response = textwrap.indent(outcome.response.output, ' ' * 4)
print('\n' + response)
else:
print_task_end(task, 'OK')
finally:
if c:
del self.__installation.containers[c.uid]
return validated
|
BugZoo
|
positive
|
def die_unless_type_or_types_issubclassable(type_or_types: TypeOrTupleTypes, exception_cls: TypeException=BeartypeDecorHintPep3119Exception, exception_prefix: str='') -> None:
"""
Raise an exception of the passed type unless the passed object is either an
**issubclassable class** (i.e., class whose metaclass does *not* define an
``__subclasscheck__()`` dunder method that raises a :exc:`TypeError`
exception) *or* tuple of one or more issubclassable classes.
Parameters
----------
type_or_types : object
Object to be validated.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep3119Exception`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`BeartypeDecorHintPep3119Exception`
If this object is neither:
* An issubclassable class.
* A tuple containing only issubclassable classes.
"""
from beartype._util.cls.utilclstest import die_unless_type_or_types
die_unless_type_or_types(type_or_types=type_or_types, exception_cls=exception_cls, exception_prefix=exception_prefix)
if isinstance(type_or_types, type):
<DeepExtract>
from beartype._util.cls.utilclstest import die_unless_type
die_unless_type(cls=type_or_types, exception_cls=exception_cls, exception_prefix=exception_prefix)
try:
issubclass(type, type_or_types)
except TypeError as exception:
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not exception class.'
assert isinstance(exception_prefix, str), f'{repr(exception_prefix)} not string.'
exception_message = f'{exception_prefix}{repr(type_or_types)} uncheckable at runtime (i.e., not passable as second parameter to issubclass(), due to raising "{exception.__class__.__name__}: {exception}" from metaclass __subclasscheck__() method).'
raise exception_cls(exception_message) from exception
except Exception:
pass
</DeepExtract>
else:
try:
issubclass(type, type_or_types)
except TypeError as exception:
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not exception class.'
assert isinstance(exception_prefix, str), f'{repr(exception_prefix)} not string.'
exception_message = f'{exception_prefix}{repr(type_or_types)} uncheckable at runtime'
for (cls_index, cls) in enumerate(type_or_types):
<DeepExtract>
from beartype._util.cls.utilclstest import die_unless_type
die_unless_type(cls=cls, exception_cls=exception_cls, exception_prefix=f'{exception_message}, as tuple item {cls_index} ')
try:
issubclass(type, cls)
except TypeError as exception:
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not exception class.'
assert isinstance(f'{exception_message}, as tuple item {cls_index} ', str), f"{repr(f'{exception_message}, as tuple item {cls_index} ')} not string."
exception_message = f'''{f'{exception_message}, as tuple item {cls_index} '}{repr(cls)} uncheckable at runtime (i.e., not passable as second parameter to issubclass(), due to raising "{exception.__class__.__name__}: {exception}" from metaclass __subclasscheck__() method).'''
raise exception_cls(exception_message) from exception
except Exception:
pass
</DeepExtract>
raise exception_cls(f'{exception_message}.') from exception
except Exception:
pass
|
def die_unless_type_or_types_issubclassable(type_or_types: TypeOrTupleTypes, exception_cls: TypeException=BeartypeDecorHintPep3119Exception, exception_prefix: str='') -> None:
"""
Raise an exception of the passed type unless the passed object is either an
**issubclassable class** (i.e., class whose metaclass does *not* define an
``__subclasscheck__()`` dunder method that raises a :exc:`TypeError`
exception) *or* tuple of one or more issubclassable classes.
Parameters
----------
type_or_types : object
Object to be validated.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep3119Exception`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`BeartypeDecorHintPep3119Exception`
If this object is neither:
* An issubclassable class.
* A tuple containing only issubclassable classes.
"""
from beartype._util.cls.utilclstest import die_unless_type_or_types
die_unless_type_or_types(type_or_types=type_or_types, exception_cls=exception_cls, exception_prefix=exception_prefix)
if isinstance(type_or_types, type):
from beartype._util.cls.utilclstest import die_unless_type
die_unless_type(cls=type_or_types, exception_cls=exception_cls, exception_prefix=exception_prefix)
try:
issubclass(type, type_or_types)
except TypeError as exception:
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not exception class.'
assert isinstance(exception_prefix, str), f'{repr(exception_prefix)} not string.'
exception_message = f'{exception_prefix}{repr(type_or_types)} uncheckable at runtime (i.e., not passable as second parameter to issubclass(), due to raising "{exception.__class__.__name__}: {exception}" from metaclass __subclasscheck__() method).'
raise exception_cls(exception_message) from exception
except Exception:
pass
else:
try:
issubclass(type, type_or_types)
except TypeError as exception:
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not exception class.'
assert isinstance(exception_prefix, str), f'{repr(exception_prefix)} not string.'
exception_message = f'{exception_prefix}{repr(type_or_types)} uncheckable at runtime'
for (cls_index, cls) in enumerate(type_or_types):
from beartype._util.cls.utilclstest import die_unless_type
die_unless_type(cls=cls, exception_cls=exception_cls, exception_prefix=f'{exception_message}, as tuple item {cls_index} ')
try:
issubclass(type, cls)
except TypeError as exception:
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not exception class.'
assert isinstance(f'{exception_message}, as tuple item {cls_index} ', str), f"{repr(f'{exception_message}, as tuple item {cls_index} ')} not string."
exception_message = f'''{f'{exception_message}, as tuple item {cls_index} '}{repr(cls)} uncheckable at runtime (i.e., not passable as second parameter to issubclass(), due to raising "{exception.__class__.__name__}: {exception}" from metaclass __subclasscheck__() method).'''
raise exception_cls(exception_message) from exception
except Exception:
pass
raise exception_cls(f'{exception_message}.') from exception
except Exception:
pass
|
beartype
|
positive
|
def set_config(self, data):
"""
Describes the specifics of the sensing implementation
"""
<DeepExtract>
if 16 <= 8:
data = data
if 16 <= 16:
data = (data & 65280) >> 8 | (data & 255) << 8
if 16 <= 32:
data = (data & 4278190080) >> 24 | (data & 16711680) >> 8 | (data & 65280) << 8 | (data & 255) << 24
raise Exception('Cannot swap endianness for length ' + 16)
</DeepExtract>
buffer = []
buffer[0] = data >> 8 & 255
buffer[1] = data >> 0 & 255
self.i2c.writeto_mem(self.device_address, self.REGISTER_CONFIG, buffer, addrsize=16)
|
def set_config(self, data):
"""
Describes the specifics of the sensing implementation
"""
if 16 <= 8:
data = data
if 16 <= 16:
data = (data & 65280) >> 8 | (data & 255) << 8
if 16 <= 32:
data = (data & 4278190080) >> 24 | (data & 16711680) >> 8 | (data & 65280) << 8 | (data & 255) << 24
raise Exception('Cannot swap endianness for length ' + 16)
buffer = []
buffer[0] = data >> 8 & 255
buffer[1] = data >> 0 & 255
self.i2c.writeto_mem(self.device_address, self.REGISTER_CONFIG, buffer, addrsize=16)
|
cyanobyte
|
positive
|
def _post(url, data, codes):
"""Mockable version of the user agent post.
"""
headers = dict(Accept='application/json')
body = dumps(data) if data else ''
<DeepExtract>
slumber_local = get_slumber_local_url_prefix()
if url.startswith(slumber_local):
logging.debug('Using local fake HTTP due to %s starting with %s', url, slumber_local)
url_fragment = url[len(slumber_local) - 1:]
elif url.startswith('/'):
logging.debug('Using local fake HTTP due to %s starting with /', url)
url_fragment = url
logging.debug('Using real HTTP for %s', url)
</DeepExtract>
if url_fragment:
headers.update(_sign_request('POST', url_fragment, body))
response = FakeClient().post(url_fragment, body, content_type='application/json', HTTP_HOST='localhost:8000', **_fake_http_headers(headers))
assert response.status_code in (codes or [200]), (url_fragment, response, response.content)
content = response.content
else:
headers.update(_sign_request('POST', urlparse(url).path, body))
headers['Content-Type'] = 'application/json'
(response, content) = _real().request(url, 'POST', body=body, headers=headers)
assert response.status in (codes or [200]), (url, response, content)
try:
return (response, loads(content))
except JSONDecodeError:
return (response, {})
|
def _post(url, data, codes):
"""Mockable version of the user agent post.
"""
headers = dict(Accept='application/json')
body = dumps(data) if data else ''
slumber_local = get_slumber_local_url_prefix()
if url.startswith(slumber_local):
logging.debug('Using local fake HTTP due to %s starting with %s', url, slumber_local)
url_fragment = url[len(slumber_local) - 1:]
elif url.startswith('/'):
logging.debug('Using local fake HTTP due to %s starting with /', url)
url_fragment = url
logging.debug('Using real HTTP for %s', url)
if url_fragment:
headers.update(_sign_request('POST', url_fragment, body))
response = FakeClient().post(url_fragment, body, content_type='application/json', HTTP_HOST='localhost:8000', **_fake_http_headers(headers))
assert response.status_code in (codes or [200]), (url_fragment, response, response.content)
content = response.content
else:
headers.update(_sign_request('POST', urlparse(url).path, body))
headers['Content-Type'] = 'application/json'
(response, content) = _real().request(url, 'POST', body=body, headers=headers)
assert response.status in (codes or [200]), (url, response, content)
try:
return (response, loads(content))
except JSONDecodeError:
return (response, {})
|
django-slumber
|
positive
|
def install_vicvb_cleanall(env):
try:
<DeepExtract>
if 'vicvb' == 'viral':
env.VIRAL_ROOT_DIR = '/usr/local/VHTNGS'
if not _path_exists(env.VIRAL_ROOT_DIR):
sudo('mkdir -p %s' % env.VIRAL_ROOT_DIR)
elif 'vicvb' == 'vigor':
env.VIGOR_ROOT_DIR = '/usr/local/VIGOR'
if not _path_exists(env.VIGOR_ROOT_DIR):
sudo('mkdir -p %s' % env.VIGOR_ROOT_DIR)
env.VIGOR_SCRATCH_DIR = '/usr/local/scratch/vigor'
if not _path_exists(env.VIGOR_SCRATCH_DIR):
sudo('mkdir -p %s' % env.VIGOR_SCRATCH_DIR)
sudo('find %s -type f -exec chmod 666 {} \\;' % env.VIGOR_SCRATCH_DIR)
sudo('find %s -type d -exec chmod 777 {} \\;' % env.VIGOR_SCRATCH_DIR)
else:
env.VICVB_LOCAL_DIR = '/usr/local/VICVB'
env.VICVB_GALAXY_DIR = '/mnt/galaxyTools/galaxy-central/static/vicvb'
</DeepExtract>
<DeepExtract>
if _path_is_dir(env.VICVB_LOCAL_DIR):
_unlock_dir(env.VICVB_LOCAL_DIR)
sudo('rm -rf %s' % env.VICVB_LOCAL_DIR)
else:
print('DEBUG: _remove_dir[%s] -- NOT FOUND' % env.VICVB_LOCAL_DIR)
</DeepExtract>
<DeepExtract>
if _path_is_dir(env.VICVB_GALAXY_DIR):
_unlock_dir(env.VICVB_GALAXY_DIR)
sudo('rm -rf %s' % env.VICVB_GALAXY_DIR)
else:
print('DEBUG: _remove_dir[%s] -- NOT FOUND' % env.VICVB_GALAXY_DIR)
</DeepExtract>
with cd('~'):
sudo('rm -fr ~/VICVB')
print('VICVB Removed\n')
finally:
disconnect_all()
|
def install_vicvb_cleanall(env):
try:
if 'vicvb' == 'viral':
env.VIRAL_ROOT_DIR = '/usr/local/VHTNGS'
if not _path_exists(env.VIRAL_ROOT_DIR):
sudo('mkdir -p %s' % env.VIRAL_ROOT_DIR)
elif 'vicvb' == 'vigor':
env.VIGOR_ROOT_DIR = '/usr/local/VIGOR'
if not _path_exists(env.VIGOR_ROOT_DIR):
sudo('mkdir -p %s' % env.VIGOR_ROOT_DIR)
env.VIGOR_SCRATCH_DIR = '/usr/local/scratch/vigor'
if not _path_exists(env.VIGOR_SCRATCH_DIR):
sudo('mkdir -p %s' % env.VIGOR_SCRATCH_DIR)
sudo('find %s -type f -exec chmod 666 {} \\;' % env.VIGOR_SCRATCH_DIR)
sudo('find %s -type d -exec chmod 777 {} \\;' % env.VIGOR_SCRATCH_DIR)
else:
env.VICVB_LOCAL_DIR = '/usr/local/VICVB'
env.VICVB_GALAXY_DIR = '/mnt/galaxyTools/galaxy-central/static/vicvb'
if _path_is_dir(env.VICVB_LOCAL_DIR):
_unlock_dir(env.VICVB_LOCAL_DIR)
sudo('rm -rf %s' % env.VICVB_LOCAL_DIR)
else:
print('DEBUG: _remove_dir[%s] -- NOT FOUND' % env.VICVB_LOCAL_DIR)
if _path_is_dir(env.VICVB_GALAXY_DIR):
_unlock_dir(env.VICVB_GALAXY_DIR)
sudo('rm -rf %s' % env.VICVB_GALAXY_DIR)
else:
print('DEBUG: _remove_dir[%s] -- NOT FOUND' % env.VICVB_GALAXY_DIR)
with cd('~'):
sudo('rm -fr ~/VICVB')
print('VICVB Removed\n')
finally:
disconnect_all()
|
cloudbiolinux
|
positive
|
def q_explained_variance(q_pred, q_true):
"""
Calculates the explained variance of the Q value
:param q_pred: (TensorFlow Tensor) The predicted Q value
:param q_true: (TensorFlow Tensor) The expected Q value
:return: (TensorFlow Tensor) the explained variance of the Q value
"""
(_, var_y) = tf.nn.moments(q_true, axes=[0, 1])
(_, var_pred) = tf.nn.moments(q_true - q_pred, axes=[0, 1])
<DeepExtract>
i = 0
for (tensor, shape) in zip([var_y, var_pred], [[]] * 2):
assert tensor.get_shape().as_list() == shape, 'id ' + str(i) + ' shape ' + str(tensor.get_shape()) + str(shape)
i += 1
</DeepExtract>
return 1.0 - var_pred / var_y
|
def q_explained_variance(q_pred, q_true):
"""
Calculates the explained variance of the Q value
:param q_pred: (TensorFlow Tensor) The predicted Q value
:param q_true: (TensorFlow Tensor) The expected Q value
:return: (TensorFlow Tensor) the explained variance of the Q value
"""
(_, var_y) = tf.nn.moments(q_true, axes=[0, 1])
(_, var_pred) = tf.nn.moments(q_true - q_pred, axes=[0, 1])
i = 0
for (tensor, shape) in zip([var_y, var_pred], [[]] * 2):
assert tensor.get_shape().as_list() == shape, 'id ' + str(i) + ' shape ' + str(tensor.get_shape()) + str(shape)
i += 1
return 1.0 - var_pred / var_y
|
ai_supermario
|
positive
|
def handle(self, handler_input):
speak_output = 'Goodbye!' + getRandomFact() + '. New adventures to Egypt, England, and Greece coming soon!'
response_builder = handler_input.response_builder
<DeepExtract>
if supports_apl(handler_input):
handler_input.response_builder.add_directive(RenderDocumentDirective(document=load_apl_document('main.json'), datasources=load_apl_document('datasources.json')))
</DeepExtract>
return response_builder.speak(speak_output).response
|
def handle(self, handler_input):
speak_output = 'Goodbye!' + getRandomFact() + '. New adventures to Egypt, England, and Greece coming soon!'
response_builder = handler_input.response_builder
if supports_apl(handler_input):
handler_input.response_builder.add_directive(RenderDocumentDirective(document=load_apl_document('main.json'), datasources=load_apl_document('datasources.json')))
return response_builder.speak(speak_output).response
|
Course_Alexa_Skill_Builder
|
positive
|
def rule_test(self, entries: List[TestEntry]) -> None:
def test_it(e: TestEntry, accept_header: str) -> bool:
expected = github_io + e.expected_url
resp = requests.head(e.input_url, headers={'accept': accept_header}, verify=False)
if resp.status_code == 301 and 'location' in resp.headers:
resp = requests.head(resp.headers['location'], headers={'accept': accept_header}, verify=False)
actual = resp.headers['location'] if resp.status_code == 302 and 'location' in resp.headers else f'Error: {resp.status_code}'
if FAIL_ON_ERROR:
self.assertEqual(expected, actual, f'redirect for: {resp.url}')
<DeepExtract>
self.results.add((e.input_url, actual, accept_header.split(',')[0]))
</DeepExtract>
return True
elif expected != actual:
print(f'{e.input_url} ({accept_header}):\n expected {expected} - got {actual}')
return False
<DeepExtract>
self.results.add((e.input_url, actual, accept_header.split(',')[0]))
</DeepExtract>
return True
def ev_al(entry: TestEntry) -> bool:
if not entry.accept_header:
return test_it(entry, default_header)
else:
<DeepExtract>
expected = github_io + entry.expected_url
resp = requests.head(entry.input_url, headers={'accept': entry.accept_header}, verify=False)
if resp.status_code == 301 and 'location' in resp.headers:
resp = requests.head(resp.headers['location'], headers={'accept': entry.accept_header}, verify=False)
actual = resp.headers['location'] if resp.status_code == 302 and 'location' in resp.headers else f'Error: {resp.status_code}'
if FAIL_ON_ERROR:
self.assertEqual(expected, actual, f'redirect for: {resp.url}')
self.record_results(entry.input_url, entry.accept_header, actual)
r1 = True
elif expected != actual:
print(f'{entry.input_url} ({entry.accept_header}):\n expected {expected} - got {actual}')
r1 = False
self.record_results(entry.input_url, entry.accept_header, actual)
r1 = True
</DeepExtract>
return test_it(entry, entry.accept_header + ',' + default_header) and r1
self.assertTrue(all([ev_al(entry) for entry in entries]))
|
def rule_test(self, entries: List[TestEntry]) -> None:
def test_it(e: TestEntry, accept_header: str) -> bool:
expected = github_io + e.expected_url
resp = requests.head(e.input_url, headers={'accept': accept_header}, verify=False)
if resp.status_code == 301 and 'location' in resp.headers:
resp = requests.head(resp.headers['location'], headers={'accept': accept_header}, verify=False)
actual = resp.headers['location'] if resp.status_code == 302 and 'location' in resp.headers else f'Error: {resp.status_code}'
if FAIL_ON_ERROR:
self.assertEqual(expected, actual, f'redirect for: {resp.url}')
self.results.add((e.input_url, actual, accept_header.split(',')[0]))
return True
elif expected != actual:
print(f'{e.input_url} ({accept_header}):\n expected {expected} - got {actual}')
return False
self.results.add((e.input_url, actual, accept_header.split(',')[0]))
return True
def ev_al(entry: TestEntry) -> bool:
if not entry.accept_header:
return test_it(entry, default_header)
else:
expected = github_io + entry.expected_url
resp = requests.head(entry.input_url, headers={'accept': entry.accept_header}, verify=False)
if resp.status_code == 301 and 'location' in resp.headers:
resp = requests.head(resp.headers['location'], headers={'accept': entry.accept_header}, verify=False)
actual = resp.headers['location'] if resp.status_code == 302 and 'location' in resp.headers else f'Error: {resp.status_code}'
if FAIL_ON_ERROR:
self.assertEqual(expected, actual, f'redirect for: {resp.url}')
self.record_results(entry.input_url, entry.accept_header, actual)
r1 = True
elif expected != actual:
print(f'{entry.input_url} ({entry.accept_header}):\n expected {expected} - got {actual}')
r1 = False
self.record_results(entry.input_url, entry.accept_header, actual)
r1 = True
return test_it(entry, entry.accept_header + ',' + default_header) and r1
self.assertTrue(all([ev_al(entry) for entry in entries]))
|
biolinkml
|
positive
|
def alert(self, matches):
<DeepExtract>
body = self.get_aggregation_summary_text(matches)
if self.rule.get('alert_text_type') != 'aggregation_summary_only':
for match in matches:
body += str(BasicMatchString(self.rule, match))
if len(matches) > 1:
body += '\n----------------------------------------\n'
body = body
</DeepExtract>
headers = {'content-type': 'application/json'}
proxies = {'https': self.victorops_proxy} if self.victorops_proxy else None
payload = {'message_type': self.victorops_message_type, 'entity_display_name': self.victorops_entity_display_name, 'monitoring_tool': 'ElastAlert', 'state_message': body}
if self.victorops_entity_id:
payload['entity_id'] = self.victorops_entity_id
try:
response = requests.post(self.url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers, proxies=proxies)
response.raise_for_status()
except RequestException as e:
raise EAException('Error posting to VictorOps: %s' % e)
elastalert_logger.info('Trigger sent to VictorOps')
|
def alert(self, matches):
body = self.get_aggregation_summary_text(matches)
if self.rule.get('alert_text_type') != 'aggregation_summary_only':
for match in matches:
body += str(BasicMatchString(self.rule, match))
if len(matches) > 1:
body += '\n----------------------------------------\n'
body = body
headers = {'content-type': 'application/json'}
proxies = {'https': self.victorops_proxy} if self.victorops_proxy else None
payload = {'message_type': self.victorops_message_type, 'entity_display_name': self.victorops_entity_display_name, 'monitoring_tool': 'ElastAlert', 'state_message': body}
if self.victorops_entity_id:
payload['entity_id'] = self.victorops_entity_id
try:
response = requests.post(self.url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers, proxies=proxies)
response.raise_for_status()
except RequestException as e:
raise EAException('Error posting to VictorOps: %s' % e)
elastalert_logger.info('Trigger sent to VictorOps')
|
elastalert
|
positive
|
def unbind_from_fs(self, cpe_fs: str):
<DeepExtract>
cpe_fs = cpe_fs.replace('\\-', '-')
cpe_fs = cpe_fs.replace('\\.', '.')
cpe_fs = re.compile('\\\\(.)', re.M).sub(lambda m: '%' + hex(ord(m.group(1)))[2:], cpe_fs)
</DeepExtract>
cpe_components = cpe_fs.split(':')
for (i, comp) in enumerate(cpe_components):
if i == 2:
self.part = comp
elif i == 3:
self.vendor = comp
elif i == 4:
self.product = comp
elif i == 5:
self.version = comp
elif i == 6:
self.update = comp
elif i == 7:
self.edition = comp
elif i == 8:
self.language = comp
elif i == 9:
self.sw_edition = comp
elif i == 10:
self.target_sw = comp
elif i == 11:
self.target_hw = comp
elif i == 12:
self.other = comp
|
def unbind_from_fs(self, cpe_fs: str):
cpe_fs = cpe_fs.replace('\\-', '-')
cpe_fs = cpe_fs.replace('\\.', '.')
cpe_fs = re.compile('\\\\(.)', re.M).sub(lambda m: '%' + hex(ord(m.group(1)))[2:], cpe_fs)
cpe_components = cpe_fs.split(':')
for (i, comp) in enumerate(cpe_components):
if i == 2:
self.part = comp
elif i == 3:
self.vendor = comp
elif i == 4:
self.product = comp
elif i == 5:
self.version = comp
elif i == 6:
self.update = comp
elif i == 7:
self.edition = comp
elif i == 8:
self.language = comp
elif i == 9:
self.sw_edition = comp
elif i == 10:
self.target_sw = comp
elif i == 11:
self.target_hw = comp
elif i == 12:
self.other = comp
|
cve-search
|
positive
|
def get_similar_dictionary(self, entity_name, texts, fuzziness_threshold='auto:4,7', search_language_script=None, **kwargs):
"""
Args:
entity_name: the name of the entity to lookup in the datastore for getting entity values and their variants
texts(list of strings): the text for which variants need to be find out
fuzziness_threshold: fuzziness allowed for search results on entity value variants
search_language_script: language of elasticsearch documents which are eligible for match
kwargs:
For Elasticsearch:
Refer https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search
Returns:
list of collections.OrderedDict: dictionary mapping entity value variants to their entity value
Example:
db = DataStore()
ngrams_list = ['Pune', 'Mumbai', 'Goa', 'Bangalore']
db.get_similar_ngrams_dictionary(entity_name='city', ngrams_list=ngrams_list, fuzziness_threshold=2)
Output:
[
{u'Bangalore': u'Bangalore',
u'Mulbagal': u'Mulbagal',
u'Multai': u'Multai',
u'Mumbai': u'Mumbai',
u'Pune': u'Pune',
u'Puri': u'Puri',
u'bangalore': u'bengaluru',
u'goa': u'goa',
u'mumbai': u'mumbai',
u'pune': u'pune'}
]
"""
results_list = []
if self._client_or_connection is None:
<DeepExtract>
if self._engine == ELASTICSEARCH:
self._store_name = self._connection_settings[ELASTICSEARCH_ALIAS]
self._client_or_connection = elastic_search.connect.connect(**self._connection_settings)
else:
self._client_or_connection = None
raise EngineNotImplementedException()
if self._client_or_connection is None:
raise EngineConnectionException(engine=self._engine)
</DeepExtract>
if self._engine == ELASTICSEARCH:
<DeepExtract>
if ELASTICSEARCH_DOC_TYPE not in self._connection_settings:
raise DataStoreSettingsImproperlyConfiguredException('Elasticsearch needs doc_type. Please configure ES_DOC_TYPE in your environment')
</DeepExtract>
request_timeout = self._connection_settings.get('request_timeout', 20)
results_list = elastic_search.query.full_text_query(connection=self._client_or_connection, index_name=self._store_name, doc_type=self._connection_settings[ELASTICSEARCH_DOC_TYPE], entity_name=entity_name, sentences=texts, fuzziness_threshold=fuzziness_threshold, search_language_script=search_language_script, request_timeout=request_timeout, **kwargs)
return results_list
|
def get_similar_dictionary(self, entity_name, texts, fuzziness_threshold='auto:4,7', search_language_script=None, **kwargs):
"""
Args:
entity_name: the name of the entity to lookup in the datastore for getting entity values and their variants
texts(list of strings): the text for which variants need to be find out
fuzziness_threshold: fuzziness allowed for search results on entity value variants
search_language_script: language of elasticsearch documents which are eligible for match
kwargs:
For Elasticsearch:
Refer https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search
Returns:
list of collections.OrderedDict: dictionary mapping entity value variants to their entity value
Example:
db = DataStore()
ngrams_list = ['Pune', 'Mumbai', 'Goa', 'Bangalore']
db.get_similar_ngrams_dictionary(entity_name='city', ngrams_list=ngrams_list, fuzziness_threshold=2)
Output:
[
{u'Bangalore': u'Bangalore',
u'Mulbagal': u'Mulbagal',
u'Multai': u'Multai',
u'Mumbai': u'Mumbai',
u'Pune': u'Pune',
u'Puri': u'Puri',
u'bangalore': u'bengaluru',
u'goa': u'goa',
u'mumbai': u'mumbai',
u'pune': u'pune'}
]
"""
results_list = []
if self._client_or_connection is None:
if self._engine == ELASTICSEARCH:
self._store_name = self._connection_settings[ELASTICSEARCH_ALIAS]
self._client_or_connection = elastic_search.connect.connect(**self._connection_settings)
else:
self._client_or_connection = None
raise EngineNotImplementedException()
if self._client_or_connection is None:
raise EngineConnectionException(engine=self._engine)
if self._engine == ELASTICSEARCH:
if ELASTICSEARCH_DOC_TYPE not in self._connection_settings:
raise DataStoreSettingsImproperlyConfiguredException('Elasticsearch needs doc_type. Please configure ES_DOC_TYPE in your environment')
request_timeout = self._connection_settings.get('request_timeout', 20)
results_list = elastic_search.query.full_text_query(connection=self._client_or_connection, index_name=self._store_name, doc_type=self._connection_settings[ELASTICSEARCH_DOC_TYPE], entity_name=entity_name, sentences=texts, fuzziness_threshold=fuzziness_threshold, search_language_script=search_language_script, request_timeout=request_timeout, **kwargs)
return results_list
|
chatbot_ner
|
positive
|
def visit_Reshape(self, operation: operations.Reshape) -> onnx.NodeProto:
idx = self.op_counts['Reshape'] = self.op_counts['Reshape'] + 1
opname = f'Reshape_{idx}'
<DeepExtract>
if isinstance(operation.x, Operation):
x = self.visit(operation.x)
if isinstance(operation.x, np.ndarray):
tensor_proto = onnx.numpy_helper.from_array(operation.x, name=f'{opname}.x')
self.initializer.append(tensor_proto)
x = tensor_proto
if isinstance(operation.x, bool):
tensor_proto = onnx.numpy_helper.from_array(np.asarray(operation.x), name=f'{opname}.x')
self.initializer.append(tensor_proto)
x = tensor_proto
if isinstance(operation.x, (int, float)):
tensor_proto = onnx.numpy_helper.from_array(np.array(operation.x, dtype=f'{type(operation.x).__name__}32'), name=f'{opname}.x')
self.initializer.append(tensor_proto)
x = tensor_proto
raise ValueError(f"Unknown type for operand of {f'{opname}.x'}: {type(operation.x)}")
</DeepExtract>
<DeepExtract>
if isinstance(operation.shape, Operation):
shape = self.visit(operation.shape)
if isinstance(operation.shape, np.ndarray):
tensor_proto = onnx.numpy_helper.from_array(operation.shape, name=f'{opname}.shape')
self.initializer.append(tensor_proto)
shape = tensor_proto
if isinstance(operation.shape, bool):
tensor_proto = onnx.numpy_helper.from_array(np.asarray(operation.shape), name=f'{opname}.shape')
self.initializer.append(tensor_proto)
shape = tensor_proto
if isinstance(operation.shape, (int, float)):
tensor_proto = onnx.numpy_helper.from_array(np.array(operation.shape, dtype=f'{type(operation.shape).__name__}32'), name=f'{opname}.shape')
self.initializer.append(tensor_proto)
shape = tensor_proto
raise ValueError(f"Unknown type for operand of {f'{opname}.shape'}: {type(operation.shape)}")
</DeepExtract>
if operation.allowzero:
raise ValueError('Reshape allowzero is not yet supported')
node = onnx.helper.make_node('Reshape', inputs=[x.name, shape.name], outputs=[opname], name=opname)
return node
|
def visit_Reshape(self, operation: operations.Reshape) -> onnx.NodeProto:
idx = self.op_counts['Reshape'] = self.op_counts['Reshape'] + 1
opname = f'Reshape_{idx}'
if isinstance(operation.x, Operation):
x = self.visit(operation.x)
if isinstance(operation.x, np.ndarray):
tensor_proto = onnx.numpy_helper.from_array(operation.x, name=f'{opname}.x')
self.initializer.append(tensor_proto)
x = tensor_proto
if isinstance(operation.x, bool):
tensor_proto = onnx.numpy_helper.from_array(np.asarray(operation.x), name=f'{opname}.x')
self.initializer.append(tensor_proto)
x = tensor_proto
if isinstance(operation.x, (int, float)):
tensor_proto = onnx.numpy_helper.from_array(np.array(operation.x, dtype=f'{type(operation.x).__name__}32'), name=f'{opname}.x')
self.initializer.append(tensor_proto)
x = tensor_proto
raise ValueError(f"Unknown type for operand of {f'{opname}.x'}: {type(operation.x)}")
if isinstance(operation.shape, Operation):
shape = self.visit(operation.shape)
if isinstance(operation.shape, np.ndarray):
tensor_proto = onnx.numpy_helper.from_array(operation.shape, name=f'{opname}.shape')
self.initializer.append(tensor_proto)
shape = tensor_proto
if isinstance(operation.shape, bool):
tensor_proto = onnx.numpy_helper.from_array(np.asarray(operation.shape), name=f'{opname}.shape')
self.initializer.append(tensor_proto)
shape = tensor_proto
if isinstance(operation.shape, (int, float)):
tensor_proto = onnx.numpy_helper.from_array(np.array(operation.shape, dtype=f'{type(operation.shape).__name__}32'), name=f'{opname}.shape')
self.initializer.append(tensor_proto)
shape = tensor_proto
raise ValueError(f"Unknown type for operand of {f'{opname}.shape'}: {type(operation.shape)}")
if operation.allowzero:
raise ValueError('Reshape allowzero is not yet supported')
node = onnx.helper.make_node('Reshape', inputs=[x.name, shape.name], outputs=[opname], name=opname)
return node
|
DNNV
|
positive
|
def run(self):
"""
Process the input queues in lock-step, and push any results to
the registered output queues.
"""
try:
while True:
input_chunks = [input.get() for input in self.input_queues]
for input in self.input_queues:
input.task_done()
if any((chunk is QUEUE_ABORT for chunk in input_chunks)):
<DeepExtract>
for queue in self.output_queues:
queue.put(QUEUE_ABORT)
</DeepExtract>
return
if any((chunk is QUEUE_FINISHED for chunk in input_chunks)):
break
<DeepExtract>
if self.process_chunks(input_chunks) is not None:
for queue in self.output_queues:
queue.put(self.process_chunks(input_chunks))
</DeepExtract>
<DeepExtract>
if self.finalise() is not None:
for queue in self.output_queues:
queue.put(self.finalise())
</DeepExtract>
except:
<DeepExtract>
for queue in self.output_queues:
queue.put(QUEUE_ABORT)
</DeepExtract>
raise
else:
for queue in self.output_queues:
queue.put(QUEUE_FINISHED)
|
def run(self):
"""
Process the input queues in lock-step, and push any results to
the registered output queues.
"""
try:
while True:
input_chunks = [input.get() for input in self.input_queues]
for input in self.input_queues:
input.task_done()
if any((chunk is QUEUE_ABORT for chunk in input_chunks)):
for queue in self.output_queues:
queue.put(QUEUE_ABORT)
return
if any((chunk is QUEUE_FINISHED for chunk in input_chunks)):
break
if self.process_chunks(input_chunks) is not None:
for queue in self.output_queues:
queue.put(self.process_chunks(input_chunks))
if self.finalise() is not None:
for queue in self.output_queues:
queue.put(self.finalise())
except:
for queue in self.output_queues:
queue.put(QUEUE_ABORT)
raise
else:
for queue in self.output_queues:
queue.put(QUEUE_FINISHED)
|
biggus
|
positive
|
def parse_dataframes(self, dataframes: List[DataFrame], aux: Dict[str, DataFrame], **parse_opts) -> DataFrame:
data = dataframes[0].rename(columns={'iso_code': '3166-1-alpha-3', 'new_cases': 'new_confirmed', 'new_deaths': 'new_deceased', 'new_tests': 'new_tested', 'total_cases': 'total_confirmed', 'total_deaths': 'total_deceased', 'total_tests': 'total_tested'}).merge(aux['country_codes'])
<DeepExtract>
data_columns = data.columns
data = data.merge(aux['metadata'], suffixes=('', 'aux_'), how='left')
data.aggregate_report_offset = data.aggregate_report_offset.apply(safe_int_cast)
data['date'] = data.apply(lambda x: date_offset(x['date'], get_or_default(x, 'aggregate_report_offset', 0)), axis=1)
data = data[data_columns]
</DeepExtract>
return data
|
def parse_dataframes(self, dataframes: List[DataFrame], aux: Dict[str, DataFrame], **parse_opts) -> DataFrame:
data = dataframes[0].rename(columns={'iso_code': '3166-1-alpha-3', 'new_cases': 'new_confirmed', 'new_deaths': 'new_deceased', 'new_tests': 'new_tested', 'total_cases': 'total_confirmed', 'total_deaths': 'total_deceased', 'total_tests': 'total_tested'}).merge(aux['country_codes'])
data_columns = data.columns
data = data.merge(aux['metadata'], suffixes=('', 'aux_'), how='left')
data.aggregate_report_offset = data.aggregate_report_offset.apply(safe_int_cast)
data['date'] = data.apply(lambda x: date_offset(x['date'], get_or_default(x, 'aggregate_report_offset', 0)), axis=1)
data = data[data_columns]
return data
|
covid-19-open-data
|
positive
|
def _generate_detections(cls_outputs, box_outputs, anchor_boxes, indices, classes, image_id, image_scale, num_classes):
"""Generates detections with RetinaNet model outputs and anchors.
Args:
cls_outputs: a numpy array with shape [N, 1], which has the highest class
scores on all feature levels. The N is the number of selected
top-K total anchors on all levels. (k being MAX_DETECTION_POINTS)
box_outputs: a numpy array with shape [N, 4], which stacks box regression
outputs on all feature levels. The N is the number of selected top-k
total anchors on all levels. (k being MAX_DETECTION_POINTS)
anchor_boxes: a numpy array with shape [N, 4], which stacks anchors on all
feature levels. The N is the number of selected top-k total anchors on
all levels.
indices: a numpy array with shape [N], which is the indices from top-k
selection.
classes: a numpy array with shape [N], which represents the class
prediction on all selected anchors from top-k selection.
image_id: an integer number to specify the image id.
image_scale: a float tensor representing the scale between original image
and input image for the detector. It is used to rescale detections for
evaluating with the original groundtruth annotations.
num_classes: a integer that indicates the number of classes.
Returns:
detections: detection results in a tensor with each row representing
[image_id, x, y, width, height, score, class]
"""
anchor_boxes = anchor_boxes[indices, :]
<DeepExtract>
scores = 1 / (1 + np.exp(-cls_outputs))
</DeepExtract>
<DeepExtract>
ycenter_a = (anchor_boxes.swapaxes(0, 1)[0] + anchor_boxes.swapaxes(0, 1)[2]) / 2
xcenter_a = (anchor_boxes.swapaxes(0, 1)[1] + anchor_boxes.swapaxes(0, 1)[3]) / 2
ha = anchor_boxes.swapaxes(0, 1)[2] - anchor_boxes.swapaxes(0, 1)[0]
wa = anchor_boxes.swapaxes(0, 1)[3] - anchor_boxes.swapaxes(0, 1)[1]
(ty, tx, th, tw) = box_outputs.swapaxes(0, 1)
w = np.exp(tw) * wa
h = np.exp(th) * ha
ycenter = ty * ha + ycenter_a
xcenter = tx * wa + xcenter_a
ymin = ycenter - h / 2.0
xmin = xcenter - w / 2.0
ymax = ycenter + h / 2.0
xmax = xcenter + w / 2.0
boxes = np.column_stack([ymin, xmin, ymax, xmax])
</DeepExtract>
boxes = boxes[:, [1, 0, 3, 2]]
detections = []
for c in range(num_classes):
indices = np.where(classes == c)[0]
if indices.shape[0] == 0:
continue
boxes_cls = boxes[indices, :]
scores_cls = scores[indices]
all_detections_cls = np.column_stack((boxes_cls, scores_cls))
<DeepExtract>
x1 = all_detections_cls[:, 0]
y1 = all_detections_cls[:, 1]
x2 = all_detections_cls[:, 2]
y2 = all_detections_cls[:, 3]
scores = all_detections_cls[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
intersection = w * h
overlap = intersection / (areas[i] + areas[order[1:]] - intersection)
inds = np.where(overlap <= 0.5)[0]
order = order[inds + 1]
top_detection_idx = keep
</DeepExtract>
top_detections_cls = all_detections_cls[top_detection_idx]
top_detections_cls[:, 2] -= top_detections_cls[:, 0]
top_detections_cls[:, 3] -= top_detections_cls[:, 1]
top_detections_cls = np.column_stack((np.repeat(image_id, len(top_detection_idx)), top_detections_cls, np.repeat(c + 1, len(top_detection_idx))))
detections.append(top_detections_cls)
def _generate_dummy_detections(number):
detections_dummy = np.zeros((number, 7), dtype=np.float32)
detections_dummy[:, 0] = image_id[0]
detections_dummy[:, 5] = _DUMMY_DETECTION_SCORE
return detections_dummy
if detections:
detections = np.vstack(detections)
indices = np.argsort(-detections[:, -2])
detections = np.array(detections[indices[0:MAX_DETECTIONS_PER_IMAGE]], dtype=np.float32)
n = max(MAX_DETECTIONS_PER_IMAGE - len(detections), 0)
<DeepExtract>
detections_dummy = np.zeros((n, 7), dtype=np.float32)
detections_dummy[:, 0] = image_id[0]
detections_dummy[:, 5] = _DUMMY_DETECTION_SCORE
detections_dummy = detections_dummy
</DeepExtract>
detections = np.vstack([detections, detections_dummy])
detections[:, 1:5] *= image_scale
else:
<DeepExtract>
detections_dummy = np.zeros((MAX_DETECTIONS_PER_IMAGE, 7), dtype=np.float32)
detections_dummy[:, 0] = image_id[0]
detections_dummy[:, 5] = _DUMMY_DETECTION_SCORE
detections = detections_dummy
</DeepExtract>
detections[:, 1:5] *= image_scale
return detections
|
def _generate_detections(cls_outputs, box_outputs, anchor_boxes, indices, classes, image_id, image_scale, num_classes):
"""Generates detections with RetinaNet model outputs and anchors.
Args:
cls_outputs: a numpy array with shape [N, 1], which has the highest class
scores on all feature levels. The N is the number of selected
top-K total anchors on all levels. (k being MAX_DETECTION_POINTS)
box_outputs: a numpy array with shape [N, 4], which stacks box regression
outputs on all feature levels. The N is the number of selected top-k
total anchors on all levels. (k being MAX_DETECTION_POINTS)
anchor_boxes: a numpy array with shape [N, 4], which stacks anchors on all
feature levels. The N is the number of selected top-k total anchors on
all levels.
indices: a numpy array with shape [N], which is the indices from top-k
selection.
classes: a numpy array with shape [N], which represents the class
prediction on all selected anchors from top-k selection.
image_id: an integer number to specify the image id.
image_scale: a float tensor representing the scale between original image
and input image for the detector. It is used to rescale detections for
evaluating with the original groundtruth annotations.
num_classes: a integer that indicates the number of classes.
Returns:
detections: detection results in a tensor with each row representing
[image_id, x, y, width, height, score, class]
"""
anchor_boxes = anchor_boxes[indices, :]
scores = 1 / (1 + np.exp(-cls_outputs))
ycenter_a = (anchor_boxes.swapaxes(0, 1)[0] + anchor_boxes.swapaxes(0, 1)[2]) / 2
xcenter_a = (anchor_boxes.swapaxes(0, 1)[1] + anchor_boxes.swapaxes(0, 1)[3]) / 2
ha = anchor_boxes.swapaxes(0, 1)[2] - anchor_boxes.swapaxes(0, 1)[0]
wa = anchor_boxes.swapaxes(0, 1)[3] - anchor_boxes.swapaxes(0, 1)[1]
(ty, tx, th, tw) = box_outputs.swapaxes(0, 1)
w = np.exp(tw) * wa
h = np.exp(th) * ha
ycenter = ty * ha + ycenter_a
xcenter = tx * wa + xcenter_a
ymin = ycenter - h / 2.0
xmin = xcenter - w / 2.0
ymax = ycenter + h / 2.0
xmax = xcenter + w / 2.0
boxes = np.column_stack([ymin, xmin, ymax, xmax])
boxes = boxes[:, [1, 0, 3, 2]]
detections = []
for c in range(num_classes):
indices = np.where(classes == c)[0]
if indices.shape[0] == 0:
continue
boxes_cls = boxes[indices, :]
scores_cls = scores[indices]
all_detections_cls = np.column_stack((boxes_cls, scores_cls))
x1 = all_detections_cls[:, 0]
y1 = all_detections_cls[:, 1]
x2 = all_detections_cls[:, 2]
y2 = all_detections_cls[:, 3]
scores = all_detections_cls[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
intersection = w * h
overlap = intersection / (areas[i] + areas[order[1:]] - intersection)
inds = np.where(overlap <= 0.5)[0]
order = order[inds + 1]
top_detection_idx = keep
top_detections_cls = all_detections_cls[top_detection_idx]
top_detections_cls[:, 2] -= top_detections_cls[:, 0]
top_detections_cls[:, 3] -= top_detections_cls[:, 1]
top_detections_cls = np.column_stack((np.repeat(image_id, len(top_detection_idx)), top_detections_cls, np.repeat(c + 1, len(top_detection_idx))))
detections.append(top_detections_cls)
def _generate_dummy_detections(number):
detections_dummy = np.zeros((number, 7), dtype=np.float32)
detections_dummy[:, 0] = image_id[0]
detections_dummy[:, 5] = _DUMMY_DETECTION_SCORE
return detections_dummy
if detections:
detections = np.vstack(detections)
indices = np.argsort(-detections[:, -2])
detections = np.array(detections[indices[0:MAX_DETECTIONS_PER_IMAGE]], dtype=np.float32)
n = max(MAX_DETECTIONS_PER_IMAGE - len(detections), 0)
detections_dummy = np.zeros((n, 7), dtype=np.float32)
detections_dummy[:, 0] = image_id[0]
detections_dummy[:, 5] = _DUMMY_DETECTION_SCORE
detections_dummy = detections_dummy
detections = np.vstack([detections, detections_dummy])
detections[:, 1:5] *= image_scale
else:
detections_dummy = np.zeros((MAX_DETECTIONS_PER_IMAGE, 7), dtype=np.float32)
detections_dummy[:, 0] = image_id[0]
detections_dummy[:, 5] = _DUMMY_DETECTION_SCORE
detections = detections_dummy
detections[:, 1:5] *= image_scale
return detections
|
class-balanced-loss
|
positive
|
def forward(self, rpn_cls_prob, rpn_bbox_pred, im_info):
"""Op for generating RPN porposals.
blobs_in:
- 'rpn_cls_probs': 4D tensor of shape (N, A, H, W), where N is the
number of minibatch images, A is the number of anchors per
locations, and (H, W) is the spatial size of the prediction grid.
Each value represents a "probability of object" rating in [0, 1].
- 'rpn_bbox_pred': 4D tensor of shape (N, 4 * A, H, W) of predicted
deltas for transformation anchor boxes into RPN proposals.
- 'im_info': 2D tensor of shape (N, 3) where the three columns encode
the input image's [height, width, scale]. Height and width are
for the input to the network, not the original image; scale is the
scale factor used to scale the original image to the network input
size.
blobs_out:
- 'rpn_rois': 2D tensor of shape (R, 5), for R RPN proposals where the
five columns encode [batch ind, x1, y1, x2, y2]. The boxes are
w.r.t. the network input, which is a *scaled* version of the
original image; these proposals must be scaled by 1 / scale (where
scale comes from im_info; see above) to transform it back to the
original input image coordinate system.
- 'rpn_roi_probs': 1D tensor of objectness probability scores
(extracted from rpn_cls_probs; see above).
"""
'Type conversion'
scores = rpn_cls_prob.data.cpu().numpy()
bbox_deltas = rpn_bbox_pred.data.cpu().numpy()
im_info = im_info.data.cpu().numpy()
(height, width) = scores.shape[-2:]
shift_x = np.arange(0, width) * self._feat_stride
shift_y = np.arange(0, height) * self._feat_stride
(shift_x, shift_y) = np.meshgrid(shift_x, shift_y, copy=False)
shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose()
num_images = scores.shape[0]
A = self._num_anchors
K = shifts.shape[0]
all_anchors = self._anchors[np.newaxis, :, :] + shifts[:, np.newaxis, :]
all_anchors = all_anchors.reshape((K * A, 4))
rois = np.empty((0, 5), dtype=np.float32)
roi_probs = np.empty((0, 1), dtype=np.float32)
for im_i in range(num_images):
<DeepExtract>
cfg_key = 'TRAIN' if self.training else 'TEST'
pre_nms_topN = cfg[cfg_key].RPN_PRE_NMS_TOP_N
post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N
nms_thresh = cfg[cfg_key].RPN_NMS_THRESH
min_size = cfg[cfg_key].RPN_MIN_SIZE
bbox_deltas[im_i, :, :, :] = bbox_deltas[im_i, :, :, :].transpose((1, 2, 0)).reshape((-1, 4))
scores[im_i, :, :, :] = scores[im_i, :, :, :].transpose((1, 2, 0)).reshape((-1, 1))
if pre_nms_topN <= 0 or pre_nms_topN >= len(scores[im_i, :, :, :]):
order = np.argsort(-scores[im_i, :, :, :].squeeze())
else:
inds = np.argpartition(-scores[im_i, :, :, :].squeeze(), pre_nms_topN)[:pre_nms_topN]
order = np.argsort(-scores[im_i, :, :, :][inds].squeeze())
order = inds[order]
bbox_deltas[im_i, :, :, :] = bbox_deltas[im_i, :, :, :][order, :]
all_anchors = all_anchors[order, :]
scores[im_i, :, :, :] = scores[im_i, :, :, :][order]
proposals = box_utils.bbox_transform(all_anchors, bbox_deltas[im_i, :, :, :], (1.0, 1.0, 1.0, 1.0))
proposals = box_utils.clip_tiled_boxes(proposals, im_info[im_i, :][:2])
keep = _filter_boxes(proposals, min_size, im_info[im_i, :])
proposals = proposals[keep, :]
scores[im_i, :, :, :] = scores[im_i, :, :, :][keep]
if nms_thresh > 0:
keep = box_utils.nms(np.hstack((proposals, scores[im_i, :, :, :])), nms_thresh)
if post_nms_topN > 0:
keep = keep[:post_nms_topN]
proposals = proposals[keep, :]
scores[im_i, :, :, :] = scores[im_i, :, :, :][keep]
(im_i_boxes, im_i_probs) = (proposals, scores[im_i, :, :, :])
</DeepExtract>
batch_inds = im_i * np.ones((im_i_boxes.shape[0], 1), dtype=np.float32)
im_i_rois = np.hstack((batch_inds, im_i_boxes))
rois = np.append(rois, im_i_rois, axis=0)
roi_probs = np.append(roi_probs, im_i_probs, axis=0)
return (rois, roi_probs)
|
def forward(self, rpn_cls_prob, rpn_bbox_pred, im_info):
"""Op for generating RPN porposals.
blobs_in:
- 'rpn_cls_probs': 4D tensor of shape (N, A, H, W), where N is the
number of minibatch images, A is the number of anchors per
locations, and (H, W) is the spatial size of the prediction grid.
Each value represents a "probability of object" rating in [0, 1].
- 'rpn_bbox_pred': 4D tensor of shape (N, 4 * A, H, W) of predicted
deltas for transformation anchor boxes into RPN proposals.
- 'im_info': 2D tensor of shape (N, 3) where the three columns encode
the input image's [height, width, scale]. Height and width are
for the input to the network, not the original image; scale is the
scale factor used to scale the original image to the network input
size.
blobs_out:
- 'rpn_rois': 2D tensor of shape (R, 5), for R RPN proposals where the
five columns encode [batch ind, x1, y1, x2, y2]. The boxes are
w.r.t. the network input, which is a *scaled* version of the
original image; these proposals must be scaled by 1 / scale (where
scale comes from im_info; see above) to transform it back to the
original input image coordinate system.
- 'rpn_roi_probs': 1D tensor of objectness probability scores
(extracted from rpn_cls_probs; see above).
"""
'Type conversion'
scores = rpn_cls_prob.data.cpu().numpy()
bbox_deltas = rpn_bbox_pred.data.cpu().numpy()
im_info = im_info.data.cpu().numpy()
(height, width) = scores.shape[-2:]
shift_x = np.arange(0, width) * self._feat_stride
shift_y = np.arange(0, height) * self._feat_stride
(shift_x, shift_y) = np.meshgrid(shift_x, shift_y, copy=False)
shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose()
num_images = scores.shape[0]
A = self._num_anchors
K = shifts.shape[0]
all_anchors = self._anchors[np.newaxis, :, :] + shifts[:, np.newaxis, :]
all_anchors = all_anchors.reshape((K * A, 4))
rois = np.empty((0, 5), dtype=np.float32)
roi_probs = np.empty((0, 1), dtype=np.float32)
for im_i in range(num_images):
cfg_key = 'TRAIN' if self.training else 'TEST'
pre_nms_topN = cfg[cfg_key].RPN_PRE_NMS_TOP_N
post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N
nms_thresh = cfg[cfg_key].RPN_NMS_THRESH
min_size = cfg[cfg_key].RPN_MIN_SIZE
bbox_deltas[im_i, :, :, :] = bbox_deltas[im_i, :, :, :].transpose((1, 2, 0)).reshape((-1, 4))
scores[im_i, :, :, :] = scores[im_i, :, :, :].transpose((1, 2, 0)).reshape((-1, 1))
if pre_nms_topN <= 0 or pre_nms_topN >= len(scores[im_i, :, :, :]):
order = np.argsort(-scores[im_i, :, :, :].squeeze())
else:
inds = np.argpartition(-scores[im_i, :, :, :].squeeze(), pre_nms_topN)[:pre_nms_topN]
order = np.argsort(-scores[im_i, :, :, :][inds].squeeze())
order = inds[order]
bbox_deltas[im_i, :, :, :] = bbox_deltas[im_i, :, :, :][order, :]
all_anchors = all_anchors[order, :]
scores[im_i, :, :, :] = scores[im_i, :, :, :][order]
proposals = box_utils.bbox_transform(all_anchors, bbox_deltas[im_i, :, :, :], (1.0, 1.0, 1.0, 1.0))
proposals = box_utils.clip_tiled_boxes(proposals, im_info[im_i, :][:2])
keep = _filter_boxes(proposals, min_size, im_info[im_i, :])
proposals = proposals[keep, :]
scores[im_i, :, :, :] = scores[im_i, :, :, :][keep]
if nms_thresh > 0:
keep = box_utils.nms(np.hstack((proposals, scores[im_i, :, :, :])), nms_thresh)
if post_nms_topN > 0:
keep = keep[:post_nms_topN]
proposals = proposals[keep, :]
scores[im_i, :, :, :] = scores[im_i, :, :, :][keep]
(im_i_boxes, im_i_probs) = (proposals, scores[im_i, :, :, :])
batch_inds = im_i * np.ones((im_i_boxes.shape[0], 1), dtype=np.float32)
im_i_rois = np.hstack((batch_inds, im_i_boxes))
rois = np.append(rois, im_i_rois, axis=0)
roi_probs = np.append(roi_probs, im_i_probs, axis=0)
return (rois, roi_probs)
|
Detectron.pytorch
|
positive
|
def try_setting_up_bot(self) -> bool:
"""
This function will try to setup the main bot for trading.
:return: Boolean whether setup was successful or not.
"""
try:
<DeepExtract>
self.create_trader(self.caller)
self.set_parameters(self.caller)
if self.gui.configuration.enableTelegramTrading.isChecked() and self.gui.telegram_bot is None:
self.initialize_telegram_bot()
if self.gui.configuration.schedulingStatisticsCheckBox.isChecked():
self.initialize_scheduler()
if self.caller == LIVE:
self.gui.running_live = True
elif self.caller == SIMULATION:
self.gui.simulation_running_live = True
else:
raise RuntimeError('Invalid type of caller specified.')
</DeepExtract>
self.signals.started.emit(self.caller)
return True
except Exception as e:
error_message = traceback.format_exc()
trader: SimulationTrader = self.gui.get_trader(self.caller)
self.logger.critical(error_message)
if trader:
trader.output_message(f'Bot has crashed because of :{e}')
trader.output_message(error_message)
if self.gui.telegram_bot and self.gui.configuration.chat_pass:
self.gui.telegram_bot.send_message(self.telegram_chat_id, f'Bot has crashed because of :{e}.')
self.gui.telegram_bot.send_message(self.telegram_chat_id, error_message)
self.fail_error = str(e)
return False
|
def try_setting_up_bot(self) -> bool:
"""
This function will try to setup the main bot for trading.
:return: Boolean whether setup was successful or not.
"""
try:
self.create_trader(self.caller)
self.set_parameters(self.caller)
if self.gui.configuration.enableTelegramTrading.isChecked() and self.gui.telegram_bot is None:
self.initialize_telegram_bot()
if self.gui.configuration.schedulingStatisticsCheckBox.isChecked():
self.initialize_scheduler()
if self.caller == LIVE:
self.gui.running_live = True
elif self.caller == SIMULATION:
self.gui.simulation_running_live = True
else:
raise RuntimeError('Invalid type of caller specified.')
self.signals.started.emit(self.caller)
return True
except Exception as e:
error_message = traceback.format_exc()
trader: SimulationTrader = self.gui.get_trader(self.caller)
self.logger.critical(error_message)
if trader:
trader.output_message(f'Bot has crashed because of :{e}')
trader.output_message(error_message)
if self.gui.telegram_bot and self.gui.configuration.chat_pass:
self.gui.telegram_bot.send_message(self.telegram_chat_id, f'Bot has crashed because of :{e}.')
self.gui.telegram_bot.send_message(self.telegram_chat_id, error_message)
self.fail_error = str(e)
return False
|
algobot
|
positive
|
def chunk(data, duration, trex_box):
"""Decode data into a segment and chunk it given duration and trex_box data."""
root = mp4(data)
mfhd = root.find(b'moof.mfhd')
tfhd = root.find(b'moof.traf.tfhd')
seqno = mfhd.seqno
track_id = tfhd.track_id
<DeepExtract>
for chunk_samples in partition(decode_fragment(data, trex_box), duration):
yield (create_moof(seqno, track_id, chunk_samples, None), create_mdat(chunk_samples))
</DeepExtract>
chunks = []
for (moof, mdat) in fragments:
chunks.append(moof.serialize() + mdat.serialize())
return chunks
|
def chunk(data, duration, trex_box):
"""Decode data into a segment and chunk it given duration and trex_box data."""
root = mp4(data)
mfhd = root.find(b'moof.mfhd')
tfhd = root.find(b'moof.traf.tfhd')
seqno = mfhd.seqno
track_id = tfhd.track_id
for chunk_samples in partition(decode_fragment(data, trex_box), duration):
yield (create_moof(seqno, track_id, chunk_samples, None), create_mdat(chunk_samples))
chunks = []
for (moof, mdat) in fragments:
chunks.append(moof.serialize() + mdat.serialize())
return chunks
|
dash-live-source-simulator
|
positive
|
def test_extraction_add_location_file(self):
self.dist.message_extractors = {'project': [('**/ignored/**.*', 'ignore', None), ('**.py', 'python', None)]}
self.cmd.output_file = 'project/i18n/temp.pot'
self.cmd.add_location = 'file'
self.cmd.omit_header = True
self.cmd.finalize_options()
self.cmd.run()
<DeepExtract>
assert os.path.isfile(pot_file)
</DeepExtract>
expected_content = '#: project/file1.py\nmsgid "bar"\nmsgstr ""\n\n#: project/file2.py\nmsgid "foobar"\nmsgid_plural "foobars"\nmsgstr[0] ""\nmsgstr[1] ""\n\n'
with open(pot_file) as f:
actual_content = f.read()
assert expected_content == actual_content
|
def test_extraction_add_location_file(self):
self.dist.message_extractors = {'project': [('**/ignored/**.*', 'ignore', None), ('**.py', 'python', None)]}
self.cmd.output_file = 'project/i18n/temp.pot'
self.cmd.add_location = 'file'
self.cmd.omit_header = True
self.cmd.finalize_options()
self.cmd.run()
assert os.path.isfile(pot_file)
expected_content = '#: project/file1.py\nmsgid "bar"\nmsgstr ""\n\n#: project/file2.py\nmsgid "foobar"\nmsgid_plural "foobars"\nmsgstr[0] ""\nmsgstr[1] ""\n\n'
with open(pot_file) as f:
actual_content = f.read()
assert expected_content == actual_content
|
babel
|
positive
|
def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor):
"""
Args:
input: (B, #anchors, #classes) float tensor.
Predicted logits for each class
target: (B, #anchors, #classes) float tensor.
One-hot encoded classification targets
weights: (B, #anchors) float tensor.
Anchor-wise weights.
Returns:
weighted_loss: (B, #anchors, #classes) float tensor after weighting.
"""
pred_sigmoid = torch.sigmoid(input)
alpha_weight = target * self.alpha + (1 - target) * (1 - self.alpha)
pt = target * (1.0 - pred_sigmoid) + (1.0 - target) * pred_sigmoid
focal_weight = alpha_weight * torch.pow(pt, self.gamma)
<DeepExtract>
loss = torch.clamp(input, min=0) - input * target + torch.log1p(torch.exp(-torch.abs(input)))
bce_loss = loss
</DeepExtract>
loss = focal_weight * bce_loss
if weights.shape.__len__() == 2 or (weights.shape.__len__() == 1 and target.shape.__len__() == 2):
weights = weights.unsqueeze(-1)
assert weights.shape.__len__() == loss.shape.__len__()
return loss * weights
|
def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor):
"""
Args:
input: (B, #anchors, #classes) float tensor.
Predicted logits for each class
target: (B, #anchors, #classes) float tensor.
One-hot encoded classification targets
weights: (B, #anchors) float tensor.
Anchor-wise weights.
Returns:
weighted_loss: (B, #anchors, #classes) float tensor after weighting.
"""
pred_sigmoid = torch.sigmoid(input)
alpha_weight = target * self.alpha + (1 - target) * (1 - self.alpha)
pt = target * (1.0 - pred_sigmoid) + (1.0 - target) * pred_sigmoid
focal_weight = alpha_weight * torch.pow(pt, self.gamma)
loss = torch.clamp(input, min=0) - input * target + torch.log1p(torch.exp(-torch.abs(input)))
bce_loss = loss
loss = focal_weight * bce_loss
if weights.shape.__len__() == 2 or (weights.shape.__len__() == 1 and target.shape.__len__() == 2):
weights = weights.unsqueeze(-1)
assert weights.shape.__len__() == loss.shape.__len__()
return loss * weights
|
3DIoUMatch
|
positive
|
def opts_entry(frame):
""" Add the options entry boxes """
for item in ('avgiterations',):
if item == 'avgiterations':
text = 'Iterations to Average:'
default = '10'
entframe = ttk.Frame(frame)
entframe.pack(fill=tk.X, pady=5, padx=5, side=tk.TOP)
lbl = ttk.Label(entframe, text=text, anchor=tk.W)
lbl.pack(padx=(0, 2), side=tk.LEFT)
ctl = ttk.Entry(entframe, width=4, justify=tk.RIGHT)
ctl.pack(side=tk.RIGHT, anchor=tk.W)
ctl.insert(0, default)
<DeepExtract>
hlp = ''
if item == 'reset':
hlp = 'Load/Refresh stats for the currently training session'
elif item == 'clear':
hlp = 'Clear currently displayed session stats'
elif item == 'save':
hlp = 'Save session stats to csv'
elif item == 'load':
hlp = 'Load saved session stats'
hlp = hlp
</DeepExtract>
Tooltip(entframe, text=hlp, wraplength=200)
self.vars[item] = ctl
|
def opts_entry(frame):
""" Add the options entry boxes """
for item in ('avgiterations',):
if item == 'avgiterations':
text = 'Iterations to Average:'
default = '10'
entframe = ttk.Frame(frame)
entframe.pack(fill=tk.X, pady=5, padx=5, side=tk.TOP)
lbl = ttk.Label(entframe, text=text, anchor=tk.W)
lbl.pack(padx=(0, 2), side=tk.LEFT)
ctl = ttk.Entry(entframe, width=4, justify=tk.RIGHT)
ctl.pack(side=tk.RIGHT, anchor=tk.W)
ctl.insert(0, default)
hlp = ''
if item == 'reset':
hlp = 'Load/Refresh stats for the currently training session'
elif item == 'clear':
hlp = 'Clear currently displayed session stats'
elif item == 'save':
hlp = 'Save session stats to csv'
elif item == 'load':
hlp = 'Load saved session stats'
hlp = hlp
Tooltip(entframe, text=hlp, wraplength=200)
self.vars[item] = ctl
|
DeepFakeTutorial
|
positive
|
def call(self, inputs):
"""Forward pass."""
if self.conditional:
(x, z) = inputs
<DeepExtract>
if len(x.shape) == 2:
x = x[:, tf.newaxis, tf.newaxis, :]
elif len(x.shape) == 3:
x = x[:, :, tf.newaxis, :]
else:
x = x
</DeepExtract>
<DeepExtract>
if len(z.shape) == 2:
z = z[:, tf.newaxis, tf.newaxis, :]
elif len(z.shape) == 3:
z = z[:, :, tf.newaxis, :]
else:
z = z
</DeepExtract>
else:
x = inputs
<DeepExtract>
if len(x.shape) == 2:
x = x[:, tf.newaxis, tf.newaxis, :]
elif len(x.shape) == 3:
x = x[:, :, tf.newaxis, :]
else:
x = x
</DeepExtract>
x = self.conv_in(x)
for (i, (layer, norm)) in enumerate(zip(self.layers, self.norms)):
if self.resample_layers and (not self.resample_after_convolve) and (i % self.layers_per_resample == 0):
x = self.resample_layers[i // self.layers_per_resample](x)
if self.conditional:
y = layer(x)
x += norm([y, z])
else:
x += norm(layer(x))
if self.resample_layers and self.resample_after_convolve and ((i + 1) % self.layers_per_resample == 0):
x = self.resample_layers[i // self.layers_per_resample](x)
return x[:, :, 0, :]
|
def call(self, inputs):
"""Forward pass."""
if self.conditional:
(x, z) = inputs
if len(x.shape) == 2:
x = x[:, tf.newaxis, tf.newaxis, :]
elif len(x.shape) == 3:
x = x[:, :, tf.newaxis, :]
else:
x = x
if len(z.shape) == 2:
z = z[:, tf.newaxis, tf.newaxis, :]
elif len(z.shape) == 3:
z = z[:, :, tf.newaxis, :]
else:
z = z
else:
x = inputs
if len(x.shape) == 2:
x = x[:, tf.newaxis, tf.newaxis, :]
elif len(x.shape) == 3:
x = x[:, :, tf.newaxis, :]
else:
x = x
x = self.conv_in(x)
for (i, (layer, norm)) in enumerate(zip(self.layers, self.norms)):
if self.resample_layers and (not self.resample_after_convolve) and (i % self.layers_per_resample == 0):
x = self.resample_layers[i // self.layers_per_resample](x)
if self.conditional:
y = layer(x)
x += norm([y, z])
else:
x += norm(layer(x))
if self.resample_layers and self.resample_after_convolve and ((i + 1) % self.layers_per_resample == 0):
x = self.resample_layers[i // self.layers_per_resample](x)
return x[:, :, 0, :]
|
ddsp
|
positive
|
def MF_knapsack(i, wt, val, j):
"""
This code involves the concept of memory functions. Here we solve the subproblems which are needed
unlike the below example
F is a 2D array with -1s filled up
"""
global F
if F[i][j] < 0:
if j < wt[i - 1]:
<DeepExtract>
global F
if F[i - 1][j] < 0:
if j < wt[i - 1 - 1]:
val = MF_knapsack(i - 1 - 1, wt, val, j)
else:
val = max(MF_knapsack(i - 1 - 1, wt, val, j), MF_knapsack(i - 1 - 1, wt, val, j - wt[i - 1 - 1]) + val[i - 1 - 1])
F[i - 1][j] = val
val = F[i - 1][j]
</DeepExtract>
else:
val = max(MF_knapsack(i - 1, wt, val, j), MF_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1])
F[i][j] = val
return F[i][j]
|
def MF_knapsack(i, wt, val, j):
"""
This code involves the concept of memory functions. Here we solve the subproblems which are needed
unlike the below example
F is a 2D array with -1s filled up
"""
global F
if F[i][j] < 0:
if j < wt[i - 1]:
global F
if F[i - 1][j] < 0:
if j < wt[i - 1 - 1]:
val = MF_knapsack(i - 1 - 1, wt, val, j)
else:
val = max(MF_knapsack(i - 1 - 1, wt, val, j), MF_knapsack(i - 1 - 1, wt, val, j - wt[i - 1 - 1]) + val[i - 1 - 1])
F[i - 1][j] = val
val = F[i - 1][j]
else:
val = max(MF_knapsack(i - 1, wt, val, j), MF_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1])
F[i][j] = val
return F[i][j]
|
-
|
positive
|
def train(model, data_gen, train_path, valid_path, start_epoch, num_epoches, save_path, device, batch_size=32, decay_rate=0.1, learning_rate=0.001, momentum=0.9, update_lr_epoches=[], shuffle=True):
model.train()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)
loss_history = [[], [], []]
for epoch in range(start_epoch, num_epoches + start_epoch):
step = 0
train_gen = data_gen.get_generator(train_path, batch_size, is_shuffle=shuffle)
if epoch in update_lr_epoches:
learning_rate = learning_rate * decay_rate
for param_group in optimizer.param_groups:
param_group['lr'] = learning_rate
print('Updating the learning rate at epoch: ' + str(epoch) + ', value: ' + str(learning_rate))
train_loss = []
for (batch_input_ids, batch_mask_ids, batch_input_type_ids, batch_label_types, batch_rel_matrix) in train_gen:
model.zero_grad()
loss = model.score([batch_input_ids.to(device), batch_mask_ids.to(device), batch_input_type_ids.to(device), batch_label_types.to(device), batch_rel_matrix.to(device)])
loss.backward()
optimizer.step()
optimizer.zero_grad()
loss = loss.data.cpu().tolist()
train_loss.append(loss)
print('Training: Epoch %d, step %5d / %d loss: %.3f' % (epoch + 1, step + 1, data_gen.num_samples / batch_size + 1, loss))
step += 1
valid_gen = data_gen.get_generator(valid_path, batch_size, is_shuffle=shuffle)
<DeepExtract>
num_valid = 0
num_correct = total_loss = 0
batch_size = 0
idx = 0
for (batch_input_ids, batch_mask_ids, batch_input_type_ids, batch_label_ids, batch_rel_matrix) in valid_gen:
loss = model.score([batch_input_ids.to(device), batch_mask_ids.to(device), batch_input_type_ids.to(device), batch_label_ids.to(device), batch_rel_matrix.to(device)])
idx += 1
total_loss += loss.mean().item()
loss = total_loss / idx
print('\nValidation : Loss: {:.6f} Accuracy: {}/{} ({:.4f}%)\n'.format(loss, 0, 0, 0))
(valid_loss, valid_accuracy) = (loss, 0)
</DeepExtract>
train_loss_value = np.mean(train_loss)
valid_loss_value = np.mean(valid_loss)
loss_history[0].append(epoch + 1)
loss_history[1].append(train_loss_value)
loss_history[2].append(valid_loss_value)
<DeepExtract>
plt.plot(loss_history[0], loss_history[1], '-b')
plt.plot(loss_history[0], loss_history[2], '--r')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend(['Training Loss', 'Validation Loss'])
plt.title(title)
plt.savefig(save_path)
</DeepExtract>
model.train()
save_data = {'model': model, 'history': loss_history}
with open(save_path + 'bert_ner_epoches=' + str(epoch + 1) + '_valid_loss=' + str(valid_loss) + '.pickle', 'wb') as handle:
pickle.dump(save_data, handle, protocol=2)
|
def train(model, data_gen, train_path, valid_path, start_epoch, num_epoches, save_path, device, batch_size=32, decay_rate=0.1, learning_rate=0.001, momentum=0.9, update_lr_epoches=[], shuffle=True):
model.train()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)
loss_history = [[], [], []]
for epoch in range(start_epoch, num_epoches + start_epoch):
step = 0
train_gen = data_gen.get_generator(train_path, batch_size, is_shuffle=shuffle)
if epoch in update_lr_epoches:
learning_rate = learning_rate * decay_rate
for param_group in optimizer.param_groups:
param_group['lr'] = learning_rate
print('Updating the learning rate at epoch: ' + str(epoch) + ', value: ' + str(learning_rate))
train_loss = []
for (batch_input_ids, batch_mask_ids, batch_input_type_ids, batch_label_types, batch_rel_matrix) in train_gen:
model.zero_grad()
loss = model.score([batch_input_ids.to(device), batch_mask_ids.to(device), batch_input_type_ids.to(device), batch_label_types.to(device), batch_rel_matrix.to(device)])
loss.backward()
optimizer.step()
optimizer.zero_grad()
loss = loss.data.cpu().tolist()
train_loss.append(loss)
print('Training: Epoch %d, step %5d / %d loss: %.3f' % (epoch + 1, step + 1, data_gen.num_samples / batch_size + 1, loss))
step += 1
valid_gen = data_gen.get_generator(valid_path, batch_size, is_shuffle=shuffle)
num_valid = 0
num_correct = total_loss = 0
batch_size = 0
idx = 0
for (batch_input_ids, batch_mask_ids, batch_input_type_ids, batch_label_ids, batch_rel_matrix) in valid_gen:
loss = model.score([batch_input_ids.to(device), batch_mask_ids.to(device), batch_input_type_ids.to(device), batch_label_ids.to(device), batch_rel_matrix.to(device)])
idx += 1
total_loss += loss.mean().item()
loss = total_loss / idx
print('\nValidation : Loss: {:.6f} Accuracy: {}/{} ({:.4f}%)\n'.format(loss, 0, 0, 0))
(valid_loss, valid_accuracy) = (loss, 0)
train_loss_value = np.mean(train_loss)
valid_loss_value = np.mean(valid_loss)
loss_history[0].append(epoch + 1)
loss_history[1].append(train_loss_value)
loss_history[2].append(valid_loss_value)
plt.plot(loss_history[0], loss_history[1], '-b')
plt.plot(loss_history[0], loss_history[2], '--r')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend(['Training Loss', 'Validation Loss'])
plt.title(title)
plt.savefig(save_path)
model.train()
save_data = {'model': model, 'history': loss_history}
with open(save_path + 'bert_ner_epoches=' + str(epoch + 1) + '_valid_loss=' + str(valid_loss) + '.pickle', 'wb') as handle:
pickle.dump(save_data, handle, protocol=2)
|
bert-jointly-relation-entity-extraciton
|
positive
|
def get(self, request, *args, **kwargs):
query_params = self.request.query_params
programs = split_query_argument(query_params.get('programs'))
if not programs:
self.always_exclude = self.always_exclude + ['programs']
recent = query_params.get('recent_date')
try:
<DeepExtract>
if not recent:
return
self.recent_date = datetime.strptime(recent, '%Y-%m-%d')
if (datetime.now() - self.recent_date).days <= 0:
raise ValueError(f'"{self.recent_date}" is not in the past')
</DeepExtract>
except ValueError as err:
return HttpResponseBadRequest(content='Error in recent_date: {}\n'.format(str(err)))
response = super().get(request, *args, **kwargs)
return response
|
def get(self, request, *args, **kwargs):
query_params = self.request.query_params
programs = split_query_argument(query_params.get('programs'))
if not programs:
self.always_exclude = self.always_exclude + ['programs']
recent = query_params.get('recent_date')
try:
if not recent:
return
self.recent_date = datetime.strptime(recent, '%Y-%m-%d')
if (datetime.now() - self.recent_date).days <= 0:
raise ValueError(f'"{self.recent_date}" is not in the past')
except ValueError as err:
return HttpResponseBadRequest(content='Error in recent_date: {}\n'.format(str(err)))
response = super().get(request, *args, **kwargs)
return response
|
edx-analytics-data-api
|
positive
|
def test_match_report_created(self):
self.assertEqual(MatchReport.objects.count(), 0)
<DeepExtract>
return self.client_post_report_prep()
</DeepExtract>
self.assertEqual(MatchReport.objects.count(), 1)
|
def test_match_report_created(self):
self.assertEqual(MatchReport.objects.count(), 0)
return self.client_post_report_prep()
self.assertEqual(MatchReport.objects.count(), 1)
|
callisto-core
|
positive
|
@urlpatterns.route('endorse-comments/', perms=['ej.can_edit_conversation'])
def endorse(request, conversation, slug, check=check_promoted):
check(conversation, request)
user = request.user
comments = list(conversation.comments.approved().exclude(endorsements__is_global=True, endorsements__end__gte=timezone.now()))
if request.method == 'POST':
<DeepExtract>
comment_ids = set()
for (k, v) in request.POST.items():
if k.startswith('endorse-') and v == 'on':
k = int(k.partition('-')[2])
comment_ids.add(k)
comment_ids = comment_ids
</DeepExtract>
<DeepExtract>
id_map = {comment.id: comment for comment in comments}
for comment_id in comment_ids:
try:
comment = id_map[comment_id]
except KeyError:
raise PermissionError()
endorse_comment(comment, author=request.user)
</DeepExtract>
return {'user': user, 'conversation': conversation, 'comments': comments}
|
@urlpatterns.route('endorse-comments/', perms=['ej.can_edit_conversation'])
def endorse(request, conversation, slug, check=check_promoted):
check(conversation, request)
user = request.user
comments = list(conversation.comments.approved().exclude(endorsements__is_global=True, endorsements__end__gte=timezone.now()))
if request.method == 'POST':
comment_ids = set()
for (k, v) in request.POST.items():
if k.startswith('endorse-') and v == 'on':
k = int(k.partition('-')[2])
comment_ids.add(k)
comment_ids = comment_ids
id_map = {comment.id: comment for comment in comments}
for comment_id in comment_ids:
try:
comment = id_map[comment_id]
except KeyError:
raise PermissionError()
endorse_comment(comment, author=request.user)
return {'user': user, 'conversation': conversation, 'comments': comments}
|
ej-server
|
positive
|
def run(self):
""" Processes defined conditions and compiles a list of materials.
:return: List of materials that met the conditional requirement. Type: list.
"""
conditions = self.config.get_raw_dict('conditions')
if isinstance(conditions, list):
materials = []
for and_condition in conditions:
materials.extend(self.perform_and_condition_check(and_condition, materials))
else:
<DeepExtract>
new_materials = []
if used_materials_to_check is None:
used_materials_to_check = get_all_materials()
for material in used_materials_to_check:
if material in new_materials or material in [] or material is None:
continue
select_material = True
for (key, value) in conditions.items():
requested_custom_property = False
requested_custom_function = False
if key.startswith('cp_'):
requested_custom_property = True
key = key[3:]
if key.startswith('cf_'):
requested_custom_function = True
key = key[3:]
if hasattr(material, key) and (not requested_custom_property) and (not requested_custom_function):
if isinstance(getattr(material, key), type(value)):
new_value = value
elif isinstance(getattr(material, key), mathutils.Vector):
new_value = mathutils.Vector(value)
elif isinstance(getattr(material, key), mathutils.Euler):
new_value = mathutils.Euler(value)
elif isinstance(getattr(material, key), mathutils.Color):
new_value = mathutils.Color(value)
else:
raise Exception('Types are not matching: %s and %s !' % (type(getattr(material, key)), type(value)))
if not (isinstance(getattr(material, key), str) and re.fullmatch(value, getattr(material, key)) is not None or getattr(material, key) == new_value):
select_material = False
break
elif key in material and requested_custom_property:
if isinstance(material[key], type(value)) or (isinstance(material[key], int) and isinstance(value, bool)):
if not (isinstance(material[key], str) and re.fullmatch(value, material[key]) is not None or material[key] == value):
select_material = False
break
else:
raise Exception('Types are not matching: {} and {} !'.format(type(material[key]), type(value)))
elif requested_custom_function:
if key.startswith('texture_amount_'):
if material.use_nodes:
value = int(value)
nodes = material.node_tree.nodes
texture_nodes = Utility.get_nodes_with_type(nodes, 'TexImage')
amount_of_texture_nodes = len(texture_nodes) if texture_nodes is not None else 0
if 'min' in key:
if not amount_of_texture_nodes >= value:
select_material = False
break
elif 'max' in key:
if not amount_of_texture_nodes <= value:
select_material = False
break
elif 'eq' in key:
if not amount_of_texture_nodes == value:
select_material = False
break
else:
raise Exception('This type of key is unknown: {}'.format(key))
else:
select_material = False
break
elif key.startswith('principled_bsdf_amount_'):
if material.use_nodes:
value = int(value)
nodes = material.node_tree.nodes
principled = Utility.get_nodes_with_type(nodes, 'BsdfPrincipled')
amount_of_principled_bsdf_nodes = len(principled) if principled is not None else 0
if 'min' in key:
if not amount_of_principled_bsdf_nodes >= value:
select_material = False
break
elif 'max' in key:
if not amount_of_principled_bsdf_nodes <= value:
select_material = False
break
elif 'eq' in key:
if not amount_of_principled_bsdf_nodes == value:
select_material = False
break
else:
raise Exception('This type of key is unknown: {}'.format(key))
else:
select_material = False
break
elif key.startswith('principled_bsdf_'):
if material.use_nodes:
value = float(value)
nodes = material.node_tree.nodes
principled = Utility.get_nodes_with_type(nodes, 'BsdfPrincipled')
amount_of_principled_bsdf_nodes = len(principled) if principled is not None else 0
if amount_of_principled_bsdf_nodes != 1:
select_material = False
break
principled = principled[0]
extracted_input_name = key[len('principled_bsdf_'):key.rfind('_')]
if extracted_input_name not in principled.inputs:
raise Exception('Only valid inputs of a principled node are allowed: {} in: {}'.format(extracted_input_name, key))
used_value = principled.inputs[extracted_input_name]
if len(used_value.links) > 0:
select_material = False
break
used_value = used_value.default_value
if key.endswith('min'):
if not used_value >= value:
select_material = False
break
elif key.endswith('max'):
if not used_value <= value:
select_material = False
break
elif key.endswith('eq'):
if not used_value == value:
select_material = False
break
else:
raise Exception('This type of key is unknown: {}'.format(key))
else:
select_material = False
break
elif key == 'use_materials_of_objects':
objects = Utility.build_provider_based_on_config(value).run()
found_material = False
for obj in objects:
if hasattr(obj, 'material_slots'):
for mat_slot in obj.material_slots:
if mat_slot.material == material:
found_material = True
break
if found_material:
break
if not found_material:
select_material = False
break
else:
select_material = False
break
else:
select_material = False
break
if select_material:
new_materials.append(material)
[] = new_materials
</DeepExtract>
random_samples = self.config.get_int('random_samples', 0)
has_index = self.config.has_param('index')
if has_index and (not random_samples):
materials = [materials[self.config.get_int('index')]]
elif random_samples and (not has_index):
materials = sample(materials, k=min(random_samples, len(materials)))
elif has_index and random_samples:
raise RuntimeError('Please, define only one of two: `index` or `random_samples`.')
check_if_return_is_empty = self.config.get_bool('check_empty', False)
if check_if_return_is_empty and (not materials):
raise Exception(f'There were no materials selected with the following condition: \n{self._get_conditions_as_string()}')
return materials
|
def run(self):
""" Processes defined conditions and compiles a list of materials.
:return: List of materials that met the conditional requirement. Type: list.
"""
conditions = self.config.get_raw_dict('conditions')
if isinstance(conditions, list):
materials = []
for and_condition in conditions:
materials.extend(self.perform_and_condition_check(and_condition, materials))
else:
new_materials = []
if used_materials_to_check is None:
used_materials_to_check = get_all_materials()
for material in used_materials_to_check:
if material in new_materials or material in [] or material is None:
continue
select_material = True
for (key, value) in conditions.items():
requested_custom_property = False
requested_custom_function = False
if key.startswith('cp_'):
requested_custom_property = True
key = key[3:]
if key.startswith('cf_'):
requested_custom_function = True
key = key[3:]
if hasattr(material, key) and (not requested_custom_property) and (not requested_custom_function):
if isinstance(getattr(material, key), type(value)):
new_value = value
elif isinstance(getattr(material, key), mathutils.Vector):
new_value = mathutils.Vector(value)
elif isinstance(getattr(material, key), mathutils.Euler):
new_value = mathutils.Euler(value)
elif isinstance(getattr(material, key), mathutils.Color):
new_value = mathutils.Color(value)
else:
raise Exception('Types are not matching: %s and %s !' % (type(getattr(material, key)), type(value)))
if not (isinstance(getattr(material, key), str) and re.fullmatch(value, getattr(material, key)) is not None or getattr(material, key) == new_value):
select_material = False
break
elif key in material and requested_custom_property:
if isinstance(material[key], type(value)) or (isinstance(material[key], int) and isinstance(value, bool)):
if not (isinstance(material[key], str) and re.fullmatch(value, material[key]) is not None or material[key] == value):
select_material = False
break
else:
raise Exception('Types are not matching: {} and {} !'.format(type(material[key]), type(value)))
elif requested_custom_function:
if key.startswith('texture_amount_'):
if material.use_nodes:
value = int(value)
nodes = material.node_tree.nodes
texture_nodes = Utility.get_nodes_with_type(nodes, 'TexImage')
amount_of_texture_nodes = len(texture_nodes) if texture_nodes is not None else 0
if 'min' in key:
if not amount_of_texture_nodes >= value:
select_material = False
break
elif 'max' in key:
if not amount_of_texture_nodes <= value:
select_material = False
break
elif 'eq' in key:
if not amount_of_texture_nodes == value:
select_material = False
break
else:
raise Exception('This type of key is unknown: {}'.format(key))
else:
select_material = False
break
elif key.startswith('principled_bsdf_amount_'):
if material.use_nodes:
value = int(value)
nodes = material.node_tree.nodes
principled = Utility.get_nodes_with_type(nodes, 'BsdfPrincipled')
amount_of_principled_bsdf_nodes = len(principled) if principled is not None else 0
if 'min' in key:
if not amount_of_principled_bsdf_nodes >= value:
select_material = False
break
elif 'max' in key:
if not amount_of_principled_bsdf_nodes <= value:
select_material = False
break
elif 'eq' in key:
if not amount_of_principled_bsdf_nodes == value:
select_material = False
break
else:
raise Exception('This type of key is unknown: {}'.format(key))
else:
select_material = False
break
elif key.startswith('principled_bsdf_'):
if material.use_nodes:
value = float(value)
nodes = material.node_tree.nodes
principled = Utility.get_nodes_with_type(nodes, 'BsdfPrincipled')
amount_of_principled_bsdf_nodes = len(principled) if principled is not None else 0
if amount_of_principled_bsdf_nodes != 1:
select_material = False
break
principled = principled[0]
extracted_input_name = key[len('principled_bsdf_'):key.rfind('_')]
if extracted_input_name not in principled.inputs:
raise Exception('Only valid inputs of a principled node are allowed: {} in: {}'.format(extracted_input_name, key))
used_value = principled.inputs[extracted_input_name]
if len(used_value.links) > 0:
select_material = False
break
used_value = used_value.default_value
if key.endswith('min'):
if not used_value >= value:
select_material = False
break
elif key.endswith('max'):
if not used_value <= value:
select_material = False
break
elif key.endswith('eq'):
if not used_value == value:
select_material = False
break
else:
raise Exception('This type of key is unknown: {}'.format(key))
else:
select_material = False
break
elif key == 'use_materials_of_objects':
objects = Utility.build_provider_based_on_config(value).run()
found_material = False
for obj in objects:
if hasattr(obj, 'material_slots'):
for mat_slot in obj.material_slots:
if mat_slot.material == material:
found_material = True
break
if found_material:
break
if not found_material:
select_material = False
break
else:
select_material = False
break
else:
select_material = False
break
if select_material:
new_materials.append(material)
[] = new_materials
random_samples = self.config.get_int('random_samples', 0)
has_index = self.config.has_param('index')
if has_index and (not random_samples):
materials = [materials[self.config.get_int('index')]]
elif random_samples and (not has_index):
materials = sample(materials, k=min(random_samples, len(materials)))
elif has_index and random_samples:
raise RuntimeError('Please, define only one of two: `index` or `random_samples`.')
check_if_return_is_empty = self.config.get_bool('check_empty', False)
if check_if_return_is_empty and (not materials):
raise Exception(f'There were no materials selected with the following condition: \n{self._get_conditions_as_string()}')
return materials
|
BlenderProc
|
positive
|
def call(self, inputs):
"""Implements call() for the layer."""
unpacked_inputs = tf_utils.unpack_inputs(inputs)
lm_output = unpacked_inputs[0]
sentence_output = unpacked_inputs[1]
lm_label_ids = unpacked_inputs[2]
lm_label_weights = tf.keras.backend.cast(unpacked_inputs[3], tf.float32)
sentence_labels = unpacked_inputs[4]
mask_label_loss = losses.weighted_sparse_categorical_crossentropy_loss(labels=lm_label_ids, predictions=lm_output, weights=lm_label_weights)
sentence_loss = losses.weighted_sparse_categorical_crossentropy_loss(labels=sentence_labels, predictions=sentence_output)
loss = mask_label_loss + sentence_loss
batch_shape = tf.slice(tf.keras.backend.shape(sentence_labels), [0], [1])
final_loss = tf.fill(batch_shape, loss)
<DeepExtract>
masked_lm_accuracy = tf.keras.metrics.sparse_categorical_accuracy(lm_label_ids, lm_output)
numerator = tf.reduce_sum(masked_lm_accuracy * lm_label_weights)
denominator = tf.reduce_sum(lm_label_weights) + 1e-05
masked_lm_accuracy = numerator / denominator
self.add_metric(masked_lm_accuracy, name='masked_lm_accuracy', aggregation='mean')
self.add_metric(mask_label_loss, name='lm_example_loss', aggregation='mean')
next_sentence_accuracy = tf.keras.metrics.sparse_categorical_accuracy(sentence_labels, sentence_output)
self.add_metric(next_sentence_accuracy, name='next_sentence_accuracy', aggregation='mean')
self.add_metric(sentence_loss, name='next_sentence_loss', aggregation='mean')
</DeepExtract>
return final_loss
|
def call(self, inputs):
"""Implements call() for the layer."""
unpacked_inputs = tf_utils.unpack_inputs(inputs)
lm_output = unpacked_inputs[0]
sentence_output = unpacked_inputs[1]
lm_label_ids = unpacked_inputs[2]
lm_label_weights = tf.keras.backend.cast(unpacked_inputs[3], tf.float32)
sentence_labels = unpacked_inputs[4]
mask_label_loss = losses.weighted_sparse_categorical_crossentropy_loss(labels=lm_label_ids, predictions=lm_output, weights=lm_label_weights)
sentence_loss = losses.weighted_sparse_categorical_crossentropy_loss(labels=sentence_labels, predictions=sentence_output)
loss = mask_label_loss + sentence_loss
batch_shape = tf.slice(tf.keras.backend.shape(sentence_labels), [0], [1])
final_loss = tf.fill(batch_shape, loss)
masked_lm_accuracy = tf.keras.metrics.sparse_categorical_accuracy(lm_label_ids, lm_output)
numerator = tf.reduce_sum(masked_lm_accuracy * lm_label_weights)
denominator = tf.reduce_sum(lm_label_weights) + 1e-05
masked_lm_accuracy = numerator / denominator
self.add_metric(masked_lm_accuracy, name='masked_lm_accuracy', aggregation='mean')
self.add_metric(mask_label_loss, name='lm_example_loss', aggregation='mean')
next_sentence_accuracy = tf.keras.metrics.sparse_categorical_accuracy(sentence_labels, sentence_output)
self.add_metric(next_sentence_accuracy, name='next_sentence_accuracy', aggregation='mean')
self.add_metric(sentence_loss, name='next_sentence_loss', aggregation='mean')
return final_loss
|
autodist
|
positive
|
def eval_recalls(gts, proposals, proposal_nums=None, iou_thrs=None, print_summary=True):
"""Calculate recalls.
Args:
gts(list or ndarray): a list of arrays of shape (n, 4)
proposals(list or ndarray): a list of arrays of shape (k, 4) or (k, 5)
proposal_nums(int or list of int or ndarray): top N proposals
thrs(float or list or ndarray): iou thresholds
Returns:
ndarray: recalls of different ious and proposal nums
"""
img_num = len(gts)
assert img_num == len(proposals)
<DeepExtract>
if isinstance(proposal_nums, list):
_proposal_nums = np.array(proposal_nums)
elif isinstance(proposal_nums, int):
_proposal_nums = np.array([proposal_nums])
else:
_proposal_nums = proposal_nums
if iou_thrs is None:
_iou_thrs = np.array([0.5])
elif isinstance(iou_thrs, list):
_iou_thrs = np.array(iou_thrs)
elif isinstance(iou_thrs, float):
_iou_thrs = np.array([iou_thrs])
else:
_iou_thrs = iou_thrs
(proposal_nums, iou_thrs) = (_proposal_nums, _iou_thrs)
</DeepExtract>
all_ious = []
for i in range(img_num):
if proposals[i].ndim == 2 and proposals[i].shape[1] == 5:
scores = proposals[i][:, 4]
sort_idx = np.argsort(scores)[::-1]
img_proposal = proposals[i][sort_idx, :]
else:
img_proposal = proposals[i]
prop_num = min(img_proposal.shape[0], proposal_nums[-1])
if gts[i] is None or gts[i].shape[0] == 0:
ious = np.zeros((0, img_proposal.shape[0]), dtype=np.float32)
else:
ious = bbox_overlaps(gts[i], img_proposal[:prop_num, :4])
all_ious.append(ious)
all_ious = np.array(all_ious)
<DeepExtract>
img_num = all_ious.shape[0]
total_gt_num = sum([ious.shape[0] for ious in all_ious])
_ious = np.zeros((proposal_nums.size, total_gt_num), dtype=np.float32)
for (k, proposal_num) in enumerate(proposal_nums):
tmp_ious = np.zeros(0)
for i in range(img_num):
ious = all_ious[i][:, :proposal_num].copy()
gt_ious = np.zeros(ious.shape[0])
if ious.size == 0:
tmp_ious = np.hstack((tmp_ious, gt_ious))
continue
for j in range(ious.shape[0]):
gt_max_overlaps = ious.argmax(axis=1)
max_ious = ious[np.arange(0, ious.shape[0]), gt_max_overlaps]
gt_idx = max_ious.argmax()
gt_ious[j] = max_ious[gt_idx]
box_idx = gt_max_overlaps[gt_idx]
ious[gt_idx, :] = -1
ious[:, box_idx] = -1
tmp_ious = np.hstack((tmp_ious, gt_ious))
_ious[k, :] = tmp_ious
_ious = np.fliplr(np.sort(_ious, axis=1))
recalls = np.zeros((proposal_nums.size, iou_thrs.size))
for (i, thr) in enumerate(iou_thrs):
recalls[:, i] = (_ious >= thr).sum(axis=1) / float(total_gt_num)
recalls = recalls
</DeepExtract>
if print_summary:
<DeepExtract>
proposal_nums = np.array(proposal_nums, dtype=np.int32)
iou_thrs = np.array(iou_thrs)
if row_idxs is None:
row_idxs = np.arange(proposal_nums.size)
if col_idxs is None:
col_idxs = np.arange(iou_thrs.size)
row_header = [''] + iou_thrs[col_idxs].tolist()
table_data = [row_header]
for (i, num) in enumerate(proposal_nums[row_idxs]):
row = ['{:.3f}'.format(val) for val in recalls[row_idxs[i], col_idxs].tolist()]
row.insert(0, num)
table_data.append(row)
table = AsciiTable(table_data)
print(table.table)
</DeepExtract>
return recalls
|
def eval_recalls(gts, proposals, proposal_nums=None, iou_thrs=None, print_summary=True):
"""Calculate recalls.
Args:
gts(list or ndarray): a list of arrays of shape (n, 4)
proposals(list or ndarray): a list of arrays of shape (k, 4) or (k, 5)
proposal_nums(int or list of int or ndarray): top N proposals
thrs(float or list or ndarray): iou thresholds
Returns:
ndarray: recalls of different ious and proposal nums
"""
img_num = len(gts)
assert img_num == len(proposals)
if isinstance(proposal_nums, list):
_proposal_nums = np.array(proposal_nums)
elif isinstance(proposal_nums, int):
_proposal_nums = np.array([proposal_nums])
else:
_proposal_nums = proposal_nums
if iou_thrs is None:
_iou_thrs = np.array([0.5])
elif isinstance(iou_thrs, list):
_iou_thrs = np.array(iou_thrs)
elif isinstance(iou_thrs, float):
_iou_thrs = np.array([iou_thrs])
else:
_iou_thrs = iou_thrs
(proposal_nums, iou_thrs) = (_proposal_nums, _iou_thrs)
all_ious = []
for i in range(img_num):
if proposals[i].ndim == 2 and proposals[i].shape[1] == 5:
scores = proposals[i][:, 4]
sort_idx = np.argsort(scores)[::-1]
img_proposal = proposals[i][sort_idx, :]
else:
img_proposal = proposals[i]
prop_num = min(img_proposal.shape[0], proposal_nums[-1])
if gts[i] is None or gts[i].shape[0] == 0:
ious = np.zeros((0, img_proposal.shape[0]), dtype=np.float32)
else:
ious = bbox_overlaps(gts[i], img_proposal[:prop_num, :4])
all_ious.append(ious)
all_ious = np.array(all_ious)
img_num = all_ious.shape[0]
total_gt_num = sum([ious.shape[0] for ious in all_ious])
_ious = np.zeros((proposal_nums.size, total_gt_num), dtype=np.float32)
for (k, proposal_num) in enumerate(proposal_nums):
tmp_ious = np.zeros(0)
for i in range(img_num):
ious = all_ious[i][:, :proposal_num].copy()
gt_ious = np.zeros(ious.shape[0])
if ious.size == 0:
tmp_ious = np.hstack((tmp_ious, gt_ious))
continue
for j in range(ious.shape[0]):
gt_max_overlaps = ious.argmax(axis=1)
max_ious = ious[np.arange(0, ious.shape[0]), gt_max_overlaps]
gt_idx = max_ious.argmax()
gt_ious[j] = max_ious[gt_idx]
box_idx = gt_max_overlaps[gt_idx]
ious[gt_idx, :] = -1
ious[:, box_idx] = -1
tmp_ious = np.hstack((tmp_ious, gt_ious))
_ious[k, :] = tmp_ious
_ious = np.fliplr(np.sort(_ious, axis=1))
recalls = np.zeros((proposal_nums.size, iou_thrs.size))
for (i, thr) in enumerate(iou_thrs):
recalls[:, i] = (_ious >= thr).sum(axis=1) / float(total_gt_num)
recalls = recalls
if print_summary:
proposal_nums = np.array(proposal_nums, dtype=np.int32)
iou_thrs = np.array(iou_thrs)
if row_idxs is None:
row_idxs = np.arange(proposal_nums.size)
if col_idxs is None:
col_idxs = np.arange(iou_thrs.size)
row_header = [''] + iou_thrs[col_idxs].tolist()
table_data = [row_header]
for (i, num) in enumerate(proposal_nums[row_idxs]):
row = ['{:.3f}'.format(val) for val in recalls[row_idxs[i], col_idxs].tolist()]
row.insert(0, num)
table_data.append(row)
table = AsciiTable(table_data)
print(table.table)
return recalls
|
Cascade-RPN
|
positive
|
def test_fluid(self):
if ig is not None:
<DeepExtract>
g = nx.karate_club_graph()
node_map = {}
for n in g.nodes():
node_map[n] = '$%s$' % n
nx.relabel_nodes(g, node_map, False)
g = g
</DeepExtract>
coms = algorithms.async_fluid(g, 3)
self.assertEqual(type(coms.communities), list)
if len(coms.communities) > 0:
self.assertEqual(type(coms.communities[0]), list)
self.assertEqual(type(coms.communities[0][0]), str)
|
def test_fluid(self):
if ig is not None:
g = nx.karate_club_graph()
node_map = {}
for n in g.nodes():
node_map[n] = '$%s$' % n
nx.relabel_nodes(g, node_map, False)
g = g
coms = algorithms.async_fluid(g, 3)
self.assertEqual(type(coms.communities), list)
if len(coms.communities) > 0:
self.assertEqual(type(coms.communities[0]), list)
self.assertEqual(type(coms.communities[0][0]), str)
|
cdlib
|
positive
|
def fermat_little_theorem(p):
"""Returns 1 if p may be prime, and something else if p definitely
is not prime"""
<DeepExtract>
min_nbits = 32
range = p - 1 - 1
rangebytes = ceil(math.log(range, 2) / 8.0)
rangebits = max(rangebytes * 8, min_nbits * 2)
nbits = random.randint(min_nbits, rangebits)
a = read_random_int(nbits) % range + 1
</DeepExtract>
return fast_exponentiation(a, p - 1, p)
|
def fermat_little_theorem(p):
"""Returns 1 if p may be prime, and something else if p definitely
is not prime"""
min_nbits = 32
range = p - 1 - 1
rangebytes = ceil(math.log(range, 2) / 8.0)
rangebits = max(rangebytes * 8, min_nbits * 2)
nbits = random.randint(min_nbits, rangebits)
a = read_random_int(nbits) % range + 1
return fast_exponentiation(a, p - 1, p)
|
baidupan_shell
|
positive
|
@force_fp32(apply_to=('cls_scores', 'bbox_preds'))
def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg, rescale=False):
"""
Transform network output for a batch into labeled boxes.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
Has shape (N, num_anchors * num_classes, H, W)
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (N, num_anchors * 4, H, W)
img_metas (list[dict]): size / scale info for each image
cfg (mmcv.Config): test / postprocessing configuration
rescale (bool): if True, return boxes in original image space
Returns:
list[tuple[Tensor, Tensor]]: each item in result_list is 2-tuple.
The first item is an (n, 5) tensor, where the first 4 columns
are bounding box positions (tl_x, tl_y, br_x, br_y) and the
5-th column is a score between 0 and 1. The second item is a
(n,) tensor where each item is the class index of the
corresponding box.
Example:
>>> import mmcv
>>> self = AnchorHead(num_classes=9, in_channels=1)
>>> img_metas = [{'img_shape': (32, 32, 3), 'scale_factor': 1}]
>>> cfg = mmcv.Config(dict(
>>> score_thr=0.00,
>>> nms=dict(type='nms', iou_thr=1.0),
>>> max_per_img=10))
>>> feat = torch.rand(1, 1, 3, 3)
>>> cls_score, bbox_pred = self.forward_single(feat)
>>> # note the input lists are over different levels, not images
>>> cls_scores, bbox_preds = [cls_score], [bbox_pred]
>>> result_list = self.get_bboxes(cls_scores, bbox_preds,
>>> img_metas, cfg)
>>> det_bboxes, det_labels = result_list[0]
>>> assert len(result_list) == 1
>>> assert det_bboxes.shape[1] == 5
>>> assert len(det_bboxes) == len(det_labels) == cfg.max_per_img
"""
assert len(cls_scores) == len(bbox_preds)
num_levels = len(cls_scores)
device = cls_scores[0].device
mlvl_anchors = [self.anchor_generators[i].grid_anchors(cls_scores[i].size()[-2:], self.anchor_strides[i], device=device) for i in range(num_levels)]
result_list = []
for img_id in range(len(img_metas)):
cls_score_list = [cls_scores[i][img_id].detach() for i in range(num_levels)]
bbox_pred_list = [bbox_preds[i][img_id].detach() for i in range(num_levels)]
img_shape = img_metas[img_id]['img_shape']
scale_factor = img_metas[img_id]['scale_factor']
<DeepExtract>
assert len(cls_score_list) == len(bbox_pred_list) == len(mlvl_anchors)
mlvl_bboxes = []
mlvl_scores = []
for (cls_score, bbox_pred, anchors) in zip(cls_score_list, bbox_pred_list, mlvl_anchors):
assert cls_score.size()[-2:] == bbox_pred.size()[-2:]
cls_score = cls_score.permute(1, 2, 0).reshape(-1, self.cls_out_channels)
if self.use_sigmoid_cls:
scores = cls_score.sigmoid()
else:
scores = cls_score.softmax(-1)
bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4)
nms_pre = cfg.get('nms_pre', -1)
if nms_pre > 0 and scores.shape[0] > nms_pre:
if self.use_sigmoid_cls:
(max_scores, _) = scores.max(dim=1)
else:
(max_scores, _) = scores[:, 1:].max(dim=1)
(_, topk_inds) = max_scores.topk(nms_pre)
anchors = anchors[topk_inds, :]
bbox_pred = bbox_pred[topk_inds, :]
scores = scores[topk_inds, :]
bboxes = delta2bbox(anchors, bbox_pred, self.target_means, self.target_stds, img_shape)
mlvl_bboxes.append(bboxes)
mlvl_scores.append(scores)
mlvl_bboxes = torch.cat(mlvl_bboxes)
if rescale:
mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor)
mlvl_scores = torch.cat(mlvl_scores)
if self.use_sigmoid_cls:
padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)
mlvl_scores = torch.cat([padding, mlvl_scores], dim=1)
(det_bboxes, det_labels) = multiclass_nms(mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img)
proposals = (det_bboxes, det_labels)
</DeepExtract>
result_list.append(proposals)
return result_list
|
@force_fp32(apply_to=('cls_scores', 'bbox_preds'))
def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg, rescale=False):
"""
Transform network output for a batch into labeled boxes.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
Has shape (N, num_anchors * num_classes, H, W)
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (N, num_anchors * 4, H, W)
img_metas (list[dict]): size / scale info for each image
cfg (mmcv.Config): test / postprocessing configuration
rescale (bool): if True, return boxes in original image space
Returns:
list[tuple[Tensor, Tensor]]: each item in result_list is 2-tuple.
The first item is an (n, 5) tensor, where the first 4 columns
are bounding box positions (tl_x, tl_y, br_x, br_y) and the
5-th column is a score between 0 and 1. The second item is a
(n,) tensor where each item is the class index of the
corresponding box.
Example:
>>> import mmcv
>>> self = AnchorHead(num_classes=9, in_channels=1)
>>> img_metas = [{'img_shape': (32, 32, 3), 'scale_factor': 1}]
>>> cfg = mmcv.Config(dict(
>>> score_thr=0.00,
>>> nms=dict(type='nms', iou_thr=1.0),
>>> max_per_img=10))
>>> feat = torch.rand(1, 1, 3, 3)
>>> cls_score, bbox_pred = self.forward_single(feat)
>>> # note the input lists are over different levels, not images
>>> cls_scores, bbox_preds = [cls_score], [bbox_pred]
>>> result_list = self.get_bboxes(cls_scores, bbox_preds,
>>> img_metas, cfg)
>>> det_bboxes, det_labels = result_list[0]
>>> assert len(result_list) == 1
>>> assert det_bboxes.shape[1] == 5
>>> assert len(det_bboxes) == len(det_labels) == cfg.max_per_img
"""
assert len(cls_scores) == len(bbox_preds)
num_levels = len(cls_scores)
device = cls_scores[0].device
mlvl_anchors = [self.anchor_generators[i].grid_anchors(cls_scores[i].size()[-2:], self.anchor_strides[i], device=device) for i in range(num_levels)]
result_list = []
for img_id in range(len(img_metas)):
cls_score_list = [cls_scores[i][img_id].detach() for i in range(num_levels)]
bbox_pred_list = [bbox_preds[i][img_id].detach() for i in range(num_levels)]
img_shape = img_metas[img_id]['img_shape']
scale_factor = img_metas[img_id]['scale_factor']
assert len(cls_score_list) == len(bbox_pred_list) == len(mlvl_anchors)
mlvl_bboxes = []
mlvl_scores = []
for (cls_score, bbox_pred, anchors) in zip(cls_score_list, bbox_pred_list, mlvl_anchors):
assert cls_score.size()[-2:] == bbox_pred.size()[-2:]
cls_score = cls_score.permute(1, 2, 0).reshape(-1, self.cls_out_channels)
if self.use_sigmoid_cls:
scores = cls_score.sigmoid()
else:
scores = cls_score.softmax(-1)
bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4)
nms_pre = cfg.get('nms_pre', -1)
if nms_pre > 0 and scores.shape[0] > nms_pre:
if self.use_sigmoid_cls:
(max_scores, _) = scores.max(dim=1)
else:
(max_scores, _) = scores[:, 1:].max(dim=1)
(_, topk_inds) = max_scores.topk(nms_pre)
anchors = anchors[topk_inds, :]
bbox_pred = bbox_pred[topk_inds, :]
scores = scores[topk_inds, :]
bboxes = delta2bbox(anchors, bbox_pred, self.target_means, self.target_stds, img_shape)
mlvl_bboxes.append(bboxes)
mlvl_scores.append(scores)
mlvl_bboxes = torch.cat(mlvl_bboxes)
if rescale:
mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor)
mlvl_scores = torch.cat(mlvl_scores)
if self.use_sigmoid_cls:
padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)
mlvl_scores = torch.cat([padding, mlvl_scores], dim=1)
(det_bboxes, det_labels) = multiclass_nms(mlvl_bboxes, mlvl_scores, cfg.score_thr, cfg.nms, cfg.max_per_img)
proposals = (det_bboxes, det_labels)
result_list.append(proposals)
return result_list
|
AE_TextSpotter
|
positive
|
def test_about(self):
"""Opens the about dialog and closes it"""
about = self.app.get_about_dialog()
about.show_all()
<DeepExtract>
while Gtk.events_pending():
Gtk.main_iteration_do(blocking=False)
time.sleep(delay)
</DeepExtract>
about.destroy()
|
def test_about(self):
"""Opens the about dialog and closes it"""
about = self.app.get_about_dialog()
about.show_all()
while Gtk.events_pending():
Gtk.main_iteration_do(blocking=False)
time.sleep(delay)
about.destroy()
|
bleachbit
|
positive
|
def init_iou_net(self):
self.iou_predictor = self.params.features.get_unique_attribute('iou_predictor')
for p in self.iou_predictor.parameters():
p.requires_grad = False
<DeepExtract>
box_center = (self.pos - self.pos.round()) / self.target_scale + (self.iou_img_sample_sz - 1) / 2
box_sz = self.target_sz / self.target_scale
target_ul = box_center - (box_sz - 1) / 2
self.classifier_target_box = torch.cat([target_ul.flip((0,)), box_sz.flip((0,))])
</DeepExtract>
target_boxes = TensorList()
if self.params.iounet_augmentation:
for T in self.transforms:
if not isinstance(T, (augmentation.Identity, augmentation.Translation, augmentation.FlipHorizontal, augmentation.FlipVertical, augmentation.Blur)):
break
target_boxes.append(self.classifier_target_box + torch.Tensor([T.shift[1], T.shift[0], 0, 0]))
else:
target_boxes.append(self.classifier_target_box.clone())
target_boxes = torch.cat(target_boxes.view(1, 4), 0).to(self.params.device)
<DeepExtract>
feat = self.params.features.get_unique_attribute('iounet_backbone_features')
iou_res_features = feat
</DeepExtract>
iou_res_features = TensorList([x[:target_boxes.shape[0], ...] for x in iou_res_features])
with torch.no_grad():
target_feat = self.iou_predictor.get_filter(iou_res_features, target_boxes)
self.iou_filter = TensorList([x.detach().mean(0) for x in target_feat])
if getattr(self.params, 'iounet_not_use_reference', False):
self.iou_filter = TensorList([torch.full_like(tf, tf.norm() / tf.numel()) for tf in self.iou_filter])
|
def init_iou_net(self):
self.iou_predictor = self.params.features.get_unique_attribute('iou_predictor')
for p in self.iou_predictor.parameters():
p.requires_grad = False
box_center = (self.pos - self.pos.round()) / self.target_scale + (self.iou_img_sample_sz - 1) / 2
box_sz = self.target_sz / self.target_scale
target_ul = box_center - (box_sz - 1) / 2
self.classifier_target_box = torch.cat([target_ul.flip((0,)), box_sz.flip((0,))])
target_boxes = TensorList()
if self.params.iounet_augmentation:
for T in self.transforms:
if not isinstance(T, (augmentation.Identity, augmentation.Translation, augmentation.FlipHorizontal, augmentation.FlipVertical, augmentation.Blur)):
break
target_boxes.append(self.classifier_target_box + torch.Tensor([T.shift[1], T.shift[0], 0, 0]))
else:
target_boxes.append(self.classifier_target_box.clone())
target_boxes = torch.cat(target_boxes.view(1, 4), 0).to(self.params.device)
feat = self.params.features.get_unique_attribute('iounet_backbone_features')
iou_res_features = feat
iou_res_features = TensorList([x[:target_boxes.shape[0], ...] for x in iou_res_features])
with torch.no_grad():
target_feat = self.iou_predictor.get_filter(iou_res_features, target_boxes)
self.iou_filter = TensorList([x.detach().mean(0) for x in target_feat])
if getattr(self.params, 'iounet_not_use_reference', False):
self.iou_filter = TensorList([torch.full_like(tf, tf.norm() / tf.numel()) for tf in self.iou_filter])
|
end2end_rgbt_tracking
|
positive
|
def get_bib_info(*infos, logger=None):
"""
Gathers and returns the descriptions and bibliographic sources for the components
mentioned in ``infos``.
``infos`` can be input dictionaries or single component names.
"""
if not logger:
logger_setup()
logger = get_logger('bib')
(used_components, component_infos) = get_used_components(*infos, return_infos=True)
descs: InfoDict = {}
bibs: InfoDict = {}
used_components = get_used_components(*infos)
for (kind, components) in used_components.items():
if kind is None:
continue
(descs[kind], bibs[kind]) = ({}, {})
for component in components:
try:
<DeepExtract>
cls = get_component_class(component, kind)
descs[kind][component] = cleandoc(cls.get_desc(component_infos[component]) or '') + '\n'
</DeepExtract>
<DeepExtract>
cls = get_component_class(component, kind)
lines = (cls.get_bibtex() or '').lstrip('\n').rstrip('\n') or '# [no bibliography information found]'
bibs[kind][component] = lines + '\n'
</DeepExtract>
except ComponentNotFoundError:
sugg = similar_internal_class_names(component)
logger.error(f"Could not identify component '{component}'. Did you mean any of the following? {sugg} (mind capitalization!)")
continue
for component in used_components.get(None, []):
try:
cls = get_component_class(component)
except ComponentNotFoundError:
sugg = similar_internal_class_names(component)
logger.error(f"Could not identify component '{component}'. Did you mean any of the following? {sugg} (mind capitalization!)")
continue
kind = cls.get_kind()
if kind not in descs:
(descs[kind], bibs[kind]) = ({}, {})
if kind in descs and component in descs[kind]:
continue
<DeepExtract>
cls = get_component_class(cls, kind)
descs[kind][cls] = cleandoc(cls.get_desc(info) or '') + '\n'
</DeepExtract>
<DeepExtract>
cls = get_component_class(cls, kind)
lines = (cls.get_bibtex() or '').lstrip('\n').rstrip('\n') or '# [no bibliography information found]'
bibs[kind][cls] = lines + '\n'
</DeepExtract>
descs['cobaya'] = {'cobaya': cobaya_desc}
bibs['cobaya'] = {'cobaya': cobaya_bib}
return (descs, bibs)
|
def get_bib_info(*infos, logger=None):
"""
Gathers and returns the descriptions and bibliographic sources for the components
mentioned in ``infos``.
``infos`` can be input dictionaries or single component names.
"""
if not logger:
logger_setup()
logger = get_logger('bib')
(used_components, component_infos) = get_used_components(*infos, return_infos=True)
descs: InfoDict = {}
bibs: InfoDict = {}
used_components = get_used_components(*infos)
for (kind, components) in used_components.items():
if kind is None:
continue
(descs[kind], bibs[kind]) = ({}, {})
for component in components:
try:
cls = get_component_class(component, kind)
descs[kind][component] = cleandoc(cls.get_desc(component_infos[component]) or '') + '\n'
cls = get_component_class(component, kind)
lines = (cls.get_bibtex() or '').lstrip('\n').rstrip('\n') or '# [no bibliography information found]'
bibs[kind][component] = lines + '\n'
except ComponentNotFoundError:
sugg = similar_internal_class_names(component)
logger.error(f"Could not identify component '{component}'. Did you mean any of the following? {sugg} (mind capitalization!)")
continue
for component in used_components.get(None, []):
try:
cls = get_component_class(component)
except ComponentNotFoundError:
sugg = similar_internal_class_names(component)
logger.error(f"Could not identify component '{component}'. Did you mean any of the following? {sugg} (mind capitalization!)")
continue
kind = cls.get_kind()
if kind not in descs:
(descs[kind], bibs[kind]) = ({}, {})
if kind in descs and component in descs[kind]:
continue
cls = get_component_class(cls, kind)
descs[kind][cls] = cleandoc(cls.get_desc(info) or '') + '\n'
cls = get_component_class(cls, kind)
lines = (cls.get_bibtex() or '').lstrip('\n').rstrip('\n') or '# [no bibliography information found]'
bibs[kind][cls] = lines + '\n'
descs['cobaya'] = {'cobaya': cobaya_desc}
bibs['cobaya'] = {'cobaya': cobaya_bib}
return (descs, bibs)
|
cobaya
|
positive
|
def can_heal(self, healer_id, target_robot_id):
"""Whether the healer can heal the given robot, without taking into account the healer's attack heat. Takes into account only the healer's attack range, and the location of the robot.
:type self: GameController
:type healer_id: int
:type target_robot_id: int
:rtype: bool
"""
assert type(healer_id) is int, 'incorrect type of arg healer_id: should be int, is {}'.format(type(healer_id))
assert type(target_robot_id) is int, 'incorrect type of arg target_robot_id: should be int, is {}'.format(type(target_robot_id))
result = _lib.bc_GameController_can_heal(self._ptr, healer_id, target_robot_id)
<DeepExtract>
if _lib.bc_has_err():
_lasterror = _ffi.new('char**')
err = _lib.bc_get_last_err(_lasterror)
errtext = _ffi.string(_lasterror[0])
_lib.bc_free_string(_lasterror[0])
raise Exception(errtext)
</DeepExtract>
result = bool(result)
return result
|
def can_heal(self, healer_id, target_robot_id):
"""Whether the healer can heal the given robot, without taking into account the healer's attack heat. Takes into account only the healer's attack range, and the location of the robot.
:type self: GameController
:type healer_id: int
:type target_robot_id: int
:rtype: bool
"""
assert type(healer_id) is int, 'incorrect type of arg healer_id: should be int, is {}'.format(type(healer_id))
assert type(target_robot_id) is int, 'incorrect type of arg target_robot_id: should be int, is {}'.format(type(target_robot_id))
result = _lib.bc_GameController_can_heal(self._ptr, healer_id, target_robot_id)
if _lib.bc_has_err():
_lasterror = _ffi.new('char**')
err = _lib.bc_get_last_err(_lasterror)
errtext = _ffi.string(_lasterror[0])
_lib.bc_free_string(_lasterror[0])
raise Exception(errtext)
result = bool(result)
return result
|
bc18-scaffold
|
positive
|
def test_just_partner(self):
<DeepExtract>
self.user.is_superuser = False
self.user.role = ROLE_PARTNER
self.user.save()
self.assertTrue(self.user.is_just_partner())
</DeepExtract>
user2 = CtsUserFactory()
self.shipment.partner = user2
self.shipment.save()
rsp = self.client.get(self.url)
self.assertEqual(404, rsp.status_code)
|
def test_just_partner(self):
self.user.is_superuser = False
self.user.role = ROLE_PARTNER
self.user.save()
self.assertTrue(self.user.is_just_partner())
user2 = CtsUserFactory()
self.shipment.partner = user2
self.shipment.save()
rsp = self.client.get(self.url)
self.assertEqual(404, rsp.status_code)
|
CTS
|
positive
|
def change(self, number):
if number != None:
number = str(number)
else:
number = ''
if self.edit == 'Y':
self.text = self.font.render(number, 1, (0, 0, 0))
<DeepExtract>
screen = pygame.display.get_surface()
AAfilledRoundedRect(screen, (self.offsetX, self.offsetY, 45, 40), self.color)
screen.blit(self.text, self.textpos)
</DeepExtract>
return 0
else:
return 1
|
def change(self, number):
if number != None:
number = str(number)
else:
number = ''
if self.edit == 'Y':
self.text = self.font.render(number, 1, (0, 0, 0))
screen = pygame.display.get_surface()
AAfilledRoundedRect(screen, (self.offsetX, self.offsetY, 45, 40), self.color)
screen.blit(self.text, self.textpos)
return 0
else:
return 1
|
artificial-intelligence
|
positive
|
def dog(pix, a, b, threshold):
"""Difference of Gaussians with a threshold"""
size = max(a, b)
<DeepExtract>
out = cl_builder.new_image(pix.shape[1], pix.shape[0])
cl_nodes['grayscale'].run([], [cl_builder.new_image_from_ndarray(pix)], [out])
gpix = out.to_numpy()
</DeepExtract>
res = (gaussian_repeat(gpix, a) - gaussian_repeat(gpix, b))[..., :3]
tt = threshold / size
pix[..., :3] = np.where(tt >= res, 1.0, 1.0 + np.tanh(40.0 * (tt - res)))
return pix
|
def dog(pix, a, b, threshold):
"""Difference of Gaussians with a threshold"""
size = max(a, b)
out = cl_builder.new_image(pix.shape[1], pix.shape[0])
cl_nodes['grayscale'].run([], [cl_builder.new_image_from_ndarray(pix)], [out])
gpix = out.to_numpy()
res = (gaussian_repeat(gpix, a) - gaussian_repeat(gpix, b))[..., :3]
tt = threshold / size
pix[..., :3] = np.where(tt >= res, 1.0, 1.0 + np.tanh(40.0 * (tt - res)))
return pix
|
blender-texture-tools
|
positive
|
def __init__(self, result, args):
self.args = {argname: ChHandle(x=arg) for (argname, arg) in list(args.items())}
for (argname, arg) in list(self.args.items()):
setattr(result, argname, arg)
if result.is_dr_wrt(arg.x):
<DeepExtract>
self.dterms = list(set(list(self.dterms) + [argname]))
setattr(self, argname, arg.x)
</DeepExtract>
else:
self.terms.append(argname)
setattr(self, argname, arg.x)
self._result = result
|
def __init__(self, result, args):
self.args = {argname: ChHandle(x=arg) for (argname, arg) in list(args.items())}
for (argname, arg) in list(self.args.items()):
setattr(result, argname, arg)
if result.is_dr_wrt(arg.x):
self.dterms = list(set(list(self.dterms) + [argname]))
setattr(self, argname, arg.x)
else:
self.terms.append(argname)
setattr(self, argname, arg.x)
self._result = result
|
chumpy
|
positive
|
def get_result_dict(self, image):
<DeepExtract>
image = self.transforms(image)
image_list = to_image_list(image, self.cfg.DATALOADER.SIZE_DIVISIBILITY)
image_list = image_list.to(self.device)
with torch.no_grad():
predictions = self.model(image_list)
predictions = [o.to(self.cpu_device) for o in predictions]
prediction = predictions[0]
(height, width) = image.shape[:-1]
prediction = prediction.resize((width, height))
if prediction.has_field('mask'):
masks = prediction.get_field('mask')
masks = self.masker([masks], [prediction])[0]
prediction.add_field('mask', masks)
predictions = prediction
</DeepExtract>
<DeepExtract>
scores = predictions.get_field('scores')
keep = torch.nonzero(scores > self.confidence_threshold).squeeze(1)
predictions = predictions[keep]
scores = predictions.get_field('scores')
(_, idx) = scores.sort(0, descending=True)
top_predictions = predictions[idx]
</DeepExtract>
result_dict = {i: [] for i in range(len(self.CATEGORIES))}
labels = top_predictions.get_field('labels').numpy()
scores = top_predictions.get_field('scores').numpy()
bbox = top_predictions.bbox.numpy()
for (idx, l) in enumerate(labels):
result_dict[l].append(np.concatenate([bbox[idx, :], scores[idx:idx + 1]]))
return result_dict
|
def get_result_dict(self, image):
image = self.transforms(image)
image_list = to_image_list(image, self.cfg.DATALOADER.SIZE_DIVISIBILITY)
image_list = image_list.to(self.device)
with torch.no_grad():
predictions = self.model(image_list)
predictions = [o.to(self.cpu_device) for o in predictions]
prediction = predictions[0]
(height, width) = image.shape[:-1]
prediction = prediction.resize((width, height))
if prediction.has_field('mask'):
masks = prediction.get_field('mask')
masks = self.masker([masks], [prediction])[0]
prediction.add_field('mask', masks)
predictions = prediction
scores = predictions.get_field('scores')
keep = torch.nonzero(scores > self.confidence_threshold).squeeze(1)
predictions = predictions[keep]
scores = predictions.get_field('scores')
(_, idx) = scores.sort(0, descending=True)
top_predictions = predictions[idx]
result_dict = {i: [] for i in range(len(self.CATEGORIES))}
labels = top_predictions.get_field('labels').numpy()
scores = top_predictions.get_field('scores').numpy()
bbox = top_predictions.bbox.numpy()
for (idx, l) in enumerate(labels):
result_dict[l].append(np.concatenate([bbox[idx, :], scores[idx:idx + 1]]))
return result_dict
|
DRG
|
positive
|
def test_deleted_user(db):
<DeepExtract>
with auth_api_session() as (auth_api, metadata_interceptor):
res = auth_api.SignupFlow(auth_pb2.SignupFlowReq(basic=auth_pb2.SignupBasic(name='testing', email='email@couchers.org.invalid'), account=auth_pb2.SignupAccount(username='frodo', password='a very insecure password', birthdate='1970-01-01', gender='Bot', hosting_status=api_pb2.HOSTING_STATUS_CAN_HOST, city='New York City', lat=40.7331, lng=-73.9778, radius=500, accept_tos=True), feedback=auth_pb2.ContributorForm(), accept_community_guidelines=wrappers_pb2.BoolValue(value=True)))
flow_token = res.flow_token
assert res.flow_token
assert not res.HasField('auth_res')
assert not res.need_basic
assert not res.need_account
assert not res.need_feedback
assert res.need_verify_email
with session_scope() as session:
flow = session.execute(select(SignupFlow).where(SignupFlow.flow_token == flow_token)).scalar_one()
assert flow.email_sent
assert not flow.email_verified
email_token = flow.email_token
with auth_api_session() as (auth_api, metadata_interceptor):
res = auth_api.SignupFlow(auth_pb2.SignupFlowReq(email_token=email_token))
assert not res.flow_token
assert res.HasField('auth_res')
assert res.auth_res.user_id
assert not res.auth_res.jailed
assert not res.need_basic
assert not res.need_account
assert not res.need_feedback
assert not res.need_verify_email
user_id = res.auth_res.user_id
with session_scope() as session:
token = session.execute(select(UserSession).join(User, UserSession.user_id == User.id).where(User.username == 'frodo')).scalar_one().token
assert get_session_cookie_token(metadata_interceptor) == token
</DeepExtract>
with session_scope() as session:
session.execute(select(User)).scalar_one().is_deleted = True
with auth_api_session() as (auth_api, metadata_interceptor):
with pytest.raises(grpc.RpcError) as e:
reply = auth_api.Login(auth_pb2.LoginReq(user='frodo'))
assert e.value.code() == grpc.StatusCode.NOT_FOUND
assert e.value.details() == errors.USER_NOT_FOUND
|
def test_deleted_user(db):
with auth_api_session() as (auth_api, metadata_interceptor):
res = auth_api.SignupFlow(auth_pb2.SignupFlowReq(basic=auth_pb2.SignupBasic(name='testing', email='email@couchers.org.invalid'), account=auth_pb2.SignupAccount(username='frodo', password='a very insecure password', birthdate='1970-01-01', gender='Bot', hosting_status=api_pb2.HOSTING_STATUS_CAN_HOST, city='New York City', lat=40.7331, lng=-73.9778, radius=500, accept_tos=True), feedback=auth_pb2.ContributorForm(), accept_community_guidelines=wrappers_pb2.BoolValue(value=True)))
flow_token = res.flow_token
assert res.flow_token
assert not res.HasField('auth_res')
assert not res.need_basic
assert not res.need_account
assert not res.need_feedback
assert res.need_verify_email
with session_scope() as session:
flow = session.execute(select(SignupFlow).where(SignupFlow.flow_token == flow_token)).scalar_one()
assert flow.email_sent
assert not flow.email_verified
email_token = flow.email_token
with auth_api_session() as (auth_api, metadata_interceptor):
res = auth_api.SignupFlow(auth_pb2.SignupFlowReq(email_token=email_token))
assert not res.flow_token
assert res.HasField('auth_res')
assert res.auth_res.user_id
assert not res.auth_res.jailed
assert not res.need_basic
assert not res.need_account
assert not res.need_feedback
assert not res.need_verify_email
user_id = res.auth_res.user_id
with session_scope() as session:
token = session.execute(select(UserSession).join(User, UserSession.user_id == User.id).where(User.username == 'frodo')).scalar_one().token
assert get_session_cookie_token(metadata_interceptor) == token
with session_scope() as session:
session.execute(select(User)).scalar_one().is_deleted = True
with auth_api_session() as (auth_api, metadata_interceptor):
with pytest.raises(grpc.RpcError) as e:
reply = auth_api.Login(auth_pb2.LoginReq(user='frodo'))
assert e.value.code() == grpc.StatusCode.NOT_FOUND
assert e.value.details() == errors.USER_NOT_FOUND
|
couchers
|
positive
|
def velocity(self, ix, mytime):
force = self.force
damper = self.damper
(x, y, z) = self.ptslix[ix]
xy = ix % (self.obj2.dimU * self.obj2.dimV)
xp = xy // self.obj2.dimV
yp = xy % self.obj2.dimV
self.pvs[xp, yp] += force(x, y, z, self.pvs[xp, yp], mytime)
print(ix, xy, xp, yp, force(x, y, z, self.pvs[xp, yp], mytime))
tt = self.pvs[xp, yp]
(dx, dy, dz) = damper(x, y, z, self.pvs[xp, yp], mytime)
self.pvs[xp, yp] *= damper(x, y, z, self.pvs[xp, yp], mytime)
(xn, yn, zn) = (x + tt[0], y + tt[1], z + tt[2])
(ddx, ddy, ddz) = (self.obj2.damperWall.x, self.obj2.damperWall.y, self.obj2.damperWall.z)
if self.obj2.boundMode == 'Bound Box':
if zn <= 0:
if xn > self.xmax:
xn = self.xmax - ddx * (xn - self.xmax)
self.pvs[xp, yp][0] *= -1
if xn < self.xmin:
xn = self.xmin - ddx * (xn - self.xmin)
self.pvs[xp, yp][0] *= -1
if yn > self.ymax:
yn = self.ymax - ddy * (yn - self.ymax)
self.pvs[xp, yp][1] *= -1
if yn < self.ymin:
yn = self.ymin - ddy * (yn - self.ymin)
self.pvs[xp, yp][1] *= -1
if zn > self.zmax:
zn = self.zmax - ddz * (zn - self.zmax)
self.pvs[xp, yp][2] *= -1
if zn < self.zmin:
zn = self.zmin - ddz * (zn - self.zmin)
self.pvs[xp, yp][2] *= -1
elif self.obj2.boundMode == 'Bound Cylinder':
r = 40
r = max(self.xmax, self.ymax)
if xn ** 2 + yn ** 2 > r ** 2:
try:
<DeepExtract>
v1 = xn - x
v2 = yn - y
rv2 = v1 ** 2 + v2 ** 2
zz = -(x * v1 + y * v2) / rv2
D = zz ** 2 - (x ** 2 + y ** 2 - r ** 2) / rv2
if D < 0:
if D > -20:
D = 0
t = zz + np.sqrt(D)
x2 = x + v1 * t
y2 = y + v2 * t
x2 = 0.95 * x2
y2 = 0.95 * y2
(x2, y2) = (x2, y2)
</DeepExtract>
try:
<DeepExtract>
dir = FreeCAD.Vector(x2, y2, 0)
pnt = FreeCAD.Vector(x, y, 0)
diff = FreeCAD.Vector()
diff.projectToLine(pnt, dir)
proj = pnt + diff
mirr = proj + diff
(x2, y2) = (mirr.x, mirr.y)
</DeepExtract>
except:
sayexc('')
(xn, yn) = (x2, y2)
self.pvs[xp, yp][0] = -0.5 * xn
self.pvs[xp, yp][1] = -0.5 * yn
except:
pass
if zn < self.zmin:
zn = self.zmin - ddz * (zn - self.zmin)
self.pvs[xp, yp][2] *= -1
elif self.obj2.boundMode == 'no Bounds':
pass
else:
sayErr('nont implemented mode' + self.obj2.boundMode)
rr = 1
rr = self.obj2.noise
if zn < -5:
(xn, yn, zn) = (xn + rr * (0.5 - random.random()), yn + rr * (0.5 - random.random()), zn + rr * (0.5 - random.random()))
self.ptslix[ix + self.obj2.dimU * self.obj2.dimV] = [xn, yn, zn]
return self.ptslix[ix + self.obj2.dimU * self.obj2.dimV]
|
def velocity(self, ix, mytime):
force = self.force
damper = self.damper
(x, y, z) = self.ptslix[ix]
xy = ix % (self.obj2.dimU * self.obj2.dimV)
xp = xy // self.obj2.dimV
yp = xy % self.obj2.dimV
self.pvs[xp, yp] += force(x, y, z, self.pvs[xp, yp], mytime)
print(ix, xy, xp, yp, force(x, y, z, self.pvs[xp, yp], mytime))
tt = self.pvs[xp, yp]
(dx, dy, dz) = damper(x, y, z, self.pvs[xp, yp], mytime)
self.pvs[xp, yp] *= damper(x, y, z, self.pvs[xp, yp], mytime)
(xn, yn, zn) = (x + tt[0], y + tt[1], z + tt[2])
(ddx, ddy, ddz) = (self.obj2.damperWall.x, self.obj2.damperWall.y, self.obj2.damperWall.z)
if self.obj2.boundMode == 'Bound Box':
if zn <= 0:
if xn > self.xmax:
xn = self.xmax - ddx * (xn - self.xmax)
self.pvs[xp, yp][0] *= -1
if xn < self.xmin:
xn = self.xmin - ddx * (xn - self.xmin)
self.pvs[xp, yp][0] *= -1
if yn > self.ymax:
yn = self.ymax - ddy * (yn - self.ymax)
self.pvs[xp, yp][1] *= -1
if yn < self.ymin:
yn = self.ymin - ddy * (yn - self.ymin)
self.pvs[xp, yp][1] *= -1
if zn > self.zmax:
zn = self.zmax - ddz * (zn - self.zmax)
self.pvs[xp, yp][2] *= -1
if zn < self.zmin:
zn = self.zmin - ddz * (zn - self.zmin)
self.pvs[xp, yp][2] *= -1
elif self.obj2.boundMode == 'Bound Cylinder':
r = 40
r = max(self.xmax, self.ymax)
if xn ** 2 + yn ** 2 > r ** 2:
try:
v1 = xn - x
v2 = yn - y
rv2 = v1 ** 2 + v2 ** 2
zz = -(x * v1 + y * v2) / rv2
D = zz ** 2 - (x ** 2 + y ** 2 - r ** 2) / rv2
if D < 0:
if D > -20:
D = 0
t = zz + np.sqrt(D)
x2 = x + v1 * t
y2 = y + v2 * t
x2 = 0.95 * x2
y2 = 0.95 * y2
(x2, y2) = (x2, y2)
try:
dir = FreeCAD.Vector(x2, y2, 0)
pnt = FreeCAD.Vector(x, y, 0)
diff = FreeCAD.Vector()
diff.projectToLine(pnt, dir)
proj = pnt + diff
mirr = proj + diff
(x2, y2) = (mirr.x, mirr.y)
except:
sayexc('')
(xn, yn) = (x2, y2)
self.pvs[xp, yp][0] = -0.5 * xn
self.pvs[xp, yp][1] = -0.5 * yn
except:
pass
if zn < self.zmin:
zn = self.zmin - ddz * (zn - self.zmin)
self.pvs[xp, yp][2] *= -1
elif self.obj2.boundMode == 'no Bounds':
pass
else:
sayErr('nont implemented mode' + self.obj2.boundMode)
rr = 1
rr = self.obj2.noise
if zn < -5:
(xn, yn, zn) = (xn + rr * (0.5 - random.random()), yn + rr * (0.5 - random.random()), zn + rr * (0.5 - random.random()))
self.ptslix[ix + self.obj2.dimU * self.obj2.dimV] = [xn, yn, zn]
return self.ptslix[ix + self.obj2.dimU * self.obj2.dimV]
|
Animation
|
positive
|
def publish(self, path, handler):
"""
Add a handler for a specific path.
:param path: Path to be handled.
:param handler: Content to return, either a bytestring or a function
that returns one.
"""
<DeepExtract>
if path.startswith('/'):
path = path
path = '/' + path
</DeepExtract>
self.handlers[path] = handler
|
def publish(self, path, handler):
"""
Add a handler for a specific path.
:param path: Path to be handled.
:param handler: Content to return, either a bytestring or a function
that returns one.
"""
if path.startswith('/'):
path = path
path = '/' + path
self.handlers[path] = handler
|
agraph-python
|
positive
|
def expression(_p: int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
<DeepExtract>
localctx = BasisParser.ControlFlowContext(self, self._ctx, self.state)
self.enterRule(localctx, 44, self.RULE_controlFlow)
try:
self.enterOuterAlt(localctx, 1)
self.state = 361
self.match(BasisParser.Return)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
</DeepExtract>
self.state = 365
<DeepExtract>
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, 2)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
self.controlFlow()
self.state = 365
self.expression(2)
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
self.data()
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
self.level1()
self.state = 372
self.expression(6)
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
self.level2()
self.state = 376
self.expression(5)
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
self.level3()
self.state = 380
self.expression(4)
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
</DeepExtract>
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
<DeepExtract>
localctx = BasisParser.DataContext(self, self._ctx, self.state)
self.enterRule(localctx, 48, self.RULE_data)
try:
self.state = 390
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty]:
self.enterOuterAlt(localctx, 1)
self.state = 387
self.string()
pass
elif token in [BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer]:
self.enterOuterAlt(localctx, 2)
self.state = 388
self.number()
pass
elif token in [BasisParser.Identifier]:
self.enterOuterAlt(localctx, 3)
self.state = 389
self.symbol()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
</DeepExtract>
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
<DeepExtract>
localctx = BasisParser.Level1Context(self, self._ctx, self.state)
self.enterRule(localctx, 66, self.RULE_level1)
try:
self.enterOuterAlt(localctx, 1)
self.state = 423
self.match(BasisParser.Equal)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
</DeepExtract>
self.state = 372
<DeepExtract>
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, 6)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
self.controlFlow()
self.state = 365
self.expression(2)
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
self.data()
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
self.level1()
self.state = 372
self.expression(6)
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
self.level2()
self.state = 376
self.expression(5)
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
self.level3()
self.state = 380
self.expression(4)
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
</DeepExtract>
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
<DeepExtract>
localctx = BasisParser.Level2Context(self, self._ctx, self.state)
self.enterRule(localctx, 68, self.RULE_level2)
try:
self.enterOuterAlt(localctx, 1)
self.state = 425
self.match(BasisParser.Modulo)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
</DeepExtract>
self.state = 376
<DeepExtract>
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, 5)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
self.controlFlow()
self.state = 365
self.expression(2)
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
self.data()
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
self.level1()
self.state = 372
self.expression(6)
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
self.level2()
self.state = 376
self.expression(5)
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
self.level3()
self.state = 380
self.expression(4)
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
</DeepExtract>
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
<DeepExtract>
localctx = BasisParser.Level3Context(self, self._ctx, self.state)
self.enterRule(localctx, 70, self.RULE_level3)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 427
_la = self._input.LA(1)
if not (_la == BasisParser.Plus or _la == BasisParser.Minus):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
</DeepExtract>
self.state = 380
<DeepExtract>
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, 4)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
self.controlFlow()
self.state = 365
self.expression(2)
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
self.data()
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
self.level1()
self.state = 372
self.expression(6)
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
self.level2()
self.state = 376
self.expression(5)
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
self.level3()
self.state = 380
self.expression(4)
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
</DeepExtract>
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
|
def expression(_p: int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
localctx = BasisParser.ControlFlowContext(self, self._ctx, self.state)
self.enterRule(localctx, 44, self.RULE_controlFlow)
try:
self.enterOuterAlt(localctx, 1)
self.state = 361
self.match(BasisParser.Return)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
self.state = 365
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, 2)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
self.controlFlow()
self.state = 365
self.expression(2)
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
self.data()
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
self.level1()
self.state = 372
self.expression(6)
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
self.level2()
self.state = 376
self.expression(5)
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
self.level3()
self.state = 380
self.expression(4)
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
localctx = BasisParser.DataContext(self, self._ctx, self.state)
self.enterRule(localctx, 48, self.RULE_data)
try:
self.state = 390
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty]:
self.enterOuterAlt(localctx, 1)
self.state = 387
self.string()
pass
elif token in [BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer]:
self.enterOuterAlt(localctx, 2)
self.state = 388
self.number()
pass
elif token in [BasisParser.Identifier]:
self.enterOuterAlt(localctx, 3)
self.state = 389
self.symbol()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
localctx = BasisParser.Level1Context(self, self._ctx, self.state)
self.enterRule(localctx, 66, self.RULE_level1)
try:
self.enterOuterAlt(localctx, 1)
self.state = 423
self.match(BasisParser.Equal)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
self.state = 372
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, 6)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
self.controlFlow()
self.state = 365
self.expression(2)
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
self.data()
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
self.level1()
self.state = 372
self.expression(6)
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
self.level2()
self.state = 376
self.expression(5)
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
self.level3()
self.state = 380
self.expression(4)
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
localctx = BasisParser.Level2Context(self, self._ctx, self.state)
self.enterRule(localctx, 68, self.RULE_level2)
try:
self.enterOuterAlt(localctx, 1)
self.state = 425
self.match(BasisParser.Modulo)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
self.state = 376
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, 5)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
self.controlFlow()
self.state = 365
self.expression(2)
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
self.data()
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
self.level1()
self.state = 372
self.expression(6)
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
self.level2()
self.state = 376
self.expression(5)
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
self.level3()
self.state = 380
self.expression(4)
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
localctx = BasisParser.Level3Context(self, self._ctx, self.state)
self.enterRule(localctx, 70, self.RULE_level3)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 427
_la = self._input.LA(1)
if not (_la == BasisParser.Plus or _la == BasisParser.Minus):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
self.state = 380
_parentctx = self._ctx
_parentState = self.state
localctx = BasisParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 46
self.enterRecursionRule(localctx, 46, self.RULE_expression, 4)
try:
self.enterOuterAlt(localctx, 1)
self.state = 368
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [BasisParser.Return]:
self.state = 364
self.controlFlow()
self.state = 365
self.expression(2)
pass
elif token in [BasisParser.StringEscapeBlock, BasisParser.StringEscapeSingle, BasisParser.StringLiteralBlock, BasisParser.StringLiteralSingle, BasisParser.StringEmpty, BasisParser.Decimal, BasisParser.DecimalBad, BasisParser.Binary, BasisParser.Octal, BasisParser.Hexadecimal, BasisParser.Integer, BasisParser.Identifier]:
self.state = 367
self.data()
pass
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 384
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER:
if _alt == 1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 382
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input, 49, self._ctx)
if la_ == 1:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 370
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 5)')
self.state = 371
self.level1()
self.state = 372
self.expression(6)
pass
elif la_ == 2:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 374
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 4)')
self.state = 375
self.level2()
self.state = 376
self.expression(5)
pass
elif la_ == 3:
localctx = BasisParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 378
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, 'self.precpred(self._ctx, 3)')
self.state = 379
self.level3()
self.state = 380
self.expression(4)
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
pass
self.state = 386
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input, 50, self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
|
Basis
|
positive
|
def anchor_target(anchor_list, valid_flag_list, gt_bboxes_list, img_metas, target_means, target_stds, cfg, gt_bboxes_ignore_list=None, gt_labels_list=None, label_channels=1, sampling=True, unmap_outputs=True):
"""Compute regression and classification targets for anchors.
Args:
anchor_list (list[list]): Multi level anchors of each image.
valid_flag_list (list[list]): Multi level valid flags of each image.
gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image.
img_metas (list[dict]): Meta info of each image.
target_means (Iterable): Mean value of regression targets.
target_stds (Iterable): Std value of regression targets.
cfg (dict): RPN train configs.
Returns:
tuple
"""
num_imgs = len(img_metas)
assert len(anchor_list) == len(valid_flag_list) == num_imgs
num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]
for i in range(num_imgs):
assert len(anchor_list[i]) == len(valid_flag_list[i])
anchor_list[i] = torch.cat(anchor_list[i])
valid_flag_list[i] = torch.cat(valid_flag_list[i])
if gt_bboxes_ignore_list is None:
gt_bboxes_ignore_list = [None for _ in range(num_imgs)]
if gt_labels_list is None:
gt_labels_list = [None for _ in range(num_imgs)]
(all_labels, all_label_weights, all_bbox_targets, all_bbox_weights, pos_inds_list, neg_inds_list) = multi_apply(anchor_target_single, anchor_list, valid_flag_list, gt_bboxes_list, gt_bboxes_ignore_list, gt_labels_list, img_metas, target_means=target_means, target_stds=target_stds, cfg=cfg, label_channels=label_channels, sampling=sampling, unmap_outputs=unmap_outputs)
if any([labels is None for labels in all_labels]):
return None
num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list])
num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list])
<DeepExtract>
all_labels = torch.stack(all_labels, 0)
level_targets = []
start = 0
for n in num_level_anchors:
end = start + n
level_targets.append(all_labels[:, start:end].squeeze(0))
start = end
labels_list = level_targets
</DeepExtract>
<DeepExtract>
all_label_weights = torch.stack(all_label_weights, 0)
level_targets = []
start = 0
for n in num_level_anchors:
end = start + n
level_targets.append(all_label_weights[:, start:end].squeeze(0))
start = end
label_weights_list = level_targets
</DeepExtract>
<DeepExtract>
all_bbox_targets = torch.stack(all_bbox_targets, 0)
level_targets = []
start = 0
for n in num_level_anchors:
end = start + n
level_targets.append(all_bbox_targets[:, start:end].squeeze(0))
start = end
bbox_targets_list = level_targets
</DeepExtract>
<DeepExtract>
all_bbox_weights = torch.stack(all_bbox_weights, 0)
level_targets = []
start = 0
for n in num_level_anchors:
end = start + n
level_targets.append(all_bbox_weights[:, start:end].squeeze(0))
start = end
bbox_weights_list = level_targets
</DeepExtract>
return (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg)
|
def anchor_target(anchor_list, valid_flag_list, gt_bboxes_list, img_metas, target_means, target_stds, cfg, gt_bboxes_ignore_list=None, gt_labels_list=None, label_channels=1, sampling=True, unmap_outputs=True):
"""Compute regression and classification targets for anchors.
Args:
anchor_list (list[list]): Multi level anchors of each image.
valid_flag_list (list[list]): Multi level valid flags of each image.
gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image.
img_metas (list[dict]): Meta info of each image.
target_means (Iterable): Mean value of regression targets.
target_stds (Iterable): Std value of regression targets.
cfg (dict): RPN train configs.
Returns:
tuple
"""
num_imgs = len(img_metas)
assert len(anchor_list) == len(valid_flag_list) == num_imgs
num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]
for i in range(num_imgs):
assert len(anchor_list[i]) == len(valid_flag_list[i])
anchor_list[i] = torch.cat(anchor_list[i])
valid_flag_list[i] = torch.cat(valid_flag_list[i])
if gt_bboxes_ignore_list is None:
gt_bboxes_ignore_list = [None for _ in range(num_imgs)]
if gt_labels_list is None:
gt_labels_list = [None for _ in range(num_imgs)]
(all_labels, all_label_weights, all_bbox_targets, all_bbox_weights, pos_inds_list, neg_inds_list) = multi_apply(anchor_target_single, anchor_list, valid_flag_list, gt_bboxes_list, gt_bboxes_ignore_list, gt_labels_list, img_metas, target_means=target_means, target_stds=target_stds, cfg=cfg, label_channels=label_channels, sampling=sampling, unmap_outputs=unmap_outputs)
if any([labels is None for labels in all_labels]):
return None
num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list])
num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list])
all_labels = torch.stack(all_labels, 0)
level_targets = []
start = 0
for n in num_level_anchors:
end = start + n
level_targets.append(all_labels[:, start:end].squeeze(0))
start = end
labels_list = level_targets
all_label_weights = torch.stack(all_label_weights, 0)
level_targets = []
start = 0
for n in num_level_anchors:
end = start + n
level_targets.append(all_label_weights[:, start:end].squeeze(0))
start = end
label_weights_list = level_targets
all_bbox_targets = torch.stack(all_bbox_targets, 0)
level_targets = []
start = 0
for n in num_level_anchors:
end = start + n
level_targets.append(all_bbox_targets[:, start:end].squeeze(0))
start = end
bbox_targets_list = level_targets
all_bbox_weights = torch.stack(all_bbox_weights, 0)
level_targets = []
start = 0
for n in num_level_anchors:
end = start + n
level_targets.append(all_bbox_weights[:, start:end].squeeze(0))
start = end
bbox_weights_list = level_targets
return (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg)
|
C-HOI
|
positive
|
def start_flops_count(self):
"""
A method that will be available after add_flops_counting_methods() is
called on a desired net object.
Activates the computation of mean flops consumption per image.
Call it before you run the network.
"""
<DeepExtract>
if hasattr(self, '__batch_counter_handle__'):
return
handle = self.register_forward_hook(batch_counter_hook)
self.__batch_counter_handle__ = handle
</DeepExtract>
self.apply(add_flops_counter_hook_function)
|
def start_flops_count(self):
"""
A method that will be available after add_flops_counting_methods() is
called on a desired net object.
Activates the computation of mean flops consumption per image.
Call it before you run the network.
"""
if hasattr(self, '__batch_counter_handle__'):
return
handle = self.register_forward_hook(batch_counter_hook)
self.__batch_counter_handle__ = handle
self.apply(add_flops_counter_hook_function)
|
ATSS-EfficientDet-PyTorch
|
positive
|
def get_options_label(self):
<DeepExtract>
state_as_string = self.get_option_value('experiment_operator')
self.operator2 = self._operators_dict[state_as_string]
self._operator_label = state_as_string
</DeepExtract>
<DeepExtract>
state_as_string = self.get_option_value('experiment_mode')
self._selected_mode = state_as_string
</DeepExtract>
if self._selected_mode == 'simple':
return self._operator_label
else:
return self._selected_mode
|
def get_options_label(self):
state_as_string = self.get_option_value('experiment_operator')
self.operator2 = self._operators_dict[state_as_string]
self._operator_label = state_as_string
state_as_string = self.get_option_value('experiment_mode')
self._selected_mode = state_as_string
if self._selected_mode == 'simple':
return self._operator_label
else:
return self._selected_mode
|
drawing
|
positive
|
def format_currency(self, value, international=False):
"""Returns the provided value in the proper currency format.
Parameters:
value (dec): The decimal to represent as a currency.
international (bool): Whether this should follow
international formatting or not.
Returns:
str: The formatted currency value.
"""
self.international = international
value = Decimal(value)
<DeepExtract>
digits = self._determine_frac_digits()
decimal_str = abs(value).quantize(Decimal(10) ** (-digits), rounding=ROUND_HALF_UP)
try:
(num_whole, num_frac) = str(decimal_str).split('.')
except ValueError:
(num_whole, num_frac) = (str(decimal_str), '')
(num_whole, num_frac) = (num_whole, num_frac)
</DeepExtract>
<DeepExtract>
remaining = num_whole
groups = []
while remaining:
groups.append(remaining[-self.conventions['mon_grouping']:])
remaining = remaining[:-self.conventions['mon_grouping']]
groups.reverse()
grouped_num_whole = self.conventions['mon_thousands_sep'].join(groups)
grouped_num_whole = grouped_num_whole
</DeepExtract>
<DeepExtract>
frac_digits = self._determine_frac_digits()
if frac_digits > 0:
dec_separator = self.conventions['mon_decimal_point']
else:
dec_separator = ''
formatted_value = '{}{}{}'.format(grouped_num_whole, dec_separator, num_frac)
</DeepExtract>
<DeepExtract>
placeholder_value = '<{}>'.format(formatted_value)
symbol = self._determine_symbol_details(bool(value < 0))
if symbol['precedes']:
placeholder_value = '{}{}{}'.format(symbol['symbol'], symbol['separated'], placeholder_value)
else:
placeholder_value = '{}{}{}'.format(placeholder_value, symbol['separated'], symbol['symbol'])
if symbol['sign_position'] == 0:
placeholder_value = '({})'.format(placeholder_value)
elif symbol['sign_position'] == 1:
placeholder_value = '{}{}'.format(symbol['sign'], placeholder_value)
elif symbol['sign_position'] == 2:
placeholder_value = '{}{}'.format(placeholder_value, symbol['sign'])
elif symbol['sign_position'] == 3:
placeholder_value = placeholder_value.replace('<', symbol['sign'])
elif symbol['sign_position'] == 4:
placeholder_value = placeholder_value.replace('>', symbol['sign'])
else:
placeholder_value = '{}{}'.format(symbol['sign'], placeholder_value)
formatted_currency = placeholder_value.replace('<', '').replace('>', '')
formatted_currency = formatted_currency
</DeepExtract>
return formatted_currency
|
def format_currency(self, value, international=False):
"""Returns the provided value in the proper currency format.
Parameters:
value (dec): The decimal to represent as a currency.
international (bool): Whether this should follow
international formatting or not.
Returns:
str: The formatted currency value.
"""
self.international = international
value = Decimal(value)
digits = self._determine_frac_digits()
decimal_str = abs(value).quantize(Decimal(10) ** (-digits), rounding=ROUND_HALF_UP)
try:
(num_whole, num_frac) = str(decimal_str).split('.')
except ValueError:
(num_whole, num_frac) = (str(decimal_str), '')
(num_whole, num_frac) = (num_whole, num_frac)
remaining = num_whole
groups = []
while remaining:
groups.append(remaining[-self.conventions['mon_grouping']:])
remaining = remaining[:-self.conventions['mon_grouping']]
groups.reverse()
grouped_num_whole = self.conventions['mon_thousands_sep'].join(groups)
grouped_num_whole = grouped_num_whole
frac_digits = self._determine_frac_digits()
if frac_digits > 0:
dec_separator = self.conventions['mon_decimal_point']
else:
dec_separator = ''
formatted_value = '{}{}{}'.format(grouped_num_whole, dec_separator, num_frac)
placeholder_value = '<{}>'.format(formatted_value)
symbol = self._determine_symbol_details(bool(value < 0))
if symbol['precedes']:
placeholder_value = '{}{}{}'.format(symbol['symbol'], symbol['separated'], placeholder_value)
else:
placeholder_value = '{}{}{}'.format(placeholder_value, symbol['separated'], symbol['symbol'])
if symbol['sign_position'] == 0:
placeholder_value = '({})'.format(placeholder_value)
elif symbol['sign_position'] == 1:
placeholder_value = '{}{}'.format(symbol['sign'], placeholder_value)
elif symbol['sign_position'] == 2:
placeholder_value = '{}{}'.format(placeholder_value, symbol['sign'])
elif symbol['sign_position'] == 3:
placeholder_value = placeholder_value.replace('<', symbol['sign'])
elif symbol['sign_position'] == 4:
placeholder_value = placeholder_value.replace('>', symbol['sign'])
else:
placeholder_value = '{}{}'.format(symbol['sign'], placeholder_value)
formatted_currency = placeholder_value.replace('<', '').replace('>', '')
formatted_currency = formatted_currency
return formatted_currency
|
django-flexible-subscriptions
|
positive
|
def from_json(self, note):
"""Converts to STIX Bundle from JSON objects"""
attr = note['attributes']
self.name = attr['title']
self.text = attr['text']
self.published = attr['published']
<DeepExtract>
refs = []
for url in attr.get('validation_urls', []):
external_url = url['name']
source_name = external_url.split('/')[2].split('.')[-2]
refs.append({'source_name': source_name, 'url': external_url})
self.external_references = refs
</DeepExtract>
<DeepExtract>
ret = set()
for topic in attr.get('topic', []):
name = topic['name']
if name not in self.report_type_mapper:
self.helper.log_warning('Could not map a report type for type {}'.format(name))
continue
ret.add(self.report_type_mapper[name])
self.report_types = list(ret)
</DeepExtract>
self.labels = [topic['name'] for topic in attr.get('topic', [])]
for entity in attr.get('note_entities', []):
type_ = entity['type']
name = entity['name']
if self.person_to_ta and type_ == 'Person':
stix_objs = ThreatActor(name, type_, self.author).to_stix_objects()
elif entity['id'] in self.tas:
if self.ta_to_intrusion_set and type_ != 'Person':
stix_objs = IntrusionSet(name, type_, self.author).to_stix_objects()
else:
stix_objs = ThreatActor(name, type_, self.author).to_stix_objects()
elif type_ not in ENTITY_TYPE_MAPPER:
msg = f'Cannot convert entity {name} to STIX2 because it is of type {type_}'
self.helper.log_warning(msg)
continue
else:
stix_objs = ENTITY_TYPE_MAPPER[type_](name, type_, self.author).to_stix_objects()
self.objects.extend(stix_objs)
if 'attachment_content' in attr:
rule = DetectionRule(attr['attachment'], attr['attachment_type'], attr['attachment_content'])
self.objects.extend(rule.to_stix_objects())
|
def from_json(self, note):
"""Converts to STIX Bundle from JSON objects"""
attr = note['attributes']
self.name = attr['title']
self.text = attr['text']
self.published = attr['published']
refs = []
for url in attr.get('validation_urls', []):
external_url = url['name']
source_name = external_url.split('/')[2].split('.')[-2]
refs.append({'source_name': source_name, 'url': external_url})
self.external_references = refs
ret = set()
for topic in attr.get('topic', []):
name = topic['name']
if name not in self.report_type_mapper:
self.helper.log_warning('Could not map a report type for type {}'.format(name))
continue
ret.add(self.report_type_mapper[name])
self.report_types = list(ret)
self.labels = [topic['name'] for topic in attr.get('topic', [])]
for entity in attr.get('note_entities', []):
type_ = entity['type']
name = entity['name']
if self.person_to_ta and type_ == 'Person':
stix_objs = ThreatActor(name, type_, self.author).to_stix_objects()
elif entity['id'] in self.tas:
if self.ta_to_intrusion_set and type_ != 'Person':
stix_objs = IntrusionSet(name, type_, self.author).to_stix_objects()
else:
stix_objs = ThreatActor(name, type_, self.author).to_stix_objects()
elif type_ not in ENTITY_TYPE_MAPPER:
msg = f'Cannot convert entity {name} to STIX2 because it is of type {type_}'
self.helper.log_warning(msg)
continue
else:
stix_objs = ENTITY_TYPE_MAPPER[type_](name, type_, self.author).to_stix_objects()
self.objects.extend(stix_objs)
if 'attachment_content' in attr:
rule = DetectionRule(attr['attachment'], attr['attachment_type'], attr['attachment_content'])
self.objects.extend(rule.to_stix_objects())
|
connectors
|
positive
|
def test_incorrect_reaction(self):
"""Test response when incorrect reaction is passed"""
<DeepExtract>
_url = reverse('comment:react', kwargs={'pk': self.comment.id, 'reaction': 'likes'})
</DeepExtract>
response = self.client.post(_url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
<DeepExtract>
_url = reverse('comment:react', kwargs={'pk': self.comment.id, 'reaction': 1})
</DeepExtract>
response = self.client.post(_url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
def test_incorrect_reaction(self):
"""Test response when incorrect reaction is passed"""
_url = reverse('comment:react', kwargs={'pk': self.comment.id, 'reaction': 'likes'})
response = self.client.post(_url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
_url = reverse('comment:react', kwargs={'pk': self.comment.id, 'reaction': 1})
response = self.client.post(_url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
Comment
|
positive
|
def main(argv):
"""
The main function for smoke recognition (using the trained model)
"""
if len(argv) < 2:
print('Usage:')
print('python recognize_smoke.py check_and_fix_urls')
print('python recognize_smoke.py process_all_urls')
print('python recognize_smoke.py process_events')
print('python recognize_smoke.py init_data_upload')
print('python recognize_smoke.py upload_data')
print('python recognize_smoke.py scan_urls')
return
program_start_time = time.time()
nf = 36
if argv[1] == 'check_and_fix_urls':
<DeepExtract>
p = '../data/production_url_list/'
for fn in get_all_file_names_in_folder(p):
if '.json' not in fn:
continue
date_in_fn = re.findall('[\\d]{4}-[\\d]{2}-[\\d]{2}', fn)
if len(date_in_fn) != 1:
print("ERROR: file name is not a date, need to fix '%s' manually" % fn)
continue
date_in_fn = date_in_fn[0]
urls = load_json(p + fn)
has_problem = False
for i in range(len(urls)):
date_in_url = get_datetime_str_from_url(urls[i]['url'])
if date_in_fn != date_in_url:
print('PROBLEM: date mismatch (file name has %s but url has %s)' % (date_in_fn, date_in_url))
has_problem = True
print('Fix the date mismatch problem automatically...')
urls[i]['url'] = urls[i]['url'].replace(date_in_url, date_in_fn)
if has_problem:
print('Replace file with the fixed version: %s' % fn)
save_json(urls, p + fn)
</DeepExtract>
elif argv[1] == 'process_all_urls':
<DeepExtract>
learner = I3dLearner(mode='rgb', use_cuda=True, parallel=True)
if learner.use_cuda:
print('Enable GPU computing...')
if torch.cuda.device_count() == 1:
print('Only one GPU...disable parallel computing...')
True = False
else:
print('No GPU or do not want to use GPU...disable parallel computing...')
True = False
transform = learner.get_transform(learner.mode, image_size=learner.image_size)
p_dates = '../data/production/processed_dates.json'
if is_file_here(p_dates):
processed_dates = load_json(p_dates)
else:
processed_dates = []
p = '../data/production_url_list/'
for fn in get_all_file_names_in_folder(p):
if '.json' not in fn:
continue
date_tr = fn.split('.json')[0]
if date_tr in processed_dates:
print('Date %s is already processed...skip...' % date_tr)
continue
if test_mode and '2019-02-03' not in fn and ('2019-02-04' not in fn):
continue
m = load_json(p + fn)
c = 0
for m in load_json(p + fn):
c += 1
if test_mode and c > 2:
break
if 'url' not in m or 'cam_id' not in m or 'view_id' not in m:
continue
flag = process_url(learner, transform, m['url'], m['cam_id'], m['view_id'], nf, True, test_mode=test_mode)
if flag is True and fn not in processed_dates:
processed_dates.append(date_tr)
save_json(list(np.unique(processed_dates)), p_dates)
</DeepExtract>
elif argv[1] == 'process_events':
<DeepExtract>
p = '../data/production/'
p_out = '../data/event/'
check_and_create_dir(p_out)
if is_file_here(p_out + 'event_metadata.json'):
e_metadata = load_json(p_out + 'event_metadata.json')
else:
e_metadata = {}
processed_dates = [fn.split('.')[0] for fn in get_all_file_names_in_folder(p_out)]
for ds in get_all_dir_names_in_folder(p):
if ds in processed_dates:
print('Date %s was processed...skip...' % ds)
continue
print('Process date %s' % ds)
event_json = defaultdict(lambda : {'url': defaultdict(dict)})
t_to_f = {}
f_to_t = {}
e_metadata[ds] = {'cam_list': defaultdict(dict)}
df_events = defaultdict(list)
for vn in get_all_dir_names_in_folder(p + ds + '/'):
print('\tProcess view %s' % vn)
cam_id = int(vn.split('-')[0])
cam_name = cam_id_to_name(cam_id)
if cam_id not in t_to_f:
t_to_f[cam_id] = {}
f_to_t[cam_id] = {}
tm_json = request_json(get_tm_json_url(cam_name=cam_name, ds=ds))
ct = tm_json['capture-times']
for i in range(len(ct)):
t = int(str_to_time(ct[i]).timestamp())
t_to_f[cam_id][t] = i
f_to_t[cam_id][i] = t
for fn in get_all_file_names_in_folder(p + ds + '/' + vn + '/'):
if '.json' not in fn:
continue
print('\t\tProcess file %s' % fn)
s = fn.split('-')
b = {'L': int(s[5]), 'T': int(s[6]), 'R': int(s[7]), 'B': int(s[8])}
fp = p + ds + '/' + vn + '/' + fn
esdr_json = load_json(fp)
esdr_json = add_smoke_events(esdr_json)
df_event = pd.DataFrame(data=esdr_json['data'], columns=['epochtime'] + esdr_json['channel_names'])
df_event = df_event.sort_values(by=['epochtime']).reset_index(drop=True)
e_frame = get_event_frame_list(df_event, t_to_f[cam_id], nf, max_f=72, min_f=36)
event_urls = get_smoke_event_urls(e_frame, f_to_t[cam_id], cam_name, ds, b, vn)
(e_times, e_duration) = get_event_time_list(e_frame, f_to_t[cam_id])
df_events[cam_id].append(df_event)
event_json[cam_id]['url'][vn]['url'] = event_urls
event_json[cam_id]['url'][vn]['event'] = e_times
event_json[cam_id]['url'][vn]['total_event_duration_in_secs'] = e_duration
save_json(esdr_json, fp)
for cam_id in df_events:
df_aggr_event = df_events[cam_id][0]['event']
for df in df_events[cam_id][1:]:
df_aggr_event = df_aggr_event | df['event']
df_aggr_event = df_aggr_event.to_frame()
df_aggr_event['epochtime'] = df_events[cam_id][0]['epochtime']
e_frame = get_event_frame_list(df_aggr_event, t_to_f[cam_id], nf, max_f=72, min_f=36)
(e_times, e_duration) = get_event_time_list(e_frame, f_to_t[cam_id])
event_json[cam_id]['event'] = e_times
event_json[cam_id]['total_event_duration_in_secs'] = e_duration
e_metadata[ds]['cam_list'][cam_id]['total_event_duration_in_secs'] = e_duration
for cam_id in event_json:
event_json[cam_id]['url'] = OrderedDict(sort_by_camera_view(event_json[cam_id]['url'].items(), 0))
save_json(event_json, p_out + ds + '.json')
e_metadata = OrderedDict(sorted(e_metadata.items()))
save_json(e_metadata, p_out + 'event_metadata.json')
</DeepExtract>
elif argv[1] == 'init_data_upload':
<DeepExtract>
product_json = {'name': 'RISE_smoke_recognition_v3', 'prettyName': 'Recognizing Industrial Smoke Emissions', 'vendor': 'CMU CREATE Lab', 'description': 'Recognizing Industrial Smoke Emissions', 'defaultChannelSpecs': {'version': 1, 'channels': {'smoke_probability': {'prettyName': 'the probability of having smoke', 'units': 'probability', 'range': {'min': 0, 'max': 1}}, 'activation_ratio': {'prettyName': 'the ratio of activation region', 'units': 'ratio', 'range': {'min': 0, 'max': 1}}, 'event': {'prettyName': 'the smoke event', 'units': 'no/yes', 'range': {'min': 0, 'max': 1}}}}}
(access_token, _) = get_esdr_access_token(load_json('../data/auth.json'))
if access_token is not None:
register_esdr_product(product_json, access_token)
else:
print('ERROR! No access token.')
</DeepExtract>
elif argv[1] == 'upload_data':
<DeepExtract>
product_id = 97
(access_token, _) = get_esdr_access_token(load_json('../data/auth.json'))
if access_token is None:
print('ERROR! No access token.')
return
p = '../data/production/'
for ds in get_all_dir_names_in_folder(p):
for vn in get_all_dir_names_in_folder(p + ds + '/'):
for fn in get_all_file_names_in_folder(p + ds + '/' + vn + '/'):
if '.json' not in fn:
continue
data = load_json(p + ds + '/' + vn + '/' + fn)
if 'channel_names' not in data or 'data' not in data:
continue
s = vn.split('-')
(lat, lng) = get_cam_location_by_id(int(s[0]))
name = 'RISE_smoke_recognition_v3_camera_%s_view_%s' % (s[0], s[1])
upload_data_to_esdr(name, data, product_id, access_token, isPublic=1, latitude=lat, longitude=lng)
</DeepExtract>
elif argv[1] == 'scan_urls':
<DeepExtract>
p = '../data/event/'
event_metadata = load_json(p + 'event_metadata.json')
pool = Pool(num_workers)
for date_str in event_metadata:
event_json = load_json(p + date_str + '.json')
url_list = []
for cam_id in event_json:
for view_id in event_json[cam_id]['url']:
url_list += event_json[cam_id]['url'][view_id]['url']
pool.starmap(url_open_worker, url_list)
pool.close()
pool.join()
</DeepExtract>
else:
print("Wrong usage. Run 'python recognize_smoke.py' for details.")
program_run_time = (time.time() - program_start_time) / 60
print('Took %.2f minutes to run the program' % program_run_time)
print('END')
|
def main(argv):
"""
The main function for smoke recognition (using the trained model)
"""
if len(argv) < 2:
print('Usage:')
print('python recognize_smoke.py check_and_fix_urls')
print('python recognize_smoke.py process_all_urls')
print('python recognize_smoke.py process_events')
print('python recognize_smoke.py init_data_upload')
print('python recognize_smoke.py upload_data')
print('python recognize_smoke.py scan_urls')
return
program_start_time = time.time()
nf = 36
if argv[1] == 'check_and_fix_urls':
p = '../data/production_url_list/'
for fn in get_all_file_names_in_folder(p):
if '.json' not in fn:
continue
date_in_fn = re.findall('[\\d]{4}-[\\d]{2}-[\\d]{2}', fn)
if len(date_in_fn) != 1:
print("ERROR: file name is not a date, need to fix '%s' manually" % fn)
continue
date_in_fn = date_in_fn[0]
urls = load_json(p + fn)
has_problem = False
for i in range(len(urls)):
date_in_url = get_datetime_str_from_url(urls[i]['url'])
if date_in_fn != date_in_url:
print('PROBLEM: date mismatch (file name has %s but url has %s)' % (date_in_fn, date_in_url))
has_problem = True
print('Fix the date mismatch problem automatically...')
urls[i]['url'] = urls[i]['url'].replace(date_in_url, date_in_fn)
if has_problem:
print('Replace file with the fixed version: %s' % fn)
save_json(urls, p + fn)
elif argv[1] == 'process_all_urls':
learner = I3dLearner(mode='rgb', use_cuda=True, parallel=True)
if learner.use_cuda:
print('Enable GPU computing...')
if torch.cuda.device_count() == 1:
print('Only one GPU...disable parallel computing...')
True = False
else:
print('No GPU or do not want to use GPU...disable parallel computing...')
True = False
transform = learner.get_transform(learner.mode, image_size=learner.image_size)
p_dates = '../data/production/processed_dates.json'
if is_file_here(p_dates):
processed_dates = load_json(p_dates)
else:
processed_dates = []
p = '../data/production_url_list/'
for fn in get_all_file_names_in_folder(p):
if '.json' not in fn:
continue
date_tr = fn.split('.json')[0]
if date_tr in processed_dates:
print('Date %s is already processed...skip...' % date_tr)
continue
if test_mode and '2019-02-03' not in fn and ('2019-02-04' not in fn):
continue
m = load_json(p + fn)
c = 0
for m in load_json(p + fn):
c += 1
if test_mode and c > 2:
break
if 'url' not in m or 'cam_id' not in m or 'view_id' not in m:
continue
flag = process_url(learner, transform, m['url'], m['cam_id'], m['view_id'], nf, True, test_mode=test_mode)
if flag is True and fn not in processed_dates:
processed_dates.append(date_tr)
save_json(list(np.unique(processed_dates)), p_dates)
elif argv[1] == 'process_events':
p = '../data/production/'
p_out = '../data/event/'
check_and_create_dir(p_out)
if is_file_here(p_out + 'event_metadata.json'):
e_metadata = load_json(p_out + 'event_metadata.json')
else:
e_metadata = {}
processed_dates = [fn.split('.')[0] for fn in get_all_file_names_in_folder(p_out)]
for ds in get_all_dir_names_in_folder(p):
if ds in processed_dates:
print('Date %s was processed...skip...' % ds)
continue
print('Process date %s' % ds)
event_json = defaultdict(lambda : {'url': defaultdict(dict)})
t_to_f = {}
f_to_t = {}
e_metadata[ds] = {'cam_list': defaultdict(dict)}
df_events = defaultdict(list)
for vn in get_all_dir_names_in_folder(p + ds + '/'):
print('\tProcess view %s' % vn)
cam_id = int(vn.split('-')[0])
cam_name = cam_id_to_name(cam_id)
if cam_id not in t_to_f:
t_to_f[cam_id] = {}
f_to_t[cam_id] = {}
tm_json = request_json(get_tm_json_url(cam_name=cam_name, ds=ds))
ct = tm_json['capture-times']
for i in range(len(ct)):
t = int(str_to_time(ct[i]).timestamp())
t_to_f[cam_id][t] = i
f_to_t[cam_id][i] = t
for fn in get_all_file_names_in_folder(p + ds + '/' + vn + '/'):
if '.json' not in fn:
continue
print('\t\tProcess file %s' % fn)
s = fn.split('-')
b = {'L': int(s[5]), 'T': int(s[6]), 'R': int(s[7]), 'B': int(s[8])}
fp = p + ds + '/' + vn + '/' + fn
esdr_json = load_json(fp)
esdr_json = add_smoke_events(esdr_json)
df_event = pd.DataFrame(data=esdr_json['data'], columns=['epochtime'] + esdr_json['channel_names'])
df_event = df_event.sort_values(by=['epochtime']).reset_index(drop=True)
e_frame = get_event_frame_list(df_event, t_to_f[cam_id], nf, max_f=72, min_f=36)
event_urls = get_smoke_event_urls(e_frame, f_to_t[cam_id], cam_name, ds, b, vn)
(e_times, e_duration) = get_event_time_list(e_frame, f_to_t[cam_id])
df_events[cam_id].append(df_event)
event_json[cam_id]['url'][vn]['url'] = event_urls
event_json[cam_id]['url'][vn]['event'] = e_times
event_json[cam_id]['url'][vn]['total_event_duration_in_secs'] = e_duration
save_json(esdr_json, fp)
for cam_id in df_events:
df_aggr_event = df_events[cam_id][0]['event']
for df in df_events[cam_id][1:]:
df_aggr_event = df_aggr_event | df['event']
df_aggr_event = df_aggr_event.to_frame()
df_aggr_event['epochtime'] = df_events[cam_id][0]['epochtime']
e_frame = get_event_frame_list(df_aggr_event, t_to_f[cam_id], nf, max_f=72, min_f=36)
(e_times, e_duration) = get_event_time_list(e_frame, f_to_t[cam_id])
event_json[cam_id]['event'] = e_times
event_json[cam_id]['total_event_duration_in_secs'] = e_duration
e_metadata[ds]['cam_list'][cam_id]['total_event_duration_in_secs'] = e_duration
for cam_id in event_json:
event_json[cam_id]['url'] = OrderedDict(sort_by_camera_view(event_json[cam_id]['url'].items(), 0))
save_json(event_json, p_out + ds + '.json')
e_metadata = OrderedDict(sorted(e_metadata.items()))
save_json(e_metadata, p_out + 'event_metadata.json')
elif argv[1] == 'init_data_upload':
product_json = {'name': 'RISE_smoke_recognition_v3', 'prettyName': 'Recognizing Industrial Smoke Emissions', 'vendor': 'CMU CREATE Lab', 'description': 'Recognizing Industrial Smoke Emissions', 'defaultChannelSpecs': {'version': 1, 'channels': {'smoke_probability': {'prettyName': 'the probability of having smoke', 'units': 'probability', 'range': {'min': 0, 'max': 1}}, 'activation_ratio': {'prettyName': 'the ratio of activation region', 'units': 'ratio', 'range': {'min': 0, 'max': 1}}, 'event': {'prettyName': 'the smoke event', 'units': 'no/yes', 'range': {'min': 0, 'max': 1}}}}}
(access_token, _) = get_esdr_access_token(load_json('../data/auth.json'))
if access_token is not None:
register_esdr_product(product_json, access_token)
else:
print('ERROR! No access token.')
elif argv[1] == 'upload_data':
product_id = 97
(access_token, _) = get_esdr_access_token(load_json('../data/auth.json'))
if access_token is None:
print('ERROR! No access token.')
return
p = '../data/production/'
for ds in get_all_dir_names_in_folder(p):
for vn in get_all_dir_names_in_folder(p + ds + '/'):
for fn in get_all_file_names_in_folder(p + ds + '/' + vn + '/'):
if '.json' not in fn:
continue
data = load_json(p + ds + '/' + vn + '/' + fn)
if 'channel_names' not in data or 'data' not in data:
continue
s = vn.split('-')
(lat, lng) = get_cam_location_by_id(int(s[0]))
name = 'RISE_smoke_recognition_v3_camera_%s_view_%s' % (s[0], s[1])
upload_data_to_esdr(name, data, product_id, access_token, isPublic=1, latitude=lat, longitude=lng)
elif argv[1] == 'scan_urls':
p = '../data/event/'
event_metadata = load_json(p + 'event_metadata.json')
pool = Pool(num_workers)
for date_str in event_metadata:
event_json = load_json(p + date_str + '.json')
url_list = []
for cam_id in event_json:
for view_id in event_json[cam_id]['url']:
url_list += event_json[cam_id]['url'][view_id]['url']
pool.starmap(url_open_worker, url_list)
pool.close()
pool.join()
else:
print("Wrong usage. Run 'python recognize_smoke.py' for details.")
program_run_time = (time.time() - program_start_time) / 60
print('Took %.2f minutes to run the program' % program_run_time)
print('END')
|
deep-smoke-machine
|
positive
|
def _merge_attrs(self, dest: Union[OBT, List[OBT]], src: Union[OBT, List[OBT]], attr: str, merge_method: Optional[prof.Method]) -> None:
"""Merge this attr of src into the attr of dest."""
src_attr = getattr(src, attr, None)
if src_attr is None:
return
item_type = type(src).__name__
if attr in ITEM_EXCLUDE_MAP.get(item_type, []):
return
dest_attr = getattr(dest, attr, None)
if dest_attr and isinstance(dest_attr, list):
<DeepExtract>
added_items = []
if merge_method == prof.Method.keep:
dest_attr.extend(src_attr)
return
for item in src_attr:
if item not in dest_attr:
merged = False
item_id = self._get_id(item)
if item_id is not None:
for other in dest_attr:
other_id = self._get_id(other)
if other_id == item_id:
if merge_method == prof.Method.merge:
self._merge_items(other, item, merge_method)
merged = True
break
if not merged:
added_items.append(item)
dest_attr.extend(added_items)
</DeepExtract>
setattr(dest, attr, dest_attr)
return
if dest_attr and merge_method == prof.Method.use_first:
return
if dest_attr == src_attr and merge_method not in [None, prof.Method.keep]:
return
setattr(dest, attr, src_attr)
|
def _merge_attrs(self, dest: Union[OBT, List[OBT]], src: Union[OBT, List[OBT]], attr: str, merge_method: Optional[prof.Method]) -> None:
"""Merge this attr of src into the attr of dest."""
src_attr = getattr(src, attr, None)
if src_attr is None:
return
item_type = type(src).__name__
if attr in ITEM_EXCLUDE_MAP.get(item_type, []):
return
dest_attr = getattr(dest, attr, None)
if dest_attr and isinstance(dest_attr, list):
added_items = []
if merge_method == prof.Method.keep:
dest_attr.extend(src_attr)
return
for item in src_attr:
if item not in dest_attr:
merged = False
item_id = self._get_id(item)
if item_id is not None:
for other in dest_attr:
other_id = self._get_id(other)
if other_id == item_id:
if merge_method == prof.Method.merge:
self._merge_items(other, item, merge_method)
merged = True
break
if not merged:
added_items.append(item)
dest_attr.extend(added_items)
setattr(dest, attr, dest_attr)
return
if dest_attr and merge_method == prof.Method.use_first:
return
if dest_attr == src_attr and merge_method not in [None, prof.Method.keep]:
return
setattr(dest, attr, src_attr)
|
compliance-trestle
|
positive
|
@provide_session
def _run_raw_task(self, mark_success=False, test_mode=False, job_id=None, pool=None, session=None):
"""
Immediately runs the task (without checking or changing db state
before execution) and then sets the appropriate final state after
completion and runs any post-execute callbacks. Meant to be called
only after another function changes the state to running.
:param mark_success: Don't run the task, mark its state as success
:type mark_success: boolean
:param test_mode: Doesn't record success or failure in the DB
:type test_mode: boolean
:param pool: specifies the pool to use to run the task instance
:type pool: str
"""
task = self.task
self.pool = pool or task.pool
self.test_mode = test_mode
<DeepExtract>
TI = TaskInstance
qry = session.query(TI).filter(TI.dag_id == self.dag_id, TI.task_id == self.task_id, TI.execution_date == self.execution_date)
if lock_for_update:
ti = qry.with_for_update().first()
else:
ti = qry.first()
if ti:
self.state = ti.state
self.start_date = ti.start_date
self.end_date = ti.end_date
self.try_number = ti._try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.pid = ti.pid
self.executor_config = ti.executor_config
else:
self.state = None
</DeepExtract>
self.job_id = job_id
self.hostname = get_hostname()
self.operator = task.__class__.__name__
context = {}
try:
if not mark_success:
<DeepExtract>
task = self.task
from airflow import macros
tables = None
if 'tables' in task.params:
tables = task.params['tables']
ds = self.execution_date.strftime('%Y-%m-%d')
ts = self.execution_date.isoformat()
yesterday_ds = (self.execution_date - timedelta(1)).strftime('%Y-%m-%d')
tomorrow_ds = (self.execution_date + timedelta(1)).strftime('%Y-%m-%d')
prev_execution_date = task.dag.previous_schedule(self.execution_date)
next_execution_date = task.dag.following_schedule(self.execution_date)
next_ds = None
if next_execution_date:
next_ds = next_execution_date.strftime('%Y-%m-%d')
prev_ds = None
if prev_execution_date:
prev_ds = prev_execution_date.strftime('%Y-%m-%d')
ds_nodash = ds.replace('-', '')
ts_nodash = ts.replace('-', '').replace(':', '')
yesterday_ds_nodash = yesterday_ds.replace('-', '')
tomorrow_ds_nodash = tomorrow_ds.replace('-', '')
ti_key_str = '{task.dag_id}__{task.task_id}__{ds_nodash}'
ti_key_str = ti_key_str.format(**locals())
params = {}
run_id = ''
dag_run = None
if hasattr(task, 'dag'):
if task.dag.params:
params.update(task.dag.params)
dag_run = session.query(DagRun).filter_by(dag_id=task.dag.dag_id, execution_date=self.execution_date).first()
run_id = dag_run.run_id if dag_run else None
session.expunge_all()
session.commit()
if task.params:
params.update(task.params)
if configuration.getboolean('core', 'dag_run_conf_overrides_params'):
self.overwrite_params_with_dag_run_conf(params=params, dag_run=dag_run)
class VariableAccessor:
"""
Wrapper around Variable. This way you can get variables in templates by using
{var.value.your_variable_name}.
"""
def __init__(self):
self.var = None
def __getattr__(self, item):
self.var = Variable.get(item)
context = self.var
def __repr__(self):
context = str(self.var)
class VariableJsonAccessor:
"""
Wrapper around deserialized Variables. This way you can get variables
in templates by using {var.json.your_variable_name}.
"""
def __init__(self):
self.var = None
def __getattr__(self, item):
self.var = Variable.get(item, deserialize_json=True)
context = self.var
def __repr__(self):
context = str(self.var)
context = {'dag': task.dag, 'ds': ds, 'next_ds': next_ds, 'prev_ds': prev_ds, 'ds_nodash': ds_nodash, 'ts': ts, 'ts_nodash': ts_nodash, 'yesterday_ds': yesterday_ds, 'yesterday_ds_nodash': yesterday_ds_nodash, 'tomorrow_ds': tomorrow_ds, 'tomorrow_ds_nodash': tomorrow_ds_nodash, 'END_DATE': ds, 'end_date': ds, 'dag_run': dag_run, 'run_id': run_id, 'execution_date': self.execution_date, 'prev_execution_date': prev_execution_date, 'next_execution_date': next_execution_date, 'latest_date': ds, 'macros': macros, 'params': params, 'tables': tables, 'task': task, 'task_instance': self, 'ti': self, 'task_instance_key_str': ti_key_str, 'conf': configuration, 'test_mode': self.test_mode, 'var': {'value': VariableAccessor(), 'json': VariableJsonAccessor()}, 'inlets': task.inlets, 'outlets': task.outlets}
</DeepExtract>
task_copy = copy.copy(task)
self.task = task_copy
def signal_handler(signum, frame):
self.log.error('Received SIGTERM. Terminating subprocesses.')
task_copy.on_kill()
raise AirflowException('Task received SIGTERM signal')
signal.signal(signal.SIGTERM, signal_handler)
<DeepExtract>
session.query(XCom).filter(XCom.dag_id == self.dag_id, XCom.task_id == self.task_id, XCom.execution_date == self.execution_date).delete()
session.commit()
</DeepExtract>
<DeepExtract>
task = self.task
jinja_context = self.get_template_context()
if hasattr(self, 'task') and hasattr(self.task, 'dag'):
if self.task.dag.user_defined_macros:
jinja_context.update(self.task.dag.user_defined_macros)
rt = self.task.render_template
for attr in task.__class__.template_fields:
content = getattr(task, attr)
if content:
rendered_content = rt(attr, content, jinja_context)
setattr(task, attr, rendered_content)
</DeepExtract>
task_copy.pre_execute(context=context)
result = None
if task_copy.execution_timeout:
try:
with timeout(int(task_copy.execution_timeout.total_seconds())):
result = task_copy.execute(context=context)
except AirflowTaskTimeout:
task_copy.on_kill()
raise
else:
result = task_copy.execute(context=context)
if result is not None:
<DeepExtract>
if execution_date and execution_date < self.execution_date:
raise ValueError('execution_date can not be in the past (current execution_date is {}; received {})'.format(self.execution_date, execution_date))
XCom.set(key=XCOM_RETURN_KEY, value=result, task_id=self.task_id, dag_id=self.dag_id, execution_date=execution_date or self.execution_date)
</DeepExtract>
try:
task_copy.post_execute(context=context, result=result)
except TypeError as e:
if 'unexpected keyword argument' in str(e):
warnings.warn('BaseOperator.post_execute() now takes two arguments, `context` and `result`, but "{}" only expected one. This behavior is deprecated and will be removed in a future version of Airflow.'.format(self.task_id), category=DeprecationWarning)
task_copy.post_execute(context=context)
else:
raise
Stats.incr('operator_successes_{}'.format(self.task.__class__.__name__), 1, 1)
Stats.incr('ti_successes')
<DeepExtract>
TI = TaskInstance
qry = session.query(TI).filter(TI.dag_id == self.dag_id, TI.task_id == self.task_id, TI.execution_date == self.execution_date)
if True:
ti = qry.with_for_update().first()
else:
ti = qry.first()
if ti:
self.state = ti.state
self.start_date = ti.start_date
self.end_date = ti.end_date
self.try_number = ti._try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.pid = ti.pid
self.executor_config = ti.executor_config
else:
self.state = None
</DeepExtract>
self.state = State.SUCCESS
except AirflowSkipException:
<DeepExtract>
TI = TaskInstance
qry = session.query(TI).filter(TI.dag_id == self.dag_id, TI.task_id == self.task_id, TI.execution_date == self.execution_date)
if True:
ti = qry.with_for_update().first()
else:
ti = qry.first()
if ti:
self.state = ti.state
self.start_date = ti.start_date
self.end_date = ti.end_date
self.try_number = ti._try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.pid = ti.pid
self.executor_config = ti.executor_config
else:
self.state = None
</DeepExtract>
self.state = State.SKIPPED
except AirflowException as e:
<DeepExtract>
TI = TaskInstance
qry = session.query(TI).filter(TI.dag_id == self.dag_id, TI.task_id == self.task_id, TI.execution_date == self.execution_date)
if lock_for_update:
ti = qry.with_for_update().first()
else:
ti = qry.first()
if ti:
self.state = ti.state
self.start_date = ti.start_date
self.end_date = ti.end_date
self.try_number = ti._try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.pid = ti.pid
self.executor_config = ti.executor_config
else:
self.state = None
</DeepExtract>
if self.state == State.SUCCESS:
return
else:
<DeepExtract>
self.log.exception(e)
task = self.task
self.end_date = timezone.utcnow()
self.set_duration()
Stats.incr('operator_failures_{}'.format(task.__class__.__name__), 1, 1)
Stats.incr('ti_failures')
if not test_mode:
session.add(Log(State.FAILED, self))
session.add(TaskFail(task, self.execution_date, self.start_date, self.end_date))
try:
if self.is_eligible_to_retry():
self.state = State.UP_FOR_RETRY
self.log.info('Marking task as UP_FOR_RETRY')
if task.email_on_retry and task.email:
self.email_alert(e, is_retry=True)
else:
self.state = State.FAILED
if task.retries:
self.log.info('All retries failed; marking task as FAILED')
else:
self.log.info('Marking task as FAILED.')
if task.email_on_failure and task.email:
self.email_alert(e, is_retry=False)
except Exception as e2:
self.log.error('Failed to send email to: %s', task.email)
self.log.exception(e2)
try:
if self.state == State.UP_FOR_RETRY and task.on_retry_callback:
task.on_retry_callback(context)
if self.state == State.FAILED and task.on_failure_callback:
task.on_failure_callback(context)
except Exception as e3:
self.log.error('Failed at executing callback')
self.log.exception(e3)
if not test_mode:
session.merge(self)
session.commit()
</DeepExtract>
raise
except (Exception, KeyboardInterrupt) as e:
<DeepExtract>
self.log.exception(e)
task = self.task
self.end_date = timezone.utcnow()
self.set_duration()
Stats.incr('operator_failures_{}'.format(task.__class__.__name__), 1, 1)
Stats.incr('ti_failures')
if not test_mode:
session.add(Log(State.FAILED, self))
session.add(TaskFail(task, self.execution_date, self.start_date, self.end_date))
try:
if self.is_eligible_to_retry():
self.state = State.UP_FOR_RETRY
self.log.info('Marking task as UP_FOR_RETRY')
if task.email_on_retry and task.email:
self.email_alert(e, is_retry=True)
else:
self.state = State.FAILED
if task.retries:
self.log.info('All retries failed; marking task as FAILED')
else:
self.log.info('Marking task as FAILED.')
if task.email_on_failure and task.email:
self.email_alert(e, is_retry=False)
except Exception as e2:
self.log.error('Failed to send email to: %s', task.email)
self.log.exception(e2)
try:
if self.state == State.UP_FOR_RETRY and task.on_retry_callback:
task.on_retry_callback(context)
if self.state == State.FAILED and task.on_failure_callback:
task.on_failure_callback(context)
except Exception as e3:
self.log.error('Failed at executing callback')
self.log.exception(e3)
if not test_mode:
session.merge(self)
session.commit()
</DeepExtract>
raise
self.end_date = timezone.utcnow()
<DeepExtract>
if self.end_date and self.start_date:
self.duration = (self.end_date - self.start_date).total_seconds()
else:
self.duration = None
</DeepExtract>
if not test_mode:
session.add(Log(self.state, self))
session.merge(self)
session.commit()
try:
if task.on_success_callback:
task.on_success_callback(context)
except Exception as e3:
self.log.error('Failed when executing success callback')
self.log.exception(e3)
session.commit()
|
@provide_session
def _run_raw_task(self, mark_success=False, test_mode=False, job_id=None, pool=None, session=None):
"""
Immediately runs the task (without checking or changing db state
before execution) and then sets the appropriate final state after
completion and runs any post-execute callbacks. Meant to be called
only after another function changes the state to running.
:param mark_success: Don't run the task, mark its state as success
:type mark_success: boolean
:param test_mode: Doesn't record success or failure in the DB
:type test_mode: boolean
:param pool: specifies the pool to use to run the task instance
:type pool: str
"""
task = self.task
self.pool = pool or task.pool
self.test_mode = test_mode
TI = TaskInstance
qry = session.query(TI).filter(TI.dag_id == self.dag_id, TI.task_id == self.task_id, TI.execution_date == self.execution_date)
if lock_for_update:
ti = qry.with_for_update().first()
else:
ti = qry.first()
if ti:
self.state = ti.state
self.start_date = ti.start_date
self.end_date = ti.end_date
self.try_number = ti._try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.pid = ti.pid
self.executor_config = ti.executor_config
else:
self.state = None
self.job_id = job_id
self.hostname = get_hostname()
self.operator = task.__class__.__name__
context = {}
try:
if not mark_success:
task = self.task
from airflow import macros
tables = None
if 'tables' in task.params:
tables = task.params['tables']
ds = self.execution_date.strftime('%Y-%m-%d')
ts = self.execution_date.isoformat()
yesterday_ds = (self.execution_date - timedelta(1)).strftime('%Y-%m-%d')
tomorrow_ds = (self.execution_date + timedelta(1)).strftime('%Y-%m-%d')
prev_execution_date = task.dag.previous_schedule(self.execution_date)
next_execution_date = task.dag.following_schedule(self.execution_date)
next_ds = None
if next_execution_date:
next_ds = next_execution_date.strftime('%Y-%m-%d')
prev_ds = None
if prev_execution_date:
prev_ds = prev_execution_date.strftime('%Y-%m-%d')
ds_nodash = ds.replace('-', '')
ts_nodash = ts.replace('-', '').replace(':', '')
yesterday_ds_nodash = yesterday_ds.replace('-', '')
tomorrow_ds_nodash = tomorrow_ds.replace('-', '')
ti_key_str = '{task.dag_id}__{task.task_id}__{ds_nodash}'
ti_key_str = ti_key_str.format(**locals())
params = {}
run_id = ''
dag_run = None
if hasattr(task, 'dag'):
if task.dag.params:
params.update(task.dag.params)
dag_run = session.query(DagRun).filter_by(dag_id=task.dag.dag_id, execution_date=self.execution_date).first()
run_id = dag_run.run_id if dag_run else None
session.expunge_all()
session.commit()
if task.params:
params.update(task.params)
if configuration.getboolean('core', 'dag_run_conf_overrides_params'):
self.overwrite_params_with_dag_run_conf(params=params, dag_run=dag_run)
class VariableAccessor:
"""
Wrapper around Variable. This way you can get variables in templates by using
{var.value.your_variable_name}.
"""
def __init__(self):
self.var = None
def __getattr__(self, item):
self.var = Variable.get(item)
context = self.var
def __repr__(self):
context = str(self.var)
class VariableJsonAccessor:
"""
Wrapper around deserialized Variables. This way you can get variables
in templates by using {var.json.your_variable_name}.
"""
def __init__(self):
self.var = None
def __getattr__(self, item):
self.var = Variable.get(item, deserialize_json=True)
context = self.var
def __repr__(self):
context = str(self.var)
context = {'dag': task.dag, 'ds': ds, 'next_ds': next_ds, 'prev_ds': prev_ds, 'ds_nodash': ds_nodash, 'ts': ts, 'ts_nodash': ts_nodash, 'yesterday_ds': yesterday_ds, 'yesterday_ds_nodash': yesterday_ds_nodash, 'tomorrow_ds': tomorrow_ds, 'tomorrow_ds_nodash': tomorrow_ds_nodash, 'END_DATE': ds, 'end_date': ds, 'dag_run': dag_run, 'run_id': run_id, 'execution_date': self.execution_date, 'prev_execution_date': prev_execution_date, 'next_execution_date': next_execution_date, 'latest_date': ds, 'macros': macros, 'params': params, 'tables': tables, 'task': task, 'task_instance': self, 'ti': self, 'task_instance_key_str': ti_key_str, 'conf': configuration, 'test_mode': self.test_mode, 'var': {'value': VariableAccessor(), 'json': VariableJsonAccessor()}, 'inlets': task.inlets, 'outlets': task.outlets}
task_copy = copy.copy(task)
self.task = task_copy
def signal_handler(signum, frame):
self.log.error('Received SIGTERM. Terminating subprocesses.')
task_copy.on_kill()
raise AirflowException('Task received SIGTERM signal')
signal.signal(signal.SIGTERM, signal_handler)
session.query(XCom).filter(XCom.dag_id == self.dag_id, XCom.task_id == self.task_id, XCom.execution_date == self.execution_date).delete()
session.commit()
task = self.task
jinja_context = self.get_template_context()
if hasattr(self, 'task') and hasattr(self.task, 'dag'):
if self.task.dag.user_defined_macros:
jinja_context.update(self.task.dag.user_defined_macros)
rt = self.task.render_template
for attr in task.__class__.template_fields:
content = getattr(task, attr)
if content:
rendered_content = rt(attr, content, jinja_context)
setattr(task, attr, rendered_content)
task_copy.pre_execute(context=context)
result = None
if task_copy.execution_timeout:
try:
with timeout(int(task_copy.execution_timeout.total_seconds())):
result = task_copy.execute(context=context)
except AirflowTaskTimeout:
task_copy.on_kill()
raise
else:
result = task_copy.execute(context=context)
if result is not None:
if execution_date and execution_date < self.execution_date:
raise ValueError('execution_date can not be in the past (current execution_date is {}; received {})'.format(self.execution_date, execution_date))
XCom.set(key=XCOM_RETURN_KEY, value=result, task_id=self.task_id, dag_id=self.dag_id, execution_date=execution_date or self.execution_date)
try:
task_copy.post_execute(context=context, result=result)
except TypeError as e:
if 'unexpected keyword argument' in str(e):
warnings.warn('BaseOperator.post_execute() now takes two arguments, `context` and `result`, but "{}" only expected one. This behavior is deprecated and will be removed in a future version of Airflow.'.format(self.task_id), category=DeprecationWarning)
task_copy.post_execute(context=context)
else:
raise
Stats.incr('operator_successes_{}'.format(self.task.__class__.__name__), 1, 1)
Stats.incr('ti_successes')
TI = TaskInstance
qry = session.query(TI).filter(TI.dag_id == self.dag_id, TI.task_id == self.task_id, TI.execution_date == self.execution_date)
if True:
ti = qry.with_for_update().first()
else:
ti = qry.first()
if ti:
self.state = ti.state
self.start_date = ti.start_date
self.end_date = ti.end_date
self.try_number = ti._try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.pid = ti.pid
self.executor_config = ti.executor_config
else:
self.state = None
self.state = State.SUCCESS
except AirflowSkipException:
TI = TaskInstance
qry = session.query(TI).filter(TI.dag_id == self.dag_id, TI.task_id == self.task_id, TI.execution_date == self.execution_date)
if True:
ti = qry.with_for_update().first()
else:
ti = qry.first()
if ti:
self.state = ti.state
self.start_date = ti.start_date
self.end_date = ti.end_date
self.try_number = ti._try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.pid = ti.pid
self.executor_config = ti.executor_config
else:
self.state = None
self.state = State.SKIPPED
except AirflowException as e:
TI = TaskInstance
qry = session.query(TI).filter(TI.dag_id == self.dag_id, TI.task_id == self.task_id, TI.execution_date == self.execution_date)
if lock_for_update:
ti = qry.with_for_update().first()
else:
ti = qry.first()
if ti:
self.state = ti.state
self.start_date = ti.start_date
self.end_date = ti.end_date
self.try_number = ti._try_number
self.max_tries = ti.max_tries
self.hostname = ti.hostname
self.pid = ti.pid
self.executor_config = ti.executor_config
else:
self.state = None
if self.state == State.SUCCESS:
return
else:
self.log.exception(e)
task = self.task
self.end_date = timezone.utcnow()
self.set_duration()
Stats.incr('operator_failures_{}'.format(task.__class__.__name__), 1, 1)
Stats.incr('ti_failures')
if not test_mode:
session.add(Log(State.FAILED, self))
session.add(TaskFail(task, self.execution_date, self.start_date, self.end_date))
try:
if self.is_eligible_to_retry():
self.state = State.UP_FOR_RETRY
self.log.info('Marking task as UP_FOR_RETRY')
if task.email_on_retry and task.email:
self.email_alert(e, is_retry=True)
else:
self.state = State.FAILED
if task.retries:
self.log.info('All retries failed; marking task as FAILED')
else:
self.log.info('Marking task as FAILED.')
if task.email_on_failure and task.email:
self.email_alert(e, is_retry=False)
except Exception as e2:
self.log.error('Failed to send email to: %s', task.email)
self.log.exception(e2)
try:
if self.state == State.UP_FOR_RETRY and task.on_retry_callback:
task.on_retry_callback(context)
if self.state == State.FAILED and task.on_failure_callback:
task.on_failure_callback(context)
except Exception as e3:
self.log.error('Failed at executing callback')
self.log.exception(e3)
if not test_mode:
session.merge(self)
session.commit()
raise
except (Exception, KeyboardInterrupt) as e:
self.log.exception(e)
task = self.task
self.end_date = timezone.utcnow()
self.set_duration()
Stats.incr('operator_failures_{}'.format(task.__class__.__name__), 1, 1)
Stats.incr('ti_failures')
if not test_mode:
session.add(Log(State.FAILED, self))
session.add(TaskFail(task, self.execution_date, self.start_date, self.end_date))
try:
if self.is_eligible_to_retry():
self.state = State.UP_FOR_RETRY
self.log.info('Marking task as UP_FOR_RETRY')
if task.email_on_retry and task.email:
self.email_alert(e, is_retry=True)
else:
self.state = State.FAILED
if task.retries:
self.log.info('All retries failed; marking task as FAILED')
else:
self.log.info('Marking task as FAILED.')
if task.email_on_failure and task.email:
self.email_alert(e, is_retry=False)
except Exception as e2:
self.log.error('Failed to send email to: %s', task.email)
self.log.exception(e2)
try:
if self.state == State.UP_FOR_RETRY and task.on_retry_callback:
task.on_retry_callback(context)
if self.state == State.FAILED and task.on_failure_callback:
task.on_failure_callback(context)
except Exception as e3:
self.log.error('Failed at executing callback')
self.log.exception(e3)
if not test_mode:
session.merge(self)
session.commit()
raise
self.end_date = timezone.utcnow()
if self.end_date and self.start_date:
self.duration = (self.end_date - self.start_date).total_seconds()
else:
self.duration = None
if not test_mode:
session.add(Log(self.state, self))
session.merge(self)
session.commit()
try:
if task.on_success_callback:
task.on_success_callback(context)
except Exception as e3:
self.log.error('Failed when executing success callback')
self.log.exception(e3)
session.commit()
|
docker-airflow
|
positive
|
def add(self, m):
proto = ctypes.WINFUNCTYPE(m.restype, *m.argtypes)
vidx = self._member_index + self._vtbl_offset
iid = self._iid if m.restype == ctypes.HRESULT else None
raw_func = proto(vidx, m.name, None, iid)
<DeepExtract>
if m.paramflags:
dirflags = [p[0] & 3 for p in m.paramflags]
if 3 in dirflags:
proto(vidx, m.name, m.paramflags, iid) = _fix_inout_args(proto(vidx, m.name, m.paramflags, iid), m.argtypes, m.paramflags)
proto(vidx, m.name, m.paramflags, iid) = proto(vidx, m.name, m.paramflags, iid)
</DeepExtract>
func.__doc__ = m.doc
func.__name__ = m.name
is_prop = m.is_prop()
if is_prop:
self._props.add(m, func)
self._mths.append((m.name, func, raw_func, is_prop))
self._member_index += 1
|
def add(self, m):
proto = ctypes.WINFUNCTYPE(m.restype, *m.argtypes)
vidx = self._member_index + self._vtbl_offset
iid = self._iid if m.restype == ctypes.HRESULT else None
raw_func = proto(vidx, m.name, None, iid)
if m.paramflags:
dirflags = [p[0] & 3 for p in m.paramflags]
if 3 in dirflags:
proto(vidx, m.name, m.paramflags, iid) = _fix_inout_args(proto(vidx, m.name, m.paramflags, iid), m.argtypes, m.paramflags)
proto(vidx, m.name, m.paramflags, iid) = proto(vidx, m.name, m.paramflags, iid)
func.__doc__ = m.doc
func.__name__ = m.name
is_prop = m.is_prop()
if is_prop:
self._props.add(m, func)
self._mths.append((m.name, func, raw_func, is_prop))
self._member_index += 1
|
comtypes
|
positive
|
def five_digit_codes(codes: Codes) -> Tuple[Codes, FiveDigitCodes]:
"""Returns a 5-digit min/max temperature code"""
values = FiveDigitCodes()
for (i, code) in reversed(list(enumerate(codes))):
if len(code) == 5 and code.isdigit():
key = int(code[0])
if key == 1:
<DeepExtract>
if not code[1:]:
values.maximum_temperature_6 = None
number = f"{('-' if code[1:][0] == '1' else '')}{int(code[1:][1:3])}.{code[1:][3]}"
values.maximum_temperature_6 = core.make_number(number, code or code[1:])
</DeepExtract>
elif key == 2:
<DeepExtract>
if not code[1:]:
values.minimum_temperature_6 = None
number = f"{('-' if code[1:][0] == '1' else '')}{int(code[1:][1:3])}.{code[1:][3]}"
values.minimum_temperature_6 = core.make_number(number, code or code[1:])
</DeepExtract>
elif key == 5:
<DeepExtract>
values.pressure_tendency = PressureTendency(repr=code, tendency=PRESSURE_TENDENCIES[code[1]], change=float(f'{code[2:4]}.{code[4]}'))
</DeepExtract>
elif key == 6:
<DeepExtract>
values.precip_36_hours = core.make_number(f'{code[1:3]}.{code[3:]}', code)
</DeepExtract>
elif key == 7:
<DeepExtract>
values.precip_24_hours = core.make_number(f'{code[1:3]}.{code[3:]}', code)
</DeepExtract>
elif key == 9:
values.sunshine_minutes = core.make_number(code[2:], code)
else:
continue
codes.pop(i)
return (codes, values)
|
def five_digit_codes(codes: Codes) -> Tuple[Codes, FiveDigitCodes]:
"""Returns a 5-digit min/max temperature code"""
values = FiveDigitCodes()
for (i, code) in reversed(list(enumerate(codes))):
if len(code) == 5 and code.isdigit():
key = int(code[0])
if key == 1:
if not code[1:]:
values.maximum_temperature_6 = None
number = f"{('-' if code[1:][0] == '1' else '')}{int(code[1:][1:3])}.{code[1:][3]}"
values.maximum_temperature_6 = core.make_number(number, code or code[1:])
elif key == 2:
if not code[1:]:
values.minimum_temperature_6 = None
number = f"{('-' if code[1:][0] == '1' else '')}{int(code[1:][1:3])}.{code[1:][3]}"
values.minimum_temperature_6 = core.make_number(number, code or code[1:])
elif key == 5:
values.pressure_tendency = PressureTendency(repr=code, tendency=PRESSURE_TENDENCIES[code[1]], change=float(f'{code[2:4]}.{code[4]}'))
elif key == 6:
values.precip_36_hours = core.make_number(f'{code[1:3]}.{code[3:]}', code)
elif key == 7:
values.precip_24_hours = core.make_number(f'{code[1:3]}.{code[3:]}', code)
elif key == 9:
values.sunshine_minutes = core.make_number(code[2:], code)
else:
continue
codes.pop(i)
return (codes, values)
|
avwx-engine
|
positive
|
def train(self, mode=True):
super(ResNet, self).train(mode)
<DeepExtract>
if self.frozen_stages >= 0:
self.norm1.eval()
for m in [self.conv1, self.norm1]:
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, 'layer{}'.format(i))
m.eval()
for param in m.parameters():
param.requires_grad = False
</DeepExtract>
if mode and self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval()
|
def train(self, mode=True):
super(ResNet, self).train(mode)
if self.frozen_stages >= 0:
self.norm1.eval()
for m in [self.conv1, self.norm1]:
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, 'layer{}'.format(i))
m.eval()
for param in m.parameters():
param.requires_grad = False
if mode and self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval()
|
DNL-Object-Detection
|
positive
|
def modify_forward(model):
for child in model.children():
if should_measure(child):
def new_forward(m):
def lambda_forward(*args):
<DeepExtract>
global count_ops, count_params
for x in args:
delta_ops = 0
delta_params = 0
multi_add = 1
type_name = get_layer_info(m)
if type_name in ['Conv2d']:
out_h = int((x.size()[2] + 2 * m.padding[0] / m.dilation[0] - m.kernel_size[0]) / m.stride[0] + 1)
out_w = int((x.size()[3] + 2 * m.padding[1] / m.dilation[1] - m.kernel_size[1]) / m.stride[1] + 1)
delta_ops = m.in_channels * m.out_channels * m.kernel_size[0] * m.kernel_size[1] * out_h * out_w / m.groups * multi_add
delta_params = get_layer_param(m)
elif type_name in ['ConvTranspose2d']:
(_, _, in_h, in_w) = x.size()
out_h = int((in_h - 1) * m.stride[0] - 2 * m.padding[0] + m.kernel_size[0] + m.output_padding[0])
out_w = int((in_w - 1) * m.stride[1] - 2 * m.padding[1] + m.kernel_size[1] + m.output_padding[1])
delta_ops = m.in_channels * m.out_channels * m.kernel_size[0] * m.kernel_size[1] * out_h * out_w / m.groups * multi_add
delta_params = get_layer_param(m)
elif type_name in ['LearnedGroupConv']:
measure_layer(m.relu, x)
measure_layer(m.norm, x)
conv = m.conv
out_h = int((x.size()[2] + 2 * conv.padding[0] - conv.kernel_size[0]) / conv.stride[0] + 1)
out_w = int((x.size()[3] + 2 * conv.padding[1] - conv.kernel_size[1]) / conv.stride[1] + 1)
delta_ops = conv.in_channels * conv.out_channels * conv.kernel_size[0] * conv.kernel_size[1] * out_h * out_w / m.condense_factor * multi_add
delta_params = get_layer_param(conv) / m.condense_factor
elif type_name in ['ReLU', 'ReLU6']:
delta_ops = x.numel()
delta_params = get_layer_param(m)
elif type_name in ['AvgPool2d', 'MaxPool2d']:
in_w = x.size()[2]
kernel_ops = m.kernel_size * m.kernel_size
out_w = int((in_w + 2 * m.padding - m.kernel_size) / m.stride + 1)
out_h = int((in_w + 2 * m.padding - m.kernel_size) / m.stride + 1)
delta_ops = x.size()[0] * x.size()[1] * out_w * out_h * kernel_ops
delta_params = get_layer_param(m)
elif type_name in ['LastLevelMaxPool']:
pass
elif type_name in ['AdaptiveAvgPool2d']:
delta_ops = x.size()[0] * x.size()[1] * x.size()[2] * x.size()[3]
delta_params = get_layer_param(m)
elif type_name in ['ZeroPad2d', 'RetinaNetPostProcessor']:
pass
elif type_name in ['Linear']:
weight_ops = m.weight.numel() * multi_add
bias_ops = m.bias.numel()
delta_ops = x.size()[0] * (weight_ops + bias_ops)
delta_params = get_layer_param(m)
elif type_name in ['BatchNorm2d', 'Dropout2d', 'DropChannel', 'Dropout', 'FrozenBatchNorm2d', 'GroupNorm']:
delta_params = get_layer_param(m)
elif type_name in ['SumTwo']:
delta_ops = x.numel()
elif type_name in ['AggregateCell']:
if not m.pre_transform:
delta_ops = 2 * x.numel()
else:
measure_layer(m.branch_1, x)
measure_layer(m.branch_2, x)
delta_params = get_layer_param(m)
elif type_name in ['Identity', 'Zero']:
pass
elif type_name in ['Scale']:
delta_params = get_layer_param(m)
delta_ops = x.numel()
elif type_name in ['FCOSPostProcessor', 'RPNPostProcessor', 'KeypointPostProcessor', 'ROIAlign', 'PostProcessor', 'KeypointRCNNPredictor']:
pass
elif type_name in ['DeformConv']:
offset_conv = list(m.parameters())[0]
delta_ops = reduce(operator.mul, offset_conv.size(), x.size()[2] * x.size()[3])
out_h = int((x.size()[2] + 2 * m.padding[0] / m.dilation[0] - m.kernel_size[0]) / m.stride[0] + 1)
out_w = int((x.size()[3] + 2 * m.padding[1] / m.dilation[1] - m.kernel_size[1]) / m.stride[1] + 1)
delta_ops += m.in_channels * m.out_channels * m.kernel_size[0] * m.kernel_size[1] * out_h * out_w / m.groups * multi_add
delta_params = get_layer_param(m)
else:
raise TypeError('unknown layer type: %s' % type_name)
count_ops += delta_ops
count_params += delta_params
return
</DeepExtract>
return m.old_forward(*args)
return lambda_forward
child.old_forward = child.forward
<DeepExtract>
def lambda_forward(*args):
measure_layer(child, *args)
child.forward = child.old_forward(*args)
child.forward = lambda_forward
</DeepExtract>
else:
<DeepExtract>
for child in child.children():
if should_measure(child):
def new_forward(m):
def lambda_forward(*args):
measure_layer(m, *args)
return m.old_forward(*args)
return lambda_forward
child.old_forward = child.forward
child.forward = new_forward(child)
else:
modify_forward(child)
</DeepExtract>
|
def modify_forward(model):
for child in model.children():
if should_measure(child):
def new_forward(m):
def lambda_forward(*args):
global count_ops, count_params
for x in args:
delta_ops = 0
delta_params = 0
multi_add = 1
type_name = get_layer_info(m)
if type_name in ['Conv2d']:
out_h = int((x.size()[2] + 2 * m.padding[0] / m.dilation[0] - m.kernel_size[0]) / m.stride[0] + 1)
out_w = int((x.size()[3] + 2 * m.padding[1] / m.dilation[1] - m.kernel_size[1]) / m.stride[1] + 1)
delta_ops = m.in_channels * m.out_channels * m.kernel_size[0] * m.kernel_size[1] * out_h * out_w / m.groups * multi_add
delta_params = get_layer_param(m)
elif type_name in ['ConvTranspose2d']:
(_, _, in_h, in_w) = x.size()
out_h = int((in_h - 1) * m.stride[0] - 2 * m.padding[0] + m.kernel_size[0] + m.output_padding[0])
out_w = int((in_w - 1) * m.stride[1] - 2 * m.padding[1] + m.kernel_size[1] + m.output_padding[1])
delta_ops = m.in_channels * m.out_channels * m.kernel_size[0] * m.kernel_size[1] * out_h * out_w / m.groups * multi_add
delta_params = get_layer_param(m)
elif type_name in ['LearnedGroupConv']:
measure_layer(m.relu, x)
measure_layer(m.norm, x)
conv = m.conv
out_h = int((x.size()[2] + 2 * conv.padding[0] - conv.kernel_size[0]) / conv.stride[0] + 1)
out_w = int((x.size()[3] + 2 * conv.padding[1] - conv.kernel_size[1]) / conv.stride[1] + 1)
delta_ops = conv.in_channels * conv.out_channels * conv.kernel_size[0] * conv.kernel_size[1] * out_h * out_w / m.condense_factor * multi_add
delta_params = get_layer_param(conv) / m.condense_factor
elif type_name in ['ReLU', 'ReLU6']:
delta_ops = x.numel()
delta_params = get_layer_param(m)
elif type_name in ['AvgPool2d', 'MaxPool2d']:
in_w = x.size()[2]
kernel_ops = m.kernel_size * m.kernel_size
out_w = int((in_w + 2 * m.padding - m.kernel_size) / m.stride + 1)
out_h = int((in_w + 2 * m.padding - m.kernel_size) / m.stride + 1)
delta_ops = x.size()[0] * x.size()[1] * out_w * out_h * kernel_ops
delta_params = get_layer_param(m)
elif type_name in ['LastLevelMaxPool']:
pass
elif type_name in ['AdaptiveAvgPool2d']:
delta_ops = x.size()[0] * x.size()[1] * x.size()[2] * x.size()[3]
delta_params = get_layer_param(m)
elif type_name in ['ZeroPad2d', 'RetinaNetPostProcessor']:
pass
elif type_name in ['Linear']:
weight_ops = m.weight.numel() * multi_add
bias_ops = m.bias.numel()
delta_ops = x.size()[0] * (weight_ops + bias_ops)
delta_params = get_layer_param(m)
elif type_name in ['BatchNorm2d', 'Dropout2d', 'DropChannel', 'Dropout', 'FrozenBatchNorm2d', 'GroupNorm']:
delta_params = get_layer_param(m)
elif type_name in ['SumTwo']:
delta_ops = x.numel()
elif type_name in ['AggregateCell']:
if not m.pre_transform:
delta_ops = 2 * x.numel()
else:
measure_layer(m.branch_1, x)
measure_layer(m.branch_2, x)
delta_params = get_layer_param(m)
elif type_name in ['Identity', 'Zero']:
pass
elif type_name in ['Scale']:
delta_params = get_layer_param(m)
delta_ops = x.numel()
elif type_name in ['FCOSPostProcessor', 'RPNPostProcessor', 'KeypointPostProcessor', 'ROIAlign', 'PostProcessor', 'KeypointRCNNPredictor']:
pass
elif type_name in ['DeformConv']:
offset_conv = list(m.parameters())[0]
delta_ops = reduce(operator.mul, offset_conv.size(), x.size()[2] * x.size()[3])
out_h = int((x.size()[2] + 2 * m.padding[0] / m.dilation[0] - m.kernel_size[0]) / m.stride[0] + 1)
out_w = int((x.size()[3] + 2 * m.padding[1] / m.dilation[1] - m.kernel_size[1]) / m.stride[1] + 1)
delta_ops += m.in_channels * m.out_channels * m.kernel_size[0] * m.kernel_size[1] * out_h * out_w / m.groups * multi_add
delta_params = get_layer_param(m)
else:
raise TypeError('unknown layer type: %s' % type_name)
count_ops += delta_ops
count_params += delta_params
return
return m.old_forward(*args)
return lambda_forward
child.old_forward = child.forward
def lambda_forward(*args):
measure_layer(child, *args)
child.forward = child.old_forward(*args)
child.forward = lambda_forward
else:
for child in child.children():
if should_measure(child):
def new_forward(m):
def lambda_forward(*args):
measure_layer(m, *args)
return m.old_forward(*args)
return lambda_forward
child.old_forward = child.forward
child.forward = new_forward(child)
else:
modify_forward(child)
</DeepExtract>
|
bezier_curve_text_spotting
|
positive
|
def add_event_handler(self, full_usage_id, handler_function, event_kind=HID_EVT_ALL, aux_data=None):
"""Add event handler for usage value/button changes,
returns True if the handler function was updated"""
<DeepExtract>
for (report_id, report_obj) in self.__input_report_templates.items():
if full_usage_id in report_obj:
report_id = report_id
report_id = None
</DeepExtract>
if report_id != None:
self.__input_report_templates[report_id][full_usage_id].__value = None
if report_id == None or not handler_function:
return False
assert isinstance(handler_function, collections.Callable)
top_map_handler = self.__evt_handlers.get(full_usage_id, dict())
event_handler_set = top_map_handler.get(event_kind, dict())
event_handler_set[handler_function] = aux_data
if event_kind not in top_map_handler:
top_map_handler[event_kind] = event_handler_set
if full_usage_id not in self.__evt_handlers:
self.__evt_handlers[full_usage_id] = top_map_handler
return True
|
def add_event_handler(self, full_usage_id, handler_function, event_kind=HID_EVT_ALL, aux_data=None):
"""Add event handler for usage value/button changes,
returns True if the handler function was updated"""
for (report_id, report_obj) in self.__input_report_templates.items():
if full_usage_id in report_obj:
report_id = report_id
report_id = None
if report_id != None:
self.__input_report_templates[report_id][full_usage_id].__value = None
if report_id == None or not handler_function:
return False
assert isinstance(handler_function, collections.Callable)
top_map_handler = self.__evt_handlers.get(full_usage_id, dict())
event_handler_set = top_map_handler.get(event_kind, dict())
event_handler_set[handler_function] = aux_data
if event_kind not in top_map_handler:
top_map_handler[event_kind] = event_handler_set
if full_usage_id not in self.__evt_handlers:
self.__evt_handlers[full_usage_id] = top_map_handler
return True
|
CyKit
|
positive
|
def get_aggregate_expression(other_columns, column_type, column_names, aggregate_function):
"""Return an expression that is used to find the maximum or minimum value across
a number of other given columns.
We cannot use Table Value Constructors as in the TPP backend (this gives a
cryptic error message: "Given correlated subquery is not supported").
Instead, we use GREATEST() or LEAST(), but we have to be careful to handle
correctly any arguments to GREATEST/LEAST that have replaced NULLs. To do this,
we replace any occurences of the default value for the given column_type with
the most extreme value possible for the column_type. (So when finding the
maximum, we replace the default value with a small value, and when finding the
minimum, with a large value.)
If all the arguments to GREATEST/LEAST have replaced NULLs, GREATEST/LEAST will
return the extreme value, so when that happens, we have to replace this with the
default value for the column type.
This gives us the result we want but it does mean we can't distinguish e.g. a
recorded value of 0.0 from a missing value. This, however, is a general problem
with the way we handle NULLs in our system, and so we're not introducing any new
difficulty here. (It's also unlikely to be a problem in practice.)
"""
<DeepExtract>
if column_type == 'date':
default_value = ''
elif column_type == 'str':
default_value = ''
elif column_type == 'bool':
default_value = 0
elif column_type == 'int':
default_value = 0
elif column_type == 'float':
default_value = 0.0
else:
raise ValueError(f'Unhandled column type: {column_type}')
</DeepExtract>
function = {'MAX': 'GREATEST', 'MIN': 'LEAST'}[aggregate_function]
if column_type in ['int', 'float']:
extreme_value_lookup = {'MAX': -2 ** 63, 'MIN': 2 ** (63 - 1)}
extreme_value = [aggregate_function]
elif column_type == 'date':
extreme_value_lookup = {'MAX': "'0001-01-01'", 'MIN': "'9999-12-31'"}
else:
assert False, column_type
extreme_value = extreme_value_lookup[aggregate_function]
components = ', '.join((f'\n CASE WHEN {other_columns[name]} = {quote(default_value)}\n THEN {extreme_value}\n ELSE {other_columns[name]} END' for name in column_names))
tables_used = set()
for name in column_names:
tables_used.update(other_columns[name].source_tables)
return ColumnExpression(f'\n CASE WHEN {function}({components}) = {extreme_value}\n THEN {quote(default_value)}\n ELSE {function}({components}) END', type=column_type, default_value=default_value, source_tables=list(tables_used), date_format=other_columns[column_names[0]].date_format)
|
def get_aggregate_expression(other_columns, column_type, column_names, aggregate_function):
"""Return an expression that is used to find the maximum or minimum value across
a number of other given columns.
We cannot use Table Value Constructors as in the TPP backend (this gives a
cryptic error message: "Given correlated subquery is not supported").
Instead, we use GREATEST() or LEAST(), but we have to be careful to handle
correctly any arguments to GREATEST/LEAST that have replaced NULLs. To do this,
we replace any occurences of the default value for the given column_type with
the most extreme value possible for the column_type. (So when finding the
maximum, we replace the default value with a small value, and when finding the
minimum, with a large value.)
If all the arguments to GREATEST/LEAST have replaced NULLs, GREATEST/LEAST will
return the extreme value, so when that happens, we have to replace this with the
default value for the column type.
This gives us the result we want but it does mean we can't distinguish e.g. a
recorded value of 0.0 from a missing value. This, however, is a general problem
with the way we handle NULLs in our system, and so we're not introducing any new
difficulty here. (It's also unlikely to be a problem in practice.)
"""
if column_type == 'date':
default_value = ''
elif column_type == 'str':
default_value = ''
elif column_type == 'bool':
default_value = 0
elif column_type == 'int':
default_value = 0
elif column_type == 'float':
default_value = 0.0
else:
raise ValueError(f'Unhandled column type: {column_type}')
function = {'MAX': 'GREATEST', 'MIN': 'LEAST'}[aggregate_function]
if column_type in ['int', 'float']:
extreme_value_lookup = {'MAX': -2 ** 63, 'MIN': 2 ** (63 - 1)}
extreme_value = [aggregate_function]
elif column_type == 'date':
extreme_value_lookup = {'MAX': "'0001-01-01'", 'MIN': "'9999-12-31'"}
else:
assert False, column_type
extreme_value = extreme_value_lookup[aggregate_function]
components = ', '.join((f'\n CASE WHEN {other_columns[name]} = {quote(default_value)}\n THEN {extreme_value}\n ELSE {other_columns[name]} END' for name in column_names))
tables_used = set()
for name in column_names:
tables_used.update(other_columns[name].source_tables)
return ColumnExpression(f'\n CASE WHEN {function}({components}) = {extreme_value}\n THEN {quote(default_value)}\n ELSE {function}({components}) END', type=column_type, default_value=default_value, source_tables=list(tables_used), date_format=other_columns[column_names[0]].date_format)
|
cohort-extractor
|
positive
|
def handle_socket_error(exception, team, caller_name):
if not (isinstance(exception, WebSocketConnectionClosedException) or exception.errno in (errno.EPIPE, errno.ECONNRESET, errno.ETIMEDOUT)):
raise
w.prnt(team.channel_buffer, 'Lost connection to slack team {} (on {}), reconnecting.'.format(team.domain, caller_name))
<DeepExtract>
if 5 >= config.debug_level:
global debug_string
'Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()) = 'DEBUG: {}'.format('Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()))
if fout:
with open('/tmp/debug.log', 'a+') as log_file:
log_file.writelines('Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()) + '\n')
if main_buffer:
w.prnt('', 'slack: ' + 'Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()))
elif slack_debug and (not debug_string or debug_string in 'Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb())):
w.prnt(slack_debug, 'Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()))
</DeepExtract>
team.set_disconnected()
|
def handle_socket_error(exception, team, caller_name):
if not (isinstance(exception, WebSocketConnectionClosedException) or exception.errno in (errno.EPIPE, errno.ECONNRESET, errno.ETIMEDOUT)):
raise
w.prnt(team.channel_buffer, 'Lost connection to slack team {} (on {}), reconnecting.'.format(team.domain, caller_name))
if 5 >= config.debug_level:
global debug_string
'Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()) = 'DEBUG: {}'.format('Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()))
if fout:
with open('/tmp/debug.log', 'a+') as log_file:
log_file.writelines('Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()) + '\n')
if main_buffer:
w.prnt('', 'slack: ' + 'Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()))
elif slack_debug and (not debug_string or debug_string in 'Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb())):
w.prnt(slack_debug, 'Socket failed on {} with exception:\n{}'.format(caller_name, format_exc_tb()))
team.set_disconnected()
|
dotfiles
|
positive
|
def measurements_collection_config(collection_config_json, **kwargs):
<DeepExtract>
try:
schema = json.loads(resource_string(__package__, os.path.join('data', 'schema-measurements-collection-config.json')))
except json.JSONDecodeError as err:
raise ValidateError('Schema {} is not a valid JSON file. Error: {}'.format('schema-measurements-collection-config.json', err))
Validator = jsonschema.validators.validator_for(schema)
try:
Validator.check_schema(schema)
except jsonschema.exceptions.SchemaError as err:
raise ValidateError(f"Schema {'schema-measurements-collection-config.json'} is not a valid JSON Schema ({Validator.META_SCHEMA['$schema']}). Error: {err}")
schema = Validator(schema)
</DeepExtract>
<DeepExtract>
with open(collection_config_json, 'rb') as fh:
try:
jsonToValidate = json.load(fh)
except json.JSONDecodeError:
raise ValidateError('Supplied JSON to validate ({}) is not a valid JSON'.format(collection_config_json))
collection_config = jsonToValidate
</DeepExtract>
<DeepExtract>
print('Validating schema of {!r}...'.format(collection_config_json))
errors = list(schema.iter_errors(collection_config))
def print_errors(errors, level=1):
prefix = ' '
for error in sorted(errors, key=jsonschema.exceptions.relevance):
path = elide_path(error.absolute_path)
value = shorten_as_json(error.instance, 50, '…')
validator = error.validator
validator_value = shorten_as_json(error.validator_value, 100, '…')
print_err(indent(f'{path} {value} failed {validator} validation for {validator_value}', prefix * level))
if error.context:
if error.validator in {'oneOf', 'anyOf'}:
validator_value_idx = lambda e: e.schema_path[0]
for (idx, ctx) in grouped(error.context, key=validator_value_idx):
validator_subvalue = shorten_as_json(error.validator_value[idx], 100, '…')
print_err(indent(f'validation for arm {idx}: {validator_subvalue}', prefix * (level + 1)))
print_errors(ctx, level + 2)
else:
print_errors(error.context, level + 1)
print_errors(errors)
if errors:
raise ValidateError('Validation of {!r} failed.'.format(collection_config_json))
</DeepExtract>
if not validate_collection_display_defaults(collection_config):
raise ValidateError('Validation of the collection config display defaults failed.')
return collection_config
|
def measurements_collection_config(collection_config_json, **kwargs):
try:
schema = json.loads(resource_string(__package__, os.path.join('data', 'schema-measurements-collection-config.json')))
except json.JSONDecodeError as err:
raise ValidateError('Schema {} is not a valid JSON file. Error: {}'.format('schema-measurements-collection-config.json', err))
Validator = jsonschema.validators.validator_for(schema)
try:
Validator.check_schema(schema)
except jsonschema.exceptions.SchemaError as err:
raise ValidateError(f"Schema {'schema-measurements-collection-config.json'} is not a valid JSON Schema ({Validator.META_SCHEMA['$schema']}). Error: {err}")
schema = Validator(schema)
with open(collection_config_json, 'rb') as fh:
try:
jsonToValidate = json.load(fh)
except json.JSONDecodeError:
raise ValidateError('Supplied JSON to validate ({}) is not a valid JSON'.format(collection_config_json))
collection_config = jsonToValidate
print('Validating schema of {!r}...'.format(collection_config_json))
errors = list(schema.iter_errors(collection_config))
def print_errors(errors, level=1):
prefix = ' '
for error in sorted(errors, key=jsonschema.exceptions.relevance):
path = elide_path(error.absolute_path)
value = shorten_as_json(error.instance, 50, '…')
validator = error.validator
validator_value = shorten_as_json(error.validator_value, 100, '…')
print_err(indent(f'{path} {value} failed {validator} validation for {validator_value}', prefix * level))
if error.context:
if error.validator in {'oneOf', 'anyOf'}:
validator_value_idx = lambda e: e.schema_path[0]
for (idx, ctx) in grouped(error.context, key=validator_value_idx):
validator_subvalue = shorten_as_json(error.validator_value[idx], 100, '…')
print_err(indent(f'validation for arm {idx}: {validator_subvalue}', prefix * (level + 1)))
print_errors(ctx, level + 2)
else:
print_errors(error.context, level + 1)
print_errors(errors)
if errors:
raise ValidateError('Validation of {!r} failed.'.format(collection_config_json))
if not validate_collection_display_defaults(collection_config):
raise ValidateError('Validation of the collection config display defaults failed.')
return collection_config
|
augur
|
positive
|
def __call__(self, proposals, mask_logits, targets):
"""
Arguments:
proposals (list[BoxList])
mask_logits (Tensor)
targets (list[BoxList])
Return:
mask_loss (Tensor): scalar tensor containing the loss
"""
<DeepExtract>
labels = []
masks = []
for (proposals_per_image, targets_per_image) in zip(proposals, targets):
matched_targets = self.match_targets_to_proposals(proposals_per_image, targets_per_image)
matched_idxs = matched_targets.get_field('matched_idxs')
labels_per_image = matched_targets.get_field('labels')
labels_per_image = labels_per_image.to(dtype=torch.int64)
neg_inds = matched_idxs == Matcher.BELOW_LOW_THRESHOLD
labels_per_image[neg_inds] = 0
positive_inds = torch.nonzero(labels_per_image > 0).squeeze(1)
segmentation_masks = matched_targets.get_field('masks')
segmentation_masks = segmentation_masks[positive_inds]
positive_proposals = proposals_per_image[positive_inds]
masks_per_image = project_masks_on_boxes(segmentation_masks, positive_proposals, self.discretization_size)
labels.append(labels_per_image)
masks.append(masks_per_image)
(labels, mask_targets) = (labels, masks)
</DeepExtract>
labels = cat(labels, dim=0)
mask_targets = cat(mask_targets, dim=0)
positive_inds = torch.nonzero(labels > 0).squeeze(1)
labels_pos = labels[positive_inds]
if mask_targets.numel() == 0:
return mask_logits.sum() * 0
mask_loss = F.binary_cross_entropy_with_logits(mask_logits[positive_inds, labels_pos], mask_targets)
return mask_loss
|
def __call__(self, proposals, mask_logits, targets):
"""
Arguments:
proposals (list[BoxList])
mask_logits (Tensor)
targets (list[BoxList])
Return:
mask_loss (Tensor): scalar tensor containing the loss
"""
labels = []
masks = []
for (proposals_per_image, targets_per_image) in zip(proposals, targets):
matched_targets = self.match_targets_to_proposals(proposals_per_image, targets_per_image)
matched_idxs = matched_targets.get_field('matched_idxs')
labels_per_image = matched_targets.get_field('labels')
labels_per_image = labels_per_image.to(dtype=torch.int64)
neg_inds = matched_idxs == Matcher.BELOW_LOW_THRESHOLD
labels_per_image[neg_inds] = 0
positive_inds = torch.nonzero(labels_per_image > 0).squeeze(1)
segmentation_masks = matched_targets.get_field('masks')
segmentation_masks = segmentation_masks[positive_inds]
positive_proposals = proposals_per_image[positive_inds]
masks_per_image = project_masks_on_boxes(segmentation_masks, positive_proposals, self.discretization_size)
labels.append(labels_per_image)
masks.append(masks_per_image)
(labels, mask_targets) = (labels, masks)
labels = cat(labels, dim=0)
mask_targets = cat(mask_targets, dim=0)
positive_inds = torch.nonzero(labels > 0).squeeze(1)
labels_pos = labels[positive_inds]
if mask_targets.numel() == 0:
return mask_logits.sum() * 0
mask_loss = F.binary_cross_entropy_with_logits(mask_logits[positive_inds, labels_pos], mask_targets)
return mask_loss
|
APNet
|
positive
|
def _got_rakp1(self, data):
clienttag = data[0]
self.Rm = data[8:24]
self.rolem = data[24]
self.maxpriv = self.rolem & 7
namepresent = data[27]
if namepresent == 0:
<DeepExtract>
logger.info('IPMI Session closed %s', self.session.sockaddr[0])
del self.sessions[self.session.sockaddr[0]]
del self.session
</DeepExtract>
return
usernamebytes = data[28:]
self.username = struct.pack('%dB' % len(usernamebytes), *usernamebytes)
if self.username not in self.authdata:
logger.info('User {} supplied by client not in user_db.'.format(self.username))
<DeepExtract>
logger.info('IPMI Session closed %s', self.session.sockaddr[0])
del self.sessions[self.session.sockaddr[0]]
del self.session
</DeepExtract>
return
uuidbytes = self.uuid.bytes
uuidbytes = list(struct.unpack('%dB' % len(uuidbytes), uuidbytes))
self.uuiddata = uuidbytes
self.Rc = list(struct.unpack('16B', os.urandom(16)))
hmacdata = self.clientsessionid + self.managedsessionid + self.Rm + self.Rc + uuidbytes + [self.rolem, len(self.username)]
hmacdata = struct.pack('%dB' % len(hmacdata), *hmacdata)
hmacdata += self.username
self.kuid = self.authdata[self.username]
if self.kg is None:
self.kg = self.kuid
authcode = hmac.new(self.kuid, hmacdata, hashlib.sha1).digest()
authcode = list(struct.unpack('%dB' % len(authcode), authcode))
newmessage = [clienttag, 0, 0, 0] + self.clientsessionid + self.Rc + uuidbytes + authcode
logger.info('IPMI rakp1 request')
self.session.send_payload(newmessage, constants.payload_types['rakp2'], retry=False)
|
def _got_rakp1(self, data):
clienttag = data[0]
self.Rm = data[8:24]
self.rolem = data[24]
self.maxpriv = self.rolem & 7
namepresent = data[27]
if namepresent == 0:
logger.info('IPMI Session closed %s', self.session.sockaddr[0])
del self.sessions[self.session.sockaddr[0]]
del self.session
return
usernamebytes = data[28:]
self.username = struct.pack('%dB' % len(usernamebytes), *usernamebytes)
if self.username not in self.authdata:
logger.info('User {} supplied by client not in user_db.'.format(self.username))
logger.info('IPMI Session closed %s', self.session.sockaddr[0])
del self.sessions[self.session.sockaddr[0]]
del self.session
return
uuidbytes = self.uuid.bytes
uuidbytes = list(struct.unpack('%dB' % len(uuidbytes), uuidbytes))
self.uuiddata = uuidbytes
self.Rc = list(struct.unpack('16B', os.urandom(16)))
hmacdata = self.clientsessionid + self.managedsessionid + self.Rm + self.Rc + uuidbytes + [self.rolem, len(self.username)]
hmacdata = struct.pack('%dB' % len(hmacdata), *hmacdata)
hmacdata += self.username
self.kuid = self.authdata[self.username]
if self.kg is None:
self.kg = self.kuid
authcode = hmac.new(self.kuid, hmacdata, hashlib.sha1).digest()
authcode = list(struct.unpack('%dB' % len(authcode), authcode))
newmessage = [clienttag, 0, 0, 0] + self.clientsessionid + self.Rc + uuidbytes + authcode
logger.info('IPMI rakp1 request')
self.session.send_payload(newmessage, constants.payload_types['rakp2'], retry=False)
|
conpot
|
positive
|
def test_dos_with_bare_lf_2(self):
reader = self.create_instance_and_load_single_file(FileReader, 'test.conf', b'[context]\r\nvariable=value\r\nother=value\n')
<DeepExtract>
out = [i for i in reader]
self.assertEqual(len(out), 3)
self.assertEqual(out[0][1], '[context]')
self.assertEqual(out[1][1], 'variable=value')
self.assertEqual(out[2][1], 'other=value')
</DeepExtract>
self.assertLinted({'W_FILE_DOS_BARELF': 1, 'W_FILE_DOS_EOFCRLF': 1})
|
def test_dos_with_bare_lf_2(self):
reader = self.create_instance_and_load_single_file(FileReader, 'test.conf', b'[context]\r\nvariable=value\r\nother=value\n')
out = [i for i in reader]
self.assertEqual(len(out), 3)
self.assertEqual(out[0][1], '[context]')
self.assertEqual(out[1][1], 'variable=value')
self.assertEqual(out[2][1], 'other=value')
self.assertLinted({'W_FILE_DOS_BARELF': 1, 'W_FILE_DOS_EOFCRLF': 1})
|
asterisklint
|
positive
|
def get_NN_prediction(image):
with tf.device('/cpu:0'):
image = image / 255.0
print(CHANNEL)
dummy_channels = TARGET_CHANNELS - CHANNEL
image = tf.concat([image, tf.zeros((tf.shape(image)[0], 84, 84, dummy_channels))], 3)
input_sum = tf.reduce_sum(tf.abs(image))
<DeepExtract>
in_shape = image.get_shape().as_list()
in_channel = in_shape[-1]
5 = [5, 5]
'VALID' = 'VALID'.upper()
filter_shape = 5 + [in_channel, 32]
stride = [1, stride, stride, 1]
W = tf.get_variable('conv0' + '/W', filter_shape)
image = tf.to_float(image)
W = tf.to_float(W)
conv = tf.nn.conv2d(image, W, stride, 'VALID')
l = nl(conv, name='output')
</DeepExtract>
<DeepExtract>
padding = padding.upper()
2 = [1, 2, 2, 1]
if stride is None:
stride = 2
else:
stride = [1, stride, stride, 1]
l = tf.to_float(l)
l = tf.nn.max_pool(l, ksize=2, strides=stride, padding=padding)
</DeepExtract>
<DeepExtract>
in_shape = l.get_shape().as_list()
in_channel = in_shape[-1]
5 = [5, 5]
'VALID' = 'VALID'.upper()
filter_shape = 5 + [in_channel, 32]
stride = [1, stride, stride, 1]
W = tf.get_variable('conv1' + '/W', filter_shape)
l = tf.to_float(l)
W = tf.to_float(W)
conv = tf.nn.conv2d(l, W, stride, 'VALID')
l = nl(conv, name='output')
</DeepExtract>
<DeepExtract>
padding = padding.upper()
2 = [1, 2, 2, 1]
if stride is None:
stride = 2
else:
stride = [1, stride, stride, 1]
l = tf.to_float(l)
l = tf.nn.max_pool(l, ksize=2, strides=stride, padding=padding)
</DeepExtract>
<DeepExtract>
in_shape = l.get_shape().as_list()
in_channel = in_shape[-1]
5 = [5, 5]
'VALID' = 'VALID'.upper()
filter_shape = 5 + [in_channel, 64]
stride = [1, stride, stride, 1]
W = tf.get_variable('conv2' + '/W', filter_shape)
l = tf.to_float(l)
W = tf.to_float(W)
conv = tf.nn.conv2d(l, W, stride, 'VALID')
l = nl(conv, name='output')
</DeepExtract>
<DeepExtract>
padding = padding.upper()
2 = [1, 2, 2, 1]
if stride is None:
stride = 2
else:
stride = [1, stride, stride, 1]
l = tf.to_float(l)
l = tf.nn.max_pool(l, ksize=2, strides=stride, padding=padding)
</DeepExtract>
<DeepExtract>
in_shape = l.get_shape().as_list()
in_channel = in_shape[-1]
3 = [3, 3]
'VALID' = 'VALID'.upper()
filter_shape = 3 + [in_channel, 64]
stride = [1, stride, stride, 1]
W = tf.get_variable('conv3' + '/W', filter_shape)
l = tf.to_float(l)
W = tf.to_float(W)
conv = tf.nn.conv2d(l, W, stride, 'VALID')
l = nl(conv, name='output')
</DeepExtract>
if args.replace_with_conv:
fc_splits = []
neurons = args.fc_neurons / args.fc_splits
for i in range(args.fc_splits):
<DeepExtract>
in_shape = l.get_shape().as_list()
in_channel = in_shape[-1]
5 = [5, 5]
'VALID' = 'VALID'.upper()
filter_shape = 5 + [in_channel, neurons]
stride = [1, stride, stride, 1]
W = tf.get_variable('fc1_{}'.format(i) + '/W', filter_shape)
l = tf.to_float(l)
W = tf.to_float(W)
conv = tf.nn.conv2d(l, W, stride, 'VALID')
fc = tf.identity(conv, name='output')
</DeepExtract>
fc = tf.reshape(tensor=fc, shape=[-1, neurons])
fc_splits.append(fc)
l = tf.concat(fc_splits, axis=1)
else:
fc_splits = []
neurons = args.fc_neurons / args.fc_splits
for i in range(args.fc_splits):
<DeepExtract>
l = batch_flatten(l)
in_dim = l.get_shape().as_list()[1]
W = tf.get_variable('fc1_{}'.format(i) + '/W', [in_dim, out_dim])
if use_bias:
b = tf.get_variable('fc1_{}'.format(i) + '/b', [out_dim])
prod = tf.nn.xw_plus_b(l, W, b) if use_bias else tf.matmul(l, W)
fc = tf.identity(prod, name='output')
</DeepExtract>
fc = tf.nn.relu(fc_part, 'relu1')
fc_splits.append(fc)
l = tf.concat(fc_splits, axis=1)
<DeepExtract>
l = batch_flatten(l)
in_dim = l.get_shape().as_list()[1]
W = tf.get_variable('fc-pi' + '/W', [in_dim, NUM_ACTIONS])
if use_bias:
b = tf.get_variable('fc-pi' + '/b', [NUM_ACTIONS])
prod = tf.nn.xw_plus_b(l, W, b) if use_bias else tf.matmul(l, W)
policy = tf.identity(prod, name='output')
</DeepExtract>
<DeepExtract>
l = batch_flatten(l)
in_dim = l.get_shape().as_list()[1]
W = tf.get_variable('fc-v' + '/W', [in_dim, 1])
if use_bias:
b = tf.get_variable('fc-v' + '/b', [1])
prod = tf.nn.xw_plus_b(l, W, b) if use_bias else tf.matmul(l, W)
value = tf.identity(prod, name='output')
</DeepExtract>
return (policy, value)
|
def get_NN_prediction(image):
with tf.device('/cpu:0'):
image = image / 255.0
print(CHANNEL)
dummy_channels = TARGET_CHANNELS - CHANNEL
image = tf.concat([image, tf.zeros((tf.shape(image)[0], 84, 84, dummy_channels))], 3)
input_sum = tf.reduce_sum(tf.abs(image))
in_shape = image.get_shape().as_list()
in_channel = in_shape[-1]
5 = [5, 5]
'VALID' = 'VALID'.upper()
filter_shape = 5 + [in_channel, 32]
stride = [1, stride, stride, 1]
W = tf.get_variable('conv0' + '/W', filter_shape)
image = tf.to_float(image)
W = tf.to_float(W)
conv = tf.nn.conv2d(image, W, stride, 'VALID')
l = nl(conv, name='output')
padding = padding.upper()
2 = [1, 2, 2, 1]
if stride is None:
stride = 2
else:
stride = [1, stride, stride, 1]
l = tf.to_float(l)
l = tf.nn.max_pool(l, ksize=2, strides=stride, padding=padding)
in_shape = l.get_shape().as_list()
in_channel = in_shape[-1]
5 = [5, 5]
'VALID' = 'VALID'.upper()
filter_shape = 5 + [in_channel, 32]
stride = [1, stride, stride, 1]
W = tf.get_variable('conv1' + '/W', filter_shape)
l = tf.to_float(l)
W = tf.to_float(W)
conv = tf.nn.conv2d(l, W, stride, 'VALID')
l = nl(conv, name='output')
padding = padding.upper()
2 = [1, 2, 2, 1]
if stride is None:
stride = 2
else:
stride = [1, stride, stride, 1]
l = tf.to_float(l)
l = tf.nn.max_pool(l, ksize=2, strides=stride, padding=padding)
in_shape = l.get_shape().as_list()
in_channel = in_shape[-1]
5 = [5, 5]
'VALID' = 'VALID'.upper()
filter_shape = 5 + [in_channel, 64]
stride = [1, stride, stride, 1]
W = tf.get_variable('conv2' + '/W', filter_shape)
l = tf.to_float(l)
W = tf.to_float(W)
conv = tf.nn.conv2d(l, W, stride, 'VALID')
l = nl(conv, name='output')
padding = padding.upper()
2 = [1, 2, 2, 1]
if stride is None:
stride = 2
else:
stride = [1, stride, stride, 1]
l = tf.to_float(l)
l = tf.nn.max_pool(l, ksize=2, strides=stride, padding=padding)
in_shape = l.get_shape().as_list()
in_channel = in_shape[-1]
3 = [3, 3]
'VALID' = 'VALID'.upper()
filter_shape = 3 + [in_channel, 64]
stride = [1, stride, stride, 1]
W = tf.get_variable('conv3' + '/W', filter_shape)
l = tf.to_float(l)
W = tf.to_float(W)
conv = tf.nn.conv2d(l, W, stride, 'VALID')
l = nl(conv, name='output')
if args.replace_with_conv:
fc_splits = []
neurons = args.fc_neurons / args.fc_splits
for i in range(args.fc_splits):
in_shape = l.get_shape().as_list()
in_channel = in_shape[-1]
5 = [5, 5]
'VALID' = 'VALID'.upper()
filter_shape = 5 + [in_channel, neurons]
stride = [1, stride, stride, 1]
W = tf.get_variable('fc1_{}'.format(i) + '/W', filter_shape)
l = tf.to_float(l)
W = tf.to_float(W)
conv = tf.nn.conv2d(l, W, stride, 'VALID')
fc = tf.identity(conv, name='output')
fc = tf.reshape(tensor=fc, shape=[-1, neurons])
fc_splits.append(fc)
l = tf.concat(fc_splits, axis=1)
else:
fc_splits = []
neurons = args.fc_neurons / args.fc_splits
for i in range(args.fc_splits):
l = batch_flatten(l)
in_dim = l.get_shape().as_list()[1]
W = tf.get_variable('fc1_{}'.format(i) + '/W', [in_dim, out_dim])
if use_bias:
b = tf.get_variable('fc1_{}'.format(i) + '/b', [out_dim])
prod = tf.nn.xw_plus_b(l, W, b) if use_bias else tf.matmul(l, W)
fc = tf.identity(prod, name='output')
fc = tf.nn.relu(fc_part, 'relu1')
fc_splits.append(fc)
l = tf.concat(fc_splits, axis=1)
l = batch_flatten(l)
in_dim = l.get_shape().as_list()[1]
W = tf.get_variable('fc-pi' + '/W', [in_dim, NUM_ACTIONS])
if use_bias:
b = tf.get_variable('fc-pi' + '/b', [NUM_ACTIONS])
prod = tf.nn.xw_plus_b(l, W, b) if use_bias else tf.matmul(l, W)
policy = tf.identity(prod, name='output')
l = batch_flatten(l)
in_dim = l.get_shape().as_list()[1]
W = tf.get_variable('fc-v' + '/W', [in_dim, 1])
if use_bias:
b = tf.get_variable('fc-v' + '/b', [1])
prod = tf.nn.xw_plus_b(l, W, b) if use_bias else tf.matmul(l, W)
value = tf.identity(prod, name='output')
return (policy, value)
|
Distributed-BA3C
|
positive
|
def __or__(self, other):
"""Perform a union between two sets for boolean OR."""
if isinstance(other, InSet) and self.expression == other.expression:
if self.is_literal() and other.is_literal():
<DeepExtract>
values = OrderedDict()
for literal in self.container:
if not isinstance(literal, Literal):
continue
k = literal.value
if isinstance(literal, String):
values.setdefault(fold_case(k), literal)
else:
values[k] = literal
container = values
</DeepExtract>
for (k, v) in other.get_literals().items():
container.setdefault(k, v)
union = [v for v in container.values()]
return InSet(self.expression, union).optimize()
elif isinstance(other, Comparison) and self.expression == other.left:
if self.is_literal() and isinstance(other.right, Literal):
return self.__or__(InSet(other.left, [other.right]))
return super(InSet, self).__or__(other)
|
def __or__(self, other):
"""Perform a union between two sets for boolean OR."""
if isinstance(other, InSet) and self.expression == other.expression:
if self.is_literal() and other.is_literal():
values = OrderedDict()
for literal in self.container:
if not isinstance(literal, Literal):
continue
k = literal.value
if isinstance(literal, String):
values.setdefault(fold_case(k), literal)
else:
values[k] = literal
container = values
for (k, v) in other.get_literals().items():
container.setdefault(k, v)
union = [v for v in container.values()]
return InSet(self.expression, union).optimize()
elif isinstance(other, Comparison) and self.expression == other.left:
if self.is_literal() and isinstance(other.right, Literal):
return self.__or__(InSet(other.left, [other.right]))
return super(InSet, self).__or__(other)
|
eql
|
positive
|
def FindMiddleEdge(s, t, replace_score=BLOSUM62(), indel_cost=5):
"""
FindMiddleEdge
BA5K Find a Middle Edge in an Alignment Graph in Linear Space
Inputs:
s an amino acid string
t an amino acid string
replace_score scoring matrix
indel_cost linear indel penalty
Returns: A middle edge in the alignment graph for s and t, in the form ((i, j) (k, l)),
where (i, j) connects to (k, l).
"""
def update(j, previous, current, s, t):
"""
update
Calculate scores in current column using values from previous column
parameters:
j Index of column that is being updated
previous Data from previous coulumn
current Data in current column
s First protein string.
t Second protein string.
"""
current[0] = -j * indel_cost
for i in range(1, len(current)):
scores = [previous[i - 1] + replace_score.get_score(s[i - 1], t[j - 1]), current[i - 1] - indel_cost, previous[i] - indel_cost]
best = np.argmax(scores)
current[i] = scores[best]
return (current, previous)
def explore(s, t, limit):
"""
Find lengths of all paths from source that end at specified column
Parameters:
s First protein string. This is an explicit parameter
because FindMiddleEdge reverse the string during the second call
to calculate lengths from sink
t Second protein string.
limit Last column to be explored
"""
column_A = [-(i * indel_cost) for i in range(len(s) + 1)]
column_B = [0 for i in range(len(s) + 1)]
for j in range(1, limit + 1):
(scores, previous) = update(j, column_A, column_B, s, t) if j % 2 == 1 else update(j, column_B, column_A, s, t)
return (scores, previous)
middle_column = len(t) // 2
<DeepExtract>
column_A = [-(i * indel_cost) for i in range(len(s) + 1)]
column_B = [0 for i in range(len(s) + 1)]
for j in range(1, middle_column + 1):
(scores, previous) = update(j, column_A, column_B, s, t) if j % 2 == 1 else update(j, column_B, column_A, s, t)
(from_source, _) = (scores, previous)
</DeepExtract>
<DeepExtract>
column_A = [-(i * indel_cost) for i in range(len(s[::-1]) + 1)]
column_B = [0 for i in range(len(s[::-1]) + 1)]
for j in range(1, len(t) - middle_column + 1):
(scores, previous) = update(j, column_A, column_B, s[::-1], t[::-1]) if j % 2 == 1 else update(j, column_B, column_A, s[::-1], t[::-1])
(to_sink, _) = (scores, previous)
</DeepExtract>
length = [a + b for (a, b) in zip(from_source, to_sink[::-1])]
return ((np.argmax(length), middle_column), (np.argmax(length) + 1, middle_column + 1))
|
def FindMiddleEdge(s, t, replace_score=BLOSUM62(), indel_cost=5):
"""
FindMiddleEdge
BA5K Find a Middle Edge in an Alignment Graph in Linear Space
Inputs:
s an amino acid string
t an amino acid string
replace_score scoring matrix
indel_cost linear indel penalty
Returns: A middle edge in the alignment graph for s and t, in the form ((i, j) (k, l)),
where (i, j) connects to (k, l).
"""
def update(j, previous, current, s, t):
"""
update
Calculate scores in current column using values from previous column
parameters:
j Index of column that is being updated
previous Data from previous coulumn
current Data in current column
s First protein string.
t Second protein string.
"""
current[0] = -j * indel_cost
for i in range(1, len(current)):
scores = [previous[i - 1] + replace_score.get_score(s[i - 1], t[j - 1]), current[i - 1] - indel_cost, previous[i] - indel_cost]
best = np.argmax(scores)
current[i] = scores[best]
return (current, previous)
def explore(s, t, limit):
"""
Find lengths of all paths from source that end at specified column
Parameters:
s First protein string. This is an explicit parameter
because FindMiddleEdge reverse the string during the second call
to calculate lengths from sink
t Second protein string.
limit Last column to be explored
"""
column_A = [-(i * indel_cost) for i in range(len(s) + 1)]
column_B = [0 for i in range(len(s) + 1)]
for j in range(1, limit + 1):
(scores, previous) = update(j, column_A, column_B, s, t) if j % 2 == 1 else update(j, column_B, column_A, s, t)
return (scores, previous)
middle_column = len(t) // 2
column_A = [-(i * indel_cost) for i in range(len(s) + 1)]
column_B = [0 for i in range(len(s) + 1)]
for j in range(1, middle_column + 1):
(scores, previous) = update(j, column_A, column_B, s, t) if j % 2 == 1 else update(j, column_B, column_A, s, t)
(from_source, _) = (scores, previous)
column_A = [-(i * indel_cost) for i in range(len(s[::-1]) + 1)]
column_B = [0 for i in range(len(s[::-1]) + 1)]
for j in range(1, len(t) - middle_column + 1):
(scores, previous) = update(j, column_A, column_B, s[::-1], t[::-1]) if j % 2 == 1 else update(j, column_B, column_A, s[::-1], t[::-1])
(to_sink, _) = (scores, previous)
length = [a + b for (a, b) in zip(from_source, to_sink[::-1])]
return ((np.argmax(length), middle_column), (np.argmax(length) + 1, middle_column + 1))
|
bioinformatics
|
positive
|
def nearest_neighbor_features_per_object(reference_embeddings, query_embeddings, reference_labels, k_nearest_neighbors, gt_ids=None, n_chunks=100):
"""Calculates the distance to the nearest neighbor per object.
For every pixel of query_embeddings calculate the distance to the
nearest neighbor in the (possibly subsampled) reference_embeddings per object.
Args:
reference_embeddings: Tensor of shape [height, width, embedding_dim],
the embedding vectors for the reference frame.
query_embeddings: Tensor of shape [n_query_images, height, width,
embedding_dim], the embedding vectors for the query frames.
reference_labels: Tensor of shape [height, width, 1], the class labels of
the reference frame.
max_neighbors_per_object: Integer, the maximum number of candidates
for the nearest neighbor query per object after subsampling,
or 0 for no subsampling.
k_nearest_neighbors: Integer, the number of nearest neighbors to use.
gt_ids: Int tensor of shape [n_objs] of the sorted unique ground truth
ids in the first frame. If None, it will be derived from
reference_labels.
n_chunks: Integer, the number of chunks to use to save memory
(set to 1 for no chunking).
Returns:
nn_features: A float32 tensor of nearest neighbor features of shape
[n_query_images, height, width, n_objects, feature_dim].
gt_ids: An int32 tensor of the unique sorted object ids present
in the reference labels.
"""
assert reference_embeddings.size()[:2] == reference_labels.size()[:2]
(h, w, _) = query_embeddings.size()
reference_labels_flat = reference_labels.view(-1)
if gt_ids is None:
ref_obj_ids = torch.unique(reference_labels_flat)[-1]
ref_obj_ids = np.arange(0, ref_obj_ids.cpu() + 1)
gt_ids = torch.from_numpy(ref_obj_ids)
gt_ids = gt_ids.int()
if torch.cuda.is_available():
gt_ids = gt_ids.cuda()
else:
gt_ids = torch.arange(0, gt_ids + 1).int()
if torch.cuda.is_available():
gt_ids = gt_ids.cuda()
embedding_dim = query_embeddings.size()[-1]
query_embeddings_flat = query_embeddings.view(-1, embedding_dim)
reference_embeddings_flat = reference_embeddings.view(-1, embedding_dim)
<DeepExtract>
chunk_size = int(np.ceil(float(query_embeddings_flat.size()[0]) / n_chunks))
wrong_label_mask = reference_labels_flat != torch.unsqueeze(gt_ids, 1)
all_features = []
for n in range(n_chunks):
if n_chunks == 1:
query_embeddings_flat_chunk = query_embeddings_flat
else:
chunk_start = n * chunk_size
chunk_end = (n + 1) * chunk_size
query_embeddings_flat_chunk = query_embeddings_flat[chunk_start:chunk_end]
features = _nn_features_per_object_for_chunk(reference_embeddings_flat, query_embeddings_flat_chunk, wrong_label_mask, k_nearest_neighbors)
all_features.append(features)
if n_chunks == 1:
nn_features = all_features[0]
else:
nn_features = torch.cat(all_features, dim=0)
nn_features = nn_features
</DeepExtract>
nn_features_dim = nn_features.size()[-1]
nn_features_reshape = nn_features.view(1, h, w, gt_ids.size(0), nn_features_dim)
return (nn_features_reshape, gt_ids)
|
def nearest_neighbor_features_per_object(reference_embeddings, query_embeddings, reference_labels, k_nearest_neighbors, gt_ids=None, n_chunks=100):
"""Calculates the distance to the nearest neighbor per object.
For every pixel of query_embeddings calculate the distance to the
nearest neighbor in the (possibly subsampled) reference_embeddings per object.
Args:
reference_embeddings: Tensor of shape [height, width, embedding_dim],
the embedding vectors for the reference frame.
query_embeddings: Tensor of shape [n_query_images, height, width,
embedding_dim], the embedding vectors for the query frames.
reference_labels: Tensor of shape [height, width, 1], the class labels of
the reference frame.
max_neighbors_per_object: Integer, the maximum number of candidates
for the nearest neighbor query per object after subsampling,
or 0 for no subsampling.
k_nearest_neighbors: Integer, the number of nearest neighbors to use.
gt_ids: Int tensor of shape [n_objs] of the sorted unique ground truth
ids in the first frame. If None, it will be derived from
reference_labels.
n_chunks: Integer, the number of chunks to use to save memory
(set to 1 for no chunking).
Returns:
nn_features: A float32 tensor of nearest neighbor features of shape
[n_query_images, height, width, n_objects, feature_dim].
gt_ids: An int32 tensor of the unique sorted object ids present
in the reference labels.
"""
assert reference_embeddings.size()[:2] == reference_labels.size()[:2]
(h, w, _) = query_embeddings.size()
reference_labels_flat = reference_labels.view(-1)
if gt_ids is None:
ref_obj_ids = torch.unique(reference_labels_flat)[-1]
ref_obj_ids = np.arange(0, ref_obj_ids.cpu() + 1)
gt_ids = torch.from_numpy(ref_obj_ids)
gt_ids = gt_ids.int()
if torch.cuda.is_available():
gt_ids = gt_ids.cuda()
else:
gt_ids = torch.arange(0, gt_ids + 1).int()
if torch.cuda.is_available():
gt_ids = gt_ids.cuda()
embedding_dim = query_embeddings.size()[-1]
query_embeddings_flat = query_embeddings.view(-1, embedding_dim)
reference_embeddings_flat = reference_embeddings.view(-1, embedding_dim)
chunk_size = int(np.ceil(float(query_embeddings_flat.size()[0]) / n_chunks))
wrong_label_mask = reference_labels_flat != torch.unsqueeze(gt_ids, 1)
all_features = []
for n in range(n_chunks):
if n_chunks == 1:
query_embeddings_flat_chunk = query_embeddings_flat
else:
chunk_start = n * chunk_size
chunk_end = (n + 1) * chunk_size
query_embeddings_flat_chunk = query_embeddings_flat[chunk_start:chunk_end]
features = _nn_features_per_object_for_chunk(reference_embeddings_flat, query_embeddings_flat_chunk, wrong_label_mask, k_nearest_neighbors)
all_features.append(features)
if n_chunks == 1:
nn_features = all_features[0]
else:
nn_features = torch.cat(all_features, dim=0)
nn_features = nn_features
nn_features_dim = nn_features.size()[-1]
nn_features_reshape = nn_features.view(1, h, w, gt_ids.size(0), nn_features_dim)
return (nn_features_reshape, gt_ids)
|
CVPR2020_MANet
|
positive
|
def copy_file_into_container(client, container, managed_path, container_path, follow_links, local_follow_links, owner_id, group_id, mode, force=False, diff=False, max_file_size_for_diff=1):
if diff:
diff = {}
else:
diff = None
<DeepExtract>
try:
file_stat = os.stat(managed_path) if local_follow_links else os.lstat(managed_path)
except OSError as exc:
if exc.errno == 2:
raise DockerFileNotFound('Cannot find local file {managed_path}'.format(managed_path=managed_path))
raise
if mode is None:
mode = stat.S_IMODE(file_stat.st_mode)
if not stat.S_ISLNK(file_stat.st_mode) and (not stat.S_ISREG(file_stat.st_mode)):
raise DockerFileCopyError('Local path {managed_path} is not a symbolic link or file')
if diff is not None:
if file_stat.st_size > max_file_size_for_diff > 0:
diff['src_larger'] = max_file_size_for_diff
elif stat.S_ISLNK(file_stat.st_mode):
diff['after_header'] = managed_path
diff['after'] = os.readlink(managed_path)
else:
with open(managed_path, 'rb') as f:
content = f.read()
if is_binary(content):
diff['src_binary'] = 1
else:
diff['after_header'] = managed_path
diff['after'] = to_text(content)
if force and (not follow_links):
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff)
(container_path, mode, idempotent) = (container_path, mode, False)
(real_container_path, regular_stat, link_target) = stat_file(client, container, in_path=container_path, follow_links=follow_links)
if follow_links:
container_path = real_container_path
if regular_stat is None:
if diff is not None:
diff['before_header'] = container_path
diff['before'] = ''
(container_path, mode, idempotent) = (container_path, mode, False)
if force:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
if force is False:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
copy_dst_to_src(diff)
(container_path, mode, idempotent) = (container_path, mode, True)
if stat.S_ISLNK(file_stat.st_mode):
if link_target is None:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
local_link_target = os.readlink(managed_path)
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, local_link_target == link_target)
if link_target is not None:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
if is_container_file_not_regular_file(regular_stat):
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
if file_stat.st_size != regular_stat['size']:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
if mode != get_container_file_mode(regular_stat):
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
def process_none(in_path):
(container_path, mode, idempotent) = (container_path, mode, False)
def process_regular(in_path, tar, member):
if any([member.mode & 4095 != mode, member.uid != owner_id, member.gid != group_id, not stat.S_ISREG(file_stat.st_mode), member.size != file_stat.st_size]):
add_diff_dst_from_regular_member(diff, max_file_size_for_diff, in_path, tar, member)
(container_path, mode, idempotent) = (container_path, mode, False)
tar_f = tar.extractfile(member)
with open(managed_path, 'rb') as local_f:
is_equal = are_fileobjs_equal_with_diff_of_first(tar_f, local_f, member.size, diff, max_file_size_for_diff, in_path)
(container_path, mode, idempotent) = (container_path, mode, is_equal)
def process_symlink(in_path, member):
if diff is not None:
diff['before_header'] = in_path
diff['before'] = member.linkname
if member.mode & 4095 != mode:
(container_path, mode, idempotent) = (container_path, mode, False)
if member.uid != owner_id:
(container_path, mode, idempotent) = (container_path, mode, False)
if member.gid != group_id:
(container_path, mode, idempotent) = (container_path, mode, False)
if not stat.S_ISLNK(file_stat.st_mode):
(container_path, mode, idempotent) = (container_path, mode, False)
local_link_target = os.readlink(managed_path)
(container_path, mode, idempotent) = (container_path, mode, member.linkname == local_link_target)
def process_other(in_path, member):
add_other_diff(diff, in_path, member)
(container_path, mode, idempotent) = (container_path, mode, False)
(container_path, mode, idempotent) = fetch_file_ex(client, container, in_path=container_path, process_none=process_none, process_regular=process_regular, process_symlink=process_symlink, process_other=process_other, follow_links=follow_links)
</DeepExtract>
changed = not idempotent
if changed and (not client.module.check_mode):
put_file(client, container, in_path=managed_path, out_path=container_path, user_id=owner_id, group_id=group_id, mode=mode, follow_links=local_follow_links)
result = dict(container_path=container_path, changed=changed)
if diff:
result['diff'] = diff
client.module.exit_json(**result)
|
def copy_file_into_container(client, container, managed_path, container_path, follow_links, local_follow_links, owner_id, group_id, mode, force=False, diff=False, max_file_size_for_diff=1):
if diff:
diff = {}
else:
diff = None
try:
file_stat = os.stat(managed_path) if local_follow_links else os.lstat(managed_path)
except OSError as exc:
if exc.errno == 2:
raise DockerFileNotFound('Cannot find local file {managed_path}'.format(managed_path=managed_path))
raise
if mode is None:
mode = stat.S_IMODE(file_stat.st_mode)
if not stat.S_ISLNK(file_stat.st_mode) and (not stat.S_ISREG(file_stat.st_mode)):
raise DockerFileCopyError('Local path {managed_path} is not a symbolic link or file')
if diff is not None:
if file_stat.st_size > max_file_size_for_diff > 0:
diff['src_larger'] = max_file_size_for_diff
elif stat.S_ISLNK(file_stat.st_mode):
diff['after_header'] = managed_path
diff['after'] = os.readlink(managed_path)
else:
with open(managed_path, 'rb') as f:
content = f.read()
if is_binary(content):
diff['src_binary'] = 1
else:
diff['after_header'] = managed_path
diff['after'] = to_text(content)
if force and (not follow_links):
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff)
(container_path, mode, idempotent) = (container_path, mode, False)
(real_container_path, regular_stat, link_target) = stat_file(client, container, in_path=container_path, follow_links=follow_links)
if follow_links:
container_path = real_container_path
if regular_stat is None:
if diff is not None:
diff['before_header'] = container_path
diff['before'] = ''
(container_path, mode, idempotent) = (container_path, mode, False)
if force:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
if force is False:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
copy_dst_to_src(diff)
(container_path, mode, idempotent) = (container_path, mode, True)
if stat.S_ISLNK(file_stat.st_mode):
if link_target is None:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
local_link_target = os.readlink(managed_path)
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, local_link_target == link_target)
if link_target is not None:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
if is_container_file_not_regular_file(regular_stat):
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
if file_stat.st_size != regular_stat['size']:
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
if mode != get_container_file_mode(regular_stat):
retrieve_diff(client, container, container_path, follow_links, diff, max_file_size_for_diff, regular_stat, link_target)
(container_path, mode, idempotent) = (container_path, mode, False)
def process_none(in_path):
(container_path, mode, idempotent) = (container_path, mode, False)
def process_regular(in_path, tar, member):
if any([member.mode & 4095 != mode, member.uid != owner_id, member.gid != group_id, not stat.S_ISREG(file_stat.st_mode), member.size != file_stat.st_size]):
add_diff_dst_from_regular_member(diff, max_file_size_for_diff, in_path, tar, member)
(container_path, mode, idempotent) = (container_path, mode, False)
tar_f = tar.extractfile(member)
with open(managed_path, 'rb') as local_f:
is_equal = are_fileobjs_equal_with_diff_of_first(tar_f, local_f, member.size, diff, max_file_size_for_diff, in_path)
(container_path, mode, idempotent) = (container_path, mode, is_equal)
def process_symlink(in_path, member):
if diff is not None:
diff['before_header'] = in_path
diff['before'] = member.linkname
if member.mode & 4095 != mode:
(container_path, mode, idempotent) = (container_path, mode, False)
if member.uid != owner_id:
(container_path, mode, idempotent) = (container_path, mode, False)
if member.gid != group_id:
(container_path, mode, idempotent) = (container_path, mode, False)
if not stat.S_ISLNK(file_stat.st_mode):
(container_path, mode, idempotent) = (container_path, mode, False)
local_link_target = os.readlink(managed_path)
(container_path, mode, idempotent) = (container_path, mode, member.linkname == local_link_target)
def process_other(in_path, member):
add_other_diff(diff, in_path, member)
(container_path, mode, idempotent) = (container_path, mode, False)
(container_path, mode, idempotent) = fetch_file_ex(client, container, in_path=container_path, process_none=process_none, process_regular=process_regular, process_symlink=process_symlink, process_other=process_other, follow_links=follow_links)
changed = not idempotent
if changed and (not client.module.check_mode):
put_file(client, container, in_path=managed_path, out_path=container_path, user_id=owner_id, group_id=group_id, mode=mode, follow_links=local_follow_links)
result = dict(container_path=container_path, changed=changed)
if diff:
result['diff'] = diff
client.module.exit_json(**result)
|
community.docker
|
positive
|
def vLineTo(self, yCoord, forConstruction=False):
"""
Make a vertical line from the current point to the provided y coordinate.
Useful if it is more convenient to specify the end location rather than distance,
as in :py:meth:`vLine`
:param float yCoord: y coordinate for the end of the line
:return: the Workplane object with the current point at the end of the new line
"""
<DeepExtract>
obj = self.objects[-1]
if isinstance(obj, Edge):
p = obj.endPoint()
elif isinstance(obj, Vector):
p = obj
else:
raise RuntimeError("Cannot convert object type '%s' to vector " % type(obj))
if True:
p = self.plane.toLocalCoords(p)
else:
p = p
</DeepExtract>
return self.lineTo(p.x, yCoord, forConstruction)
|
def vLineTo(self, yCoord, forConstruction=False):
"""
Make a vertical line from the current point to the provided y coordinate.
Useful if it is more convenient to specify the end location rather than distance,
as in :py:meth:`vLine`
:param float yCoord: y coordinate for the end of the line
:return: the Workplane object with the current point at the end of the new line
"""
obj = self.objects[-1]
if isinstance(obj, Edge):
p = obj.endPoint()
elif isinstance(obj, Vector):
p = obj
else:
raise RuntimeError("Cannot convert object type '%s' to vector " % type(obj))
if True:
p = self.plane.toLocalCoords(p)
else:
p = p
return self.lineTo(p.x, yCoord, forConstruction)
|
cadquery
|
positive
|
def _find_augmenting_path(assignment, adj_matrix):
"""Finds an augmenting path given an assignment and an adjacency matrix.
The augmenting path search starts from the unassigned workers, then goes on
to find jobs (via an unassigned pairing), then back again to workers (via an
existing pairing), and so on. The path alternates between unassigned and
existing pairings. Returns the state after the search.
Note: In the state the worker and job, indices are 1-indexed so that we can
use 0 to represent unreachable nodes. State contains the following keys:
- jobs: A [batch_size, 1, num_elems] tensor containing the highest index
unassigned worker that can reach this job through a path.
- jobs_from_worker: A [batch_size, num_elems] tensor containing the worker
reached immediately before this job.
- workers: A [batch_size, num_elems, 1] tensor containing the highest index
unassigned worker that can reach this worker through a path.
- workers_from_job: A [batch_size, num_elems] tensor containing the job
reached immediately before this worker.
- new_jobs: A bool [batch_size, num_elems] tensor containing True if the
unassigned job can be reached via a path.
State can be used to recover the path via backtracking.
Args:
assignment: A bool [batch_size, num_elems, num_elems] tensor, where each
element of the inner matrix represents whether the worker has been matched
to the job. This may be a partial assignment.
adj_matrix: A bool [batch_size, num_elems, num_elems] tensor, where each
element of the inner matrix represents whether the worker (row) can be
matched to the job (column).
Returns:
A state dict, which represents the outcome of running an augmenting
path search on the graph given the assignment.
"""
<DeepExtract>
actual_rank = assignment.shape.ndims
if 3 and actual_rank != 3:
raise ValueError('The tensor has rank %d which is not equal to the expected rank %d' % (actual_rank, 3))
shape = assignment.shape.as_list()
dynamic = tf.shape(assignment)
output = [dim if dim else dynamic[ind] for (ind, dim) in enumerate(shape)]
(batch_size, num_elems, _) = output
</DeepExtract>
unassigned_workers = ~tf.reduce_any(assignment, axis=2, keepdims=True)
unassigned_jobs = ~tf.reduce_any(assignment, axis=1, keepdims=True)
unassigned_pairings = tf.cast(adj_matrix & ~assignment, tf.int32)
existing_pairings = tf.cast(assignment, tf.int32)
worker_indices = tf.range(1, num_elems + 1, dtype=tf.int32)
init_workers = tf.tile(worker_indices[tf.newaxis, :, tf.newaxis], [batch_size, 1, 1])
init_workers *= tf.cast(unassigned_workers, tf.int32)
state = {'jobs': tf.zeros((batch_size, 1, num_elems), dtype=tf.int32), 'jobs_from_worker': tf.zeros((batch_size, num_elems), dtype=tf.int32), 'workers': init_workers, 'workers_from_job': tf.zeros((batch_size, num_elems), dtype=tf.int32)}
def _has_active_workers(state, curr_workers):
"""Check if there are still active workers."""
del state
return tf.reduce_sum(curr_workers) > 0
def _augment_step(state, curr_workers):
"""Performs one search step."""
potential_jobs = curr_workers * unassigned_pairings
curr_jobs = tf.reduce_max(potential_jobs, axis=1, keepdims=True)
curr_jobs_from_worker = 1 + tf.argmax(potential_jobs, axis=1, output_type=tf.int32)
default_jobs = tf.zeros_like(state['jobs'], dtype=state['jobs'].dtype)
curr_jobs = tf.where(state['jobs'] > 0, default_jobs, curr_jobs)
curr_jobs_from_worker *= tf.cast(curr_jobs > 0, tf.int32)[:, 0, :]
potential_workers = curr_jobs * existing_pairings
curr_workers = tf.reduce_max(potential_workers, axis=2, keepdims=True)
curr_workers_from_job = 1 + tf.argmax(potential_workers, axis=2, output_type=tf.int32)
default_workers = tf.zeros_like(state['workers'])
curr_workers = tf.where(state['workers'] > 0, default_workers, curr_workers)
curr_workers_from_job *= tf.cast(curr_workers > 0, tf.int32)[:, :, 0]
state = state.copy()
state['jobs'] = tf.maximum(state['jobs'], curr_jobs)
state['jobs_from_worker'] = tf.maximum(state['jobs_from_worker'], curr_jobs_from_worker)
state['workers'] = tf.maximum(state['workers'], curr_workers)
state['workers_from_job'] = tf.maximum(state['workers_from_job'], curr_workers_from_job)
return (state, curr_workers)
with tf.name_scope('find_augmenting_path'):
(state, _) = tf.while_loop(_has_active_workers, _augment_step, (state, init_workers), back_prop=False)
new_jobs = (state['jobs'] > 0) & unassigned_jobs
state['new_jobs'] = new_jobs[:, 0, :]
return state
|
def _find_augmenting_path(assignment, adj_matrix):
"""Finds an augmenting path given an assignment and an adjacency matrix.
The augmenting path search starts from the unassigned workers, then goes on
to find jobs (via an unassigned pairing), then back again to workers (via an
existing pairing), and so on. The path alternates between unassigned and
existing pairings. Returns the state after the search.
Note: In the state the worker and job, indices are 1-indexed so that we can
use 0 to represent unreachable nodes. State contains the following keys:
- jobs: A [batch_size, 1, num_elems] tensor containing the highest index
unassigned worker that can reach this job through a path.
- jobs_from_worker: A [batch_size, num_elems] tensor containing the worker
reached immediately before this job.
- workers: A [batch_size, num_elems, 1] tensor containing the highest index
unassigned worker that can reach this worker through a path.
- workers_from_job: A [batch_size, num_elems] tensor containing the job
reached immediately before this worker.
- new_jobs: A bool [batch_size, num_elems] tensor containing True if the
unassigned job can be reached via a path.
State can be used to recover the path via backtracking.
Args:
assignment: A bool [batch_size, num_elems, num_elems] tensor, where each
element of the inner matrix represents whether the worker has been matched
to the job. This may be a partial assignment.
adj_matrix: A bool [batch_size, num_elems, num_elems] tensor, where each
element of the inner matrix represents whether the worker (row) can be
matched to the job (column).
Returns:
A state dict, which represents the outcome of running an augmenting
path search on the graph given the assignment.
"""
actual_rank = assignment.shape.ndims
if 3 and actual_rank != 3:
raise ValueError('The tensor has rank %d which is not equal to the expected rank %d' % (actual_rank, 3))
shape = assignment.shape.as_list()
dynamic = tf.shape(assignment)
output = [dim if dim else dynamic[ind] for (ind, dim) in enumerate(shape)]
(batch_size, num_elems, _) = output
unassigned_workers = ~tf.reduce_any(assignment, axis=2, keepdims=True)
unassigned_jobs = ~tf.reduce_any(assignment, axis=1, keepdims=True)
unassigned_pairings = tf.cast(adj_matrix & ~assignment, tf.int32)
existing_pairings = tf.cast(assignment, tf.int32)
worker_indices = tf.range(1, num_elems + 1, dtype=tf.int32)
init_workers = tf.tile(worker_indices[tf.newaxis, :, tf.newaxis], [batch_size, 1, 1])
init_workers *= tf.cast(unassigned_workers, tf.int32)
state = {'jobs': tf.zeros((batch_size, 1, num_elems), dtype=tf.int32), 'jobs_from_worker': tf.zeros((batch_size, num_elems), dtype=tf.int32), 'workers': init_workers, 'workers_from_job': tf.zeros((batch_size, num_elems), dtype=tf.int32)}
def _has_active_workers(state, curr_workers):
"""Check if there are still active workers."""
del state
return tf.reduce_sum(curr_workers) > 0
def _augment_step(state, curr_workers):
"""Performs one search step."""
potential_jobs = curr_workers * unassigned_pairings
curr_jobs = tf.reduce_max(potential_jobs, axis=1, keepdims=True)
curr_jobs_from_worker = 1 + tf.argmax(potential_jobs, axis=1, output_type=tf.int32)
default_jobs = tf.zeros_like(state['jobs'], dtype=state['jobs'].dtype)
curr_jobs = tf.where(state['jobs'] > 0, default_jobs, curr_jobs)
curr_jobs_from_worker *= tf.cast(curr_jobs > 0, tf.int32)[:, 0, :]
potential_workers = curr_jobs * existing_pairings
curr_workers = tf.reduce_max(potential_workers, axis=2, keepdims=True)
curr_workers_from_job = 1 + tf.argmax(potential_workers, axis=2, output_type=tf.int32)
default_workers = tf.zeros_like(state['workers'])
curr_workers = tf.where(state['workers'] > 0, default_workers, curr_workers)
curr_workers_from_job *= tf.cast(curr_workers > 0, tf.int32)[:, :, 0]
state = state.copy()
state['jobs'] = tf.maximum(state['jobs'], curr_jobs)
state['jobs_from_worker'] = tf.maximum(state['jobs_from_worker'], curr_jobs_from_worker)
state['workers'] = tf.maximum(state['workers'], curr_workers)
state['workers_from_job'] = tf.maximum(state['workers_from_job'], curr_workers_from_job)
return (state, curr_workers)
with tf.name_scope('find_augmenting_path'):
(state, _) = tf.while_loop(_has_active_workers, _augment_step, (state, init_workers), back_prop=False)
new_jobs = (state['jobs'] > 0) & unassigned_jobs
state['new_jobs'] = new_jobs[:, 0, :]
return state
|
deeplab2
|
positive
|
def _initprop_(self, name, value):
if not hasattr(self, '_viewcount'):
raise ValueError('base Model __init__ must be called')
super()._initprop_(name, value)
def notify_js(event):
<DeepExtract>
if self._viewcount > 0:
if WIDGET_ENV == 'colab':
colab_output.eval_js(minify(f'\n (window.send_{id(self)} = window.send_{id(self)} ||\n new BroadcastChannel("channel_{id(self)}")\n ).postMessage({json.dumps(args)});\n '), ignore_result=True)
elif WIDGET_ENV == 'jupyter':
if not self._comms:
self._queue.append(args)
return
for comm in self._comms:
comm.send(args)
</DeepExtract>
if isinstance(value, Trigger):
value.on(notify_js, internal=True)
|
def _initprop_(self, name, value):
if not hasattr(self, '_viewcount'):
raise ValueError('base Model __init__ must be called')
super()._initprop_(name, value)
def notify_js(event):
if self._viewcount > 0:
if WIDGET_ENV == 'colab':
colab_output.eval_js(minify(f'\n (window.send_{id(self)} = window.send_{id(self)} ||\n new BroadcastChannel("channel_{id(self)}")\n ).postMessage({json.dumps(args)});\n '), ignore_result=True)
elif WIDGET_ENV == 'jupyter':
if not self._comms:
self._queue.append(args)
return
for comm in self._comms:
comm.send(args)
if isinstance(value, Trigger):
value.on(notify_js, internal=True)
|
dissect
|
positive
|
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
index_parser = subparsers.add_parser('index', help='Build an index for a corpus.')
index_parser.set_defaults(command='index')
index_parser.add_argument('--output', '-o', required=True, help='Path to store the index.')
index_parser.add_argument('--data', '-d', required=True, help='Directory or archive containing SGF files.')
index_parser.add_argument('--chunk-size', '-c', type=int, default=20000, help='Number of examples per training chunk.')
show_parser = subparsers.add_parser('show', help='Show a summary of an index.')
show_parser.set_defaults(command='show')
show_parser.add_argument('--file', '-f', required=True, help='Index file.')
init_parser = subparsers.add_parser('init', help='Start training.')
init_parser.set_defaults(command='init')
init_parser.add_argument('--index', '-i', required=True, help='Index file.')
init_parser.add_argument('--progress', '-p', required=True, help='Progress file.')
init_parser.add_argument('--network', '-n', required=True, help='Python module that defines the network architecture, e.g. "networks.small"')
train_parser = subparsers.add_parser('train', help='Do some training.')
train_parser.set_defaults(command='train')
train_parser.add_argument('--index', '-i', required=True, help='Index file.')
train_parser.add_argument('--progress', '-p', required=True, help='Progress file.')
train_parser.add_argument('--workers', '-w', type=int, default=1, help='Number of workers to use for preprocessing boards.')
export_parser = subparsers.add_parser('export', help='Export a bot from a training run.')
export_parser.set_defaults(command='export')
export_parser.add_argument('--progress', '-p', required=True, help='Progress file.')
export_parser.add_argument('--bot', '-b', help='Bot file name.')
args = parser.parse_args()
if args.command == 'index':
<DeepExtract>
corpus_index = build_index(args.data, args.chunk_size)
store_index(corpus_index, open(args.output, 'w'))
</DeepExtract>
elif args.command == 'show':
<DeepExtract>
corpus_index = load_index(open(args.file))
print('Index contains %d chunks in %d physical files' % (corpus_index.num_chunks, len(corpus_index.physical_files)))
</DeepExtract>
elif args.command == 'init':
<DeepExtract>
corpus_index = load_index(open(args.index))
layer_fn = _load_network_by_name(args.network)
TrainingRun.create(args.progress, corpus_index, layer_fn)
</DeepExtract>
elif args.command == 'train':
<DeepExtract>
corpus_index = load_index(open(args.index))
print('Index contains %d chunks in %d physical files' % (corpus_index.num_chunks, len(corpus_index.physical_files)))
if not os.path.exists(args.progress):
print('%s does not exist. Run train.py init first.' % (args.progress,))
else:
run = TrainingRun.load(args.progress)
q = multiprocessing.Queue(maxsize=2 * args.workers)
stop_q = multiprocessing.Queue()
p = multiprocessing.Process(target=prepare_training_data, args=(args.workers, run.chunks_completed, corpus_index, q, stop_q))
p.start()
try:
while True:
print('Waiting for prepared training chunk...')
wait_start_ts = time.time()
(X, Y) = q.get()
wait_end_ts = time.time()
print('Idle %.1f seconds' % (wait_end_ts - wait_start_ts,))
print('Training epoch %d chunk %d/%d...' % (run.epochs_completed + 1, run.chunks_completed + 1, run.num_chunks))
run.model.fit(X, Y, epochs=1)
run.complete_chunk()
finally:
while not q.empty():
q.get()
q.close()
q.join_thread()
print('Shutting down workers, please wait...')
stop_q.put(1)
stop_q.close()
p.join()
</DeepExtract>
elif args.command == 'export':
<DeepExtract>
run = TrainingRun.load(args.progress)
model_file = args.bot + '_bot.yml'
weight_file = args.bot + '_weights.hd5'
run.model.save_weights(weight_file, overwrite=True)
with open(model_file, 'w') as yml:
yml.write(run.model.to_yaml())
</DeepExtract>
|
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
index_parser = subparsers.add_parser('index', help='Build an index for a corpus.')
index_parser.set_defaults(command='index')
index_parser.add_argument('--output', '-o', required=True, help='Path to store the index.')
index_parser.add_argument('--data', '-d', required=True, help='Directory or archive containing SGF files.')
index_parser.add_argument('--chunk-size', '-c', type=int, default=20000, help='Number of examples per training chunk.')
show_parser = subparsers.add_parser('show', help='Show a summary of an index.')
show_parser.set_defaults(command='show')
show_parser.add_argument('--file', '-f', required=True, help='Index file.')
init_parser = subparsers.add_parser('init', help='Start training.')
init_parser.set_defaults(command='init')
init_parser.add_argument('--index', '-i', required=True, help='Index file.')
init_parser.add_argument('--progress', '-p', required=True, help='Progress file.')
init_parser.add_argument('--network', '-n', required=True, help='Python module that defines the network architecture, e.g. "networks.small"')
train_parser = subparsers.add_parser('train', help='Do some training.')
train_parser.set_defaults(command='train')
train_parser.add_argument('--index', '-i', required=True, help='Index file.')
train_parser.add_argument('--progress', '-p', required=True, help='Progress file.')
train_parser.add_argument('--workers', '-w', type=int, default=1, help='Number of workers to use for preprocessing boards.')
export_parser = subparsers.add_parser('export', help='Export a bot from a training run.')
export_parser.set_defaults(command='export')
export_parser.add_argument('--progress', '-p', required=True, help='Progress file.')
export_parser.add_argument('--bot', '-b', help='Bot file name.')
args = parser.parse_args()
if args.command == 'index':
corpus_index = build_index(args.data, args.chunk_size)
store_index(corpus_index, open(args.output, 'w'))
elif args.command == 'show':
corpus_index = load_index(open(args.file))
print('Index contains %d chunks in %d physical files' % (corpus_index.num_chunks, len(corpus_index.physical_files)))
elif args.command == 'init':
corpus_index = load_index(open(args.index))
layer_fn = _load_network_by_name(args.network)
TrainingRun.create(args.progress, corpus_index, layer_fn)
elif args.command == 'train':
corpus_index = load_index(open(args.index))
print('Index contains %d chunks in %d physical files' % (corpus_index.num_chunks, len(corpus_index.physical_files)))
if not os.path.exists(args.progress):
print('%s does not exist. Run train.py init first.' % (args.progress,))
else:
run = TrainingRun.load(args.progress)
q = multiprocessing.Queue(maxsize=2 * args.workers)
stop_q = multiprocessing.Queue()
p = multiprocessing.Process(target=prepare_training_data, args=(args.workers, run.chunks_completed, corpus_index, q, stop_q))
p.start()
try:
while True:
print('Waiting for prepared training chunk...')
wait_start_ts = time.time()
(X, Y) = q.get()
wait_end_ts = time.time()
print('Idle %.1f seconds' % (wait_end_ts - wait_start_ts,))
print('Training epoch %d chunk %d/%d...' % (run.epochs_completed + 1, run.chunks_completed + 1, run.num_chunks))
run.model.fit(X, Y, epochs=1)
run.complete_chunk()
finally:
while not q.empty():
q.get()
q.close()
q.join_thread()
print('Shutting down workers, please wait...')
stop_q.put(1)
stop_q.close()
p.join()
elif args.command == 'export':
run = TrainingRun.load(args.progress)
model_file = args.bot + '_bot.yml'
weight_file = args.bot + '_weights.hd5'
run.model.save_weights(weight_file, overwrite=True)
with open(model_file, 'w') as yml:
yml.write(run.model.to_yaml())
</DeepExtract>
|
deep_learning_and_the_game_of_go
|
positive
|
def update_observation_count(self, count):
if count and self.handle is None:
print('Starting the clock')
<DeepExtract>
self.handle = asyncio.get_event_loop().call_later(5, self.notify)
</DeepExtract>
if count == 0 and self.handle:
print('Stopping the clock')
self.handle.cancel()
self.handle = None
|
def update_observation_count(self, count):
if count and self.handle is None:
print('Starting the clock')
self.handle = asyncio.get_event_loop().call_later(5, self.notify)
if count == 0 and self.handle:
print('Stopping the clock')
self.handle.cancel()
self.handle = None
|
aiocoap
|
positive
|
def test_view_manage_wrong_user(self):
<DeepExtract>
self.client.login(username='admin', password='admin')
</DeepExtract>
url = reverse('admin:%s_%s_permissions_manage_user' % self.obj_info, kwargs={'object_pk': self.obj.pk, 'user_id': -10})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
|
def test_view_manage_wrong_user(self):
self.client.login(username='admin', password='admin')
url = reverse('admin:%s_%s_permissions_manage_user' % self.obj_info, kwargs={'object_pk': self.obj.pk, 'user_id': -10})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
|
django-guardian
|
positive
|
def _atrousValues(self, bottleneck):
"""Verify the values of dense feature extraction by atrous convolution.
Make sure that dense feature extraction by stack_blocks_dense() followed by
subsampling gives identical results to feature extraction at the nominal
network output stride using the simple self._stack_blocks_nondense() above.
Args:
bottleneck: The bottleneck function.
"""
blocks = [resnet_utils.Block('block1', bottleneck, [(4, 1, 1), (4, 1, 2)]), resnet_utils.Block('block2', bottleneck, [(8, 2, 1), (8, 2, 2)]), resnet_utils.Block('block3', bottleneck, [(16, 4, 1), (16, 4, 2)]), resnet_utils.Block('block4', bottleneck, [(32, 8, 1), (32, 8, 1)])]
nominal_stride = 8
height = 30
width = 31
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
with slim.arg_scope([slim.batch_norm], is_training=False):
for output_stride in [1, 2, 4, 8, None]:
with tf.Graph().as_default():
with self.test_session() as sess:
tf.set_random_seed(0)
<DeepExtract>
if None in [1, height, width, 3]:
inputs = tf.placeholder(tf.float32, (1, height, width, 3))
else:
inputs = tf.to_float(np.tile(np.reshape(np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(width), [1, width]), [1, height, width, 1]), [1, 1, 1, 3]))
</DeepExtract>
output = resnet_utils.stack_blocks_dense(inputs, blocks, output_stride)
if output_stride is None:
factor = 1
else:
factor = nominal_stride // output_stride
output = resnet_utils.subsample(output, factor)
tf.get_variable_scope().reuse_variables()
<DeepExtract>
for block in blocks:
with tf.variable_scope(block.scope, 'block', [inputs]):
for (i, unit) in enumerate(block.args):
(depth, depth_bottleneck, stride) = unit
with tf.variable_scope('unit_%d' % (i + 1), values=[inputs]):
inputs = block.unit_fn(inputs, depth=depth, depth_bottleneck=depth_bottleneck, stride=stride, rate=1)
expected = inputs
</DeepExtract>
sess.run(tf.global_variables_initializer())
(output, expected) = sess.run([output, expected])
self.assertAllClose(output, expected, atol=0.0001, rtol=0.0001)
|
def _atrousValues(self, bottleneck):
"""Verify the values of dense feature extraction by atrous convolution.
Make sure that dense feature extraction by stack_blocks_dense() followed by
subsampling gives identical results to feature extraction at the nominal
network output stride using the simple self._stack_blocks_nondense() above.
Args:
bottleneck: The bottleneck function.
"""
blocks = [resnet_utils.Block('block1', bottleneck, [(4, 1, 1), (4, 1, 2)]), resnet_utils.Block('block2', bottleneck, [(8, 2, 1), (8, 2, 2)]), resnet_utils.Block('block3', bottleneck, [(16, 4, 1), (16, 4, 2)]), resnet_utils.Block('block4', bottleneck, [(32, 8, 1), (32, 8, 1)])]
nominal_stride = 8
height = 30
width = 31
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
with slim.arg_scope([slim.batch_norm], is_training=False):
for output_stride in [1, 2, 4, 8, None]:
with tf.Graph().as_default():
with self.test_session() as sess:
tf.set_random_seed(0)
if None in [1, height, width, 3]:
inputs = tf.placeholder(tf.float32, (1, height, width, 3))
else:
inputs = tf.to_float(np.tile(np.reshape(np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(width), [1, width]), [1, height, width, 1]), [1, 1, 1, 3]))
output = resnet_utils.stack_blocks_dense(inputs, blocks, output_stride)
if output_stride is None:
factor = 1
else:
factor = nominal_stride // output_stride
output = resnet_utils.subsample(output, factor)
tf.get_variable_scope().reuse_variables()
for block in blocks:
with tf.variable_scope(block.scope, 'block', [inputs]):
for (i, unit) in enumerate(block.args):
(depth, depth_bottleneck, stride) = unit
with tf.variable_scope('unit_%d' % (i + 1), values=[inputs]):
inputs = block.unit_fn(inputs, depth=depth, depth_bottleneck=depth_bottleneck, stride=stride, rate=1)
expected = inputs
sess.run(tf.global_variables_initializer())
(output, expected) = sess.run([output, expected])
self.assertAllClose(output, expected, atol=0.0001, rtol=0.0001)
|
ARNet
|
positive
|
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
scheme = scheme or 'http'
port = port or port_by_scheme.get(scheme, 80)
pool_key = (scheme, host, port)
pool = self.pools.get(pool_key)
if pool:
return pool
<DeepExtract>
pool_cls = pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if scheme == 'http':
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
pool = pool_cls(host, port, **kwargs)
</DeepExtract>
self.pools[pool_key] = pool
return pool
|
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
scheme = scheme or 'http'
port = port or port_by_scheme.get(scheme, 80)
pool_key = (scheme, host, port)
pool = self.pools.get(pool_key)
if pool:
return pool
pool_cls = pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if scheme == 'http':
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
pool = pool_cls(host, port, **kwargs)
self.pools[pool_key] = pool
return pool
|
alp
|
positive
|
def extract_headers(mail, headers=None):
"""
returns subset of this messages headers as human-readable format:
all header values are decoded, the resulting string has
one line "KEY: VALUE" for each requested header present in the mail.
:param mail: the mail to use
:type mail: :class:`email.message.EmailMessage`
:param headers: headers to extract
:type headers: list of str
"""
headertext = ''
if headers is None:
headers = mail.keys()
for key in headers:
value = ''
if key in mail:
<DeepExtract>
logging.debug('unquoted header: |%s|', mail.get(key, ''))
valuelist = email.header.decode_header(mail.get(key, ''))
decoded_list = []
for (v, enc) in valuelist:
v = string_decode(v, enc)
decoded_list.append(string_sanitize(v))
value = ''.join(decoded_list)
if normalize:
value = re.sub('\\n\\s+', ' ', value)
value = value
</DeepExtract>
headertext += '%s: %s\n' % (key, value)
return headertext
|
def extract_headers(mail, headers=None):
"""
returns subset of this messages headers as human-readable format:
all header values are decoded, the resulting string has
one line "KEY: VALUE" for each requested header present in the mail.
:param mail: the mail to use
:type mail: :class:`email.message.EmailMessage`
:param headers: headers to extract
:type headers: list of str
"""
headertext = ''
if headers is None:
headers = mail.keys()
for key in headers:
value = ''
if key in mail:
logging.debug('unquoted header: |%s|', mail.get(key, ''))
valuelist = email.header.decode_header(mail.get(key, ''))
decoded_list = []
for (v, enc) in valuelist:
v = string_decode(v, enc)
decoded_list.append(string_sanitize(v))
value = ''.join(decoded_list)
if normalize:
value = re.sub('\\n\\s+', ' ', value)
value = value
headertext += '%s: %s\n' % (key, value)
return headertext
|
alot
|
positive
|
def setMode(self, dom, wId, mode):
id = 'Value.' + str(wId)
<DeepExtract>
set(wId, Setting.MODE, mode)
GPIOq.pinMode(wId, 1 if mode > 1 else mode)
if mode == Mode.PWM:
GPIOq.softPWMCreate(wId)
set(wId, Setting.VALUE, GPIOq.digitalRead(wId))
</DeepExtract>
dom.setValue('Value.' + str(wId), self._getValue(wId))
dom.setAttribute(id, 'value', self._getValue(wId))
if mode == Mode.IN:
dom.disableElement(id)
dom.setAttribute(id, 'step', '100')
elif mode == Mode.OUT:
dom.enableElement(id)
dom.setAttribute(id, 'step', '100')
elif mode == Mode.PWM:
dom.enableElement(id)
dom.setAttribute(id, 'step', '1')
else:
sys.exit('???')
|
def setMode(self, dom, wId, mode):
id = 'Value.' + str(wId)
set(wId, Setting.MODE, mode)
GPIOq.pinMode(wId, 1 if mode > 1 else mode)
if mode == Mode.PWM:
GPIOq.softPWMCreate(wId)
set(wId, Setting.VALUE, GPIOq.digitalRead(wId))
dom.setValue('Value.' + str(wId), self._getValue(wId))
dom.setAttribute(id, 'value', self._getValue(wId))
if mode == Mode.IN:
dom.disableElement(id)
dom.setAttribute(id, 'step', '100')
elif mode == Mode.OUT:
dom.enableElement(id)
dom.setAttribute(id, 'step', '100')
elif mode == Mode.PWM:
dom.enableElement(id)
dom.setAttribute(id, 'step', '1')
else:
sys.exit('???')
|
atlas-python
|
positive
|
@moto.mock_s3
def test_bundle_push_delocalize():
""" Test Bundle.push(delocalize)
Test if we can push individually, and see that the files actualize to s3 paths.
"""
<DeepExtract>
api.delete_context(TEST_CONTEXT)
api.context(context_name=TEST_CONTEXT)
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3', region_name='us-east-1')
s3_resource.create_bucket(Bucket=TEST_BUCKET)
objects = s3_client.list_objects(Bucket=TEST_BUCKET)
assert 'Contents' not in objects, 'Bucket should be empty'
if remote:
api.remote(TEST_CONTEXT, TEST_REMOTE, TEST_BUCKET_URL)
s3_client = s3_client
</DeepExtract>
bundles = {}
for i in range(3):
name = 'shark{}'.format(i)
<DeepExtract>
local_fp = tempfile.NamedTemporaryFile()
local_fp.write(b'an external local file in bundle')
local_fp.flush()
with api.Bundle(TEST_CONTEXT, name=name) as b:
f1 = b.get_file('file_1.txt')
f2 = b.get_file('file_2.txt')
f3 = os.path.join(b.get_directory('vince/klartho'), 'file_3.txt')
with open(f1, mode='w') as f:
f.write('This is our first file! {}'.format(name))
with open(f2, mode='w') as f:
f.write('This is our second file! {}'.format(name))
with open(f3, mode='w') as f:
f.write('This is our third file! {}'.format(name))
b.add_data([local_fp.name, f1, f2, f3])
hashes = {'f{}'.format(i): md5_file(f) for (i, f) in enumerate([local_fp.name, f1, f2, f3])}
b.add_tags(hashes)
local_fp.close()
saved_uuid = b.uuid
b = api.get(TEST_CONTEXT, None, uuid=saved_uuid)
b.commit()
for (i, f) in enumerate(b.data):
assert md5_file(f) == hashes['f{}'.format(i)]
bundles[name] = b
</DeepExtract>
bundles[name].push(delocalize=True)
objects = s3_client.list_objects(Bucket=TEST_BUCKET)
assert 'Contents' in objects, 'Bucket should not be empty'
assert len(objects['Contents']) > 0, 'Bucket should not be empty'
for b in bundles.values():
for (i, f) in enumerate(b.data):
assert f.startswith('s3://')
api.rm(TEST_CONTEXT, rm_all=True)
api.pull(TEST_CONTEXT, localize=True)
found_bundles = {b.name: b for b in api.search(TEST_CONTEXT)}
for (n, b) in found_bundles.items():
for (i, f) in enumerate(b.data):
assert md5_file(f) == b.tags['f{}'.format(i)]
api.delete_context(TEST_CONTEXT)
|
@moto.mock_s3
def test_bundle_push_delocalize():
""" Test Bundle.push(delocalize)
Test if we can push individually, and see that the files actualize to s3 paths.
"""
api.delete_context(TEST_CONTEXT)
api.context(context_name=TEST_CONTEXT)
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3', region_name='us-east-1')
s3_resource.create_bucket(Bucket=TEST_BUCKET)
objects = s3_client.list_objects(Bucket=TEST_BUCKET)
assert 'Contents' not in objects, 'Bucket should be empty'
if remote:
api.remote(TEST_CONTEXT, TEST_REMOTE, TEST_BUCKET_URL)
s3_client = s3_client
bundles = {}
for i in range(3):
name = 'shark{}'.format(i)
local_fp = tempfile.NamedTemporaryFile()
local_fp.write(b'an external local file in bundle')
local_fp.flush()
with api.Bundle(TEST_CONTEXT, name=name) as b:
f1 = b.get_file('file_1.txt')
f2 = b.get_file('file_2.txt')
f3 = os.path.join(b.get_directory('vince/klartho'), 'file_3.txt')
with open(f1, mode='w') as f:
f.write('This is our first file! {}'.format(name))
with open(f2, mode='w') as f:
f.write('This is our second file! {}'.format(name))
with open(f3, mode='w') as f:
f.write('This is our third file! {}'.format(name))
b.add_data([local_fp.name, f1, f2, f3])
hashes = {'f{}'.format(i): md5_file(f) for (i, f) in enumerate([local_fp.name, f1, f2, f3])}
b.add_tags(hashes)
local_fp.close()
saved_uuid = b.uuid
b = api.get(TEST_CONTEXT, None, uuid=saved_uuid)
b.commit()
for (i, f) in enumerate(b.data):
assert md5_file(f) == hashes['f{}'.format(i)]
bundles[name] = b
bundles[name].push(delocalize=True)
objects = s3_client.list_objects(Bucket=TEST_BUCKET)
assert 'Contents' in objects, 'Bucket should not be empty'
assert len(objects['Contents']) > 0, 'Bucket should not be empty'
for b in bundles.values():
for (i, f) in enumerate(b.data):
assert f.startswith('s3://')
api.rm(TEST_CONTEXT, rm_all=True)
api.pull(TEST_CONTEXT, localize=True)
found_bundles = {b.name: b for b in api.search(TEST_CONTEXT)}
for (n, b) in found_bundles.items():
for (i, f) in enumerate(b.data):
assert md5_file(f) == b.tags['f{}'.format(i)]
api.delete_context(TEST_CONTEXT)
|
disdat
|
positive
|
def discard(self, value):
"""Remove `value` from sorted-key list if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.discard(1)
>>> skl.discard(0)
>>> skl == [5, 4, 3, 2]
True
:param value: `value` to discard from sorted-key list
"""
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
<DeepExtract>
_maxes = self._maxes
if not _maxes:
pos = 0
pos = bisect_left(_maxes, _maxes)
if pos == len(_maxes):
pos = self._len
idx = bisect_left(self._lists[pos], _maxes)
pos = self._loc(pos, idx)
</DeepExtract>
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
<DeepExtract>
_maxes = self._maxes
if not _maxes:
idx = 0
pos = bisect_left(_maxes, _keys[pos])
if pos == len(_maxes):
idx = self._len
idx = bisect_left(self._lists[pos], _keys[pos])
idx = self._loc(pos, idx)
</DeepExtract>
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
<DeepExtract>
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > self._load >> 1:
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = child - 1 >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
</DeepExtract>
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
|
def discard(self, value):
"""Remove `value` from sorted-key list if it is a member.
If `value` is not a member, do nothing.
Runtime complexity: `O(log(n))` -- approximate.
>>> from operator import neg
>>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
>>> skl.discard(1)
>>> skl.discard(0)
>>> skl == [5, 4, 3, 2]
True
:param value: `value` to discard from sorted-key list
"""
_maxes = self._maxes
if not _maxes:
return
key = self._key(value)
_maxes = self._maxes
if not _maxes:
pos = 0
pos = bisect_left(_maxes, _maxes)
if pos == len(_maxes):
pos = self._len
idx = bisect_left(self._lists[pos], _maxes)
pos = self._loc(pos, idx)
if pos == len(_maxes):
return
_lists = self._lists
_keys = self._keys
_maxes = self._maxes
if not _maxes:
idx = 0
pos = bisect_left(_maxes, _keys[pos])
if pos == len(_maxes):
idx = self._len
idx = bisect_left(self._lists[pos], _keys[pos])
idx = self._loc(pos, idx)
len_keys = len(_keys)
len_sublist = len(_keys[pos])
while True:
if _keys[pos][idx] != key:
return
if _lists[pos][idx] == value:
_lists = self._lists
_maxes = self._maxes
_index = self._index
_lists_pos = _lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > self._load >> 1:
_maxes[pos] = _lists_pos[-1]
if _index:
child = self._offset + pos
while child > 0:
_index[child] -= 1
child = child - 1 >> 1
_index[0] -= 1
elif len(_lists) > 1:
if not pos:
pos += 1
prev = pos - 1
_lists[prev].extend(_lists[pos])
_maxes[prev] = _lists[prev][-1]
del _lists[pos]
del _maxes[pos]
del _index[:]
self._expand(prev)
elif len_lists_pos:
_maxes[pos] = _lists_pos[-1]
else:
del _lists[pos]
del _maxes[pos]
del _index[:]
return
idx += 1
if idx == len_sublist:
pos += 1
if pos == len_keys:
return
len_sublist = len(_keys[pos])
idx = 0
|
Clair3
|
positive
|
def __getitem__(self, index):
img_id = self.ids[index]
path = img_id['file_name']
iid = img_id['image_id']
img = Image.open(os.path.join(self.detail.img_folder, path)).convert('RGB')
if self.mode == 'test':
if self.transform is not None:
img = self.transform(img)
return (img, os.path.basename(path))
mask = self.masks[iid]
if self.mode == 'train':
(img, mask) = self._sync_transform(img, mask)
elif self.mode == 'val':
(img, mask) = self._val_sync_transform(img, mask)
else:
assert self.mode == 'testval'
<DeepExtract>
target = np.array(mask).astype('int32') - 1
mask = torch.from_numpy(target).long()
</DeepExtract>
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
mask = self.target_transform(mask)
return (img, mask)
|
def __getitem__(self, index):
img_id = self.ids[index]
path = img_id['file_name']
iid = img_id['image_id']
img = Image.open(os.path.join(self.detail.img_folder, path)).convert('RGB')
if self.mode == 'test':
if self.transform is not None:
img = self.transform(img)
return (img, os.path.basename(path))
mask = self.masks[iid]
if self.mode == 'train':
(img, mask) = self._sync_transform(img, mask)
elif self.mode == 'val':
(img, mask) = self._val_sync_transform(img, mask)
else:
assert self.mode == 'testval'
target = np.array(mask).astype('int32') - 1
mask = torch.from_numpy(target).long()
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
mask = self.target_transform(mask)
return (img, mask)
|
CariFaceParsing
|
positive
|
def _score_round(self, attempt: str) -> int:
"""Extract words, score and add to correct and incorrect lists."""
<DeepExtract>
words = [x for x in re.split('[^a-z]', attempt.lower()) if len(x) > 0]
words = words
</DeepExtract>
for word in words:
<DeepExtract>
if word in self.word_list:
score = _valid_scorer(word)
else:
score = 0
</DeepExtract>
if score > 0:
self.score += score
self.correct_words.append(word)
else:
self.incorrect_words.append(word)
|
def _score_round(self, attempt: str) -> int:
"""Extract words, score and add to correct and incorrect lists."""
words = [x for x in re.split('[^a-z]', attempt.lower()) if len(x) > 0]
words = words
for word in words:
if word in self.word_list:
score = _valid_scorer(word)
else:
score = 0
if score > 0:
self.score += score
self.correct_words.append(word)
else:
self.incorrect_words.append(word)
|
BIG-bench
|
positive
|
def _worker_manager_loop(in_queue, out_queue, done_event, pin_memory, device_id):
if pin_memory:
torch.cuda.set_device(device_id)
while True:
try:
r = in_queue.get()
except Exception:
if done_event.is_set():
return
raise
if r is None:
break
if isinstance(r[1], ExceptionWrapper):
out_queue.put(r)
continue
(idx, batch) = r
try:
if pin_memory:
<DeepExtract>
if torch.is_tensor(batch):
batch = batch.pin_memory()
elif isinstance(batch, string_classes):
batch = batch
elif isinstance(batch, collections.Mapping):
batch = {k: pin_memory_batch(sample) for (k, sample) in batch.items()}
elif isinstance(batch, collections.Sequence):
batch = [pin_memory_batch(sample) for sample in batch]
else:
batch = batch
</DeepExtract>
except Exception:
out_queue.put((idx, ExceptionWrapper(sys.exc_info())))
else:
out_queue.put((idx, batch))
|
def _worker_manager_loop(in_queue, out_queue, done_event, pin_memory, device_id):
if pin_memory:
torch.cuda.set_device(device_id)
while True:
try:
r = in_queue.get()
except Exception:
if done_event.is_set():
return
raise
if r is None:
break
if isinstance(r[1], ExceptionWrapper):
out_queue.put(r)
continue
(idx, batch) = r
try:
if pin_memory:
if torch.is_tensor(batch):
batch = batch.pin_memory()
elif isinstance(batch, string_classes):
batch = batch
elif isinstance(batch, collections.Mapping):
batch = {k: pin_memory_batch(sample) for (k, sample) in batch.items()}
elif isinstance(batch, collections.Sequence):
batch = [pin_memory_batch(sample) for sample in batch]
else:
batch = batch
except Exception:
out_queue.put((idx, ExceptionWrapper(sys.exc_info())))
else:
out_queue.put((idx, batch))
|
EnlightenGAN
|
positive
|
@filter_hook
def get_response(self):
<DeepExtract>
add = self.org_obj is None
change = self.org_obj is not None
new_context = {'form': self.form_obj, 'original': self.org_obj, 'show_delete': self.org_obj is not None, 'add': add, 'change': change, 'errors': self.get_error_list(), 'has_add_permission': self.has_add_permission(), 'has_view_permission': self.has_view_permission(), 'has_change_permission': self.has_change_permission(self.org_obj), 'has_delete_permission': self.has_delete_permission(self.org_obj), 'has_file_field': True, 'has_absolute_url': hasattr(self.model, 'get_absolute_url'), 'form_url': '', 'content_type_id': ContentType.objects.get_for_model(self.model).id, 'save_as': self.save_as, 'save_on_top': self.save_on_top}
new_context.update({'onclick_attrib': '', 'show_delete_link': new_context['has_delete_permission'] and (change or new_context['show_delete']), 'show_save_as_new': change and self.save_as, 'show_save_and_add_another': new_context['has_add_permission'] and (not self.save_as or add), 'show_save_and_continue': new_context['has_change_permission'], 'show_save': True})
if self.org_obj and new_context['show_delete_link']:
new_context['delete_url'] = self.model_admin_url('delete', self.org_obj.pk)
context = super(ModelFormAdminView, self).get_context()
context.update(new_context)
context = context
</DeepExtract>
context.update(self.kwargs or {})
return TemplateResponse(self.request, self.add_form_template or self.get_template_list('views/model_form.html'), context)
|
@filter_hook
def get_response(self):
add = self.org_obj is None
change = self.org_obj is not None
new_context = {'form': self.form_obj, 'original': self.org_obj, 'show_delete': self.org_obj is not None, 'add': add, 'change': change, 'errors': self.get_error_list(), 'has_add_permission': self.has_add_permission(), 'has_view_permission': self.has_view_permission(), 'has_change_permission': self.has_change_permission(self.org_obj), 'has_delete_permission': self.has_delete_permission(self.org_obj), 'has_file_field': True, 'has_absolute_url': hasattr(self.model, 'get_absolute_url'), 'form_url': '', 'content_type_id': ContentType.objects.get_for_model(self.model).id, 'save_as': self.save_as, 'save_on_top': self.save_on_top}
new_context.update({'onclick_attrib': '', 'show_delete_link': new_context['has_delete_permission'] and (change or new_context['show_delete']), 'show_save_as_new': change and self.save_as, 'show_save_and_add_another': new_context['has_add_permission'] and (not self.save_as or add), 'show_save_and_continue': new_context['has_change_permission'], 'show_save': True})
if self.org_obj and new_context['show_delete_link']:
new_context['delete_url'] = self.model_admin_url('delete', self.org_obj.pk)
context = super(ModelFormAdminView, self).get_context()
context.update(new_context)
context = context
context.update(self.kwargs or {})
return TemplateResponse(self.request, self.add_form_template or self.get_template_list('views/model_form.html'), context)
|
book
|
positive
|
def convert_annots_freq(spath, sfreq, dpath, dfreq):
"""
Converts the frequency of an annotations file.
Parameters
----------
spath:
Path of the input annotations file.
sfreq:
Frequency in Hz used in the input annotations timing.
dpath:
Path where the new annotations will be stored.
dfreq:
Frequency in Hz used in the output annotations timing.
"""
<DeepExtract>
result = []
f = open(spath, 'rb')
num = 0
chan = 0
displ = 0
while True:
bann = f.read(2)
if not bann:
break
(b0, b1) = struct.unpack('bb', bann)
A = (b1 & 255) >> 2
I = (b1 & 3) << 8 | 255 & b0
if A == SKIP_CODE and I == 0:
(b0, b1, b2, b3) = struct.unpack('4b', f.read(4))
displ = b1 << 24 | (b0 & 255) << 16 | (b3 & 255) << 8 | b2 & 255
elif A is NUM_CODE:
num = I
result[-1].num = num
elif A is SUB_CODE:
result[-1].subtype = I
elif A is CHN_CODE:
chan = I
result[-1].chan = chan
elif A is AUX_CODE:
result[-1].aux = f.read(I)
if I % 2 != 0:
f.read(1)
elif A == I == 0:
break
else:
result.append(MITAnnotation(code=A, time=I + displ, chan=chan, num=num))
displ = 0
f.close()
abs_time = 0
for annot in result:
abs_time += annot.time
annot.time = max(0, abs_time)
annots = result
</DeepExtract>
for ann in annots:
ann.time = int(ann.time / float(sfreq) * float(dfreq))
<DeepExtract>
annots = sorted(annots)
f = open(dpath, 'wb')
prev_time = 0
prev_num = 0
prev_chn = 0
for anot in annots:
rel_time = anot.time - prev_time
if rel_time > SKIP_TIME:
f.write(struct.pack('>H', SKIP_CODE << 2))
f.write(struct.pack('<H', rel_time >> 16))
f.write(struct.pack('<H', rel_time & 65535))
rel_time = 0
f.write(struct.pack('<H', anot.code << 10 | rel_time))
prev_time = anot.time
if anot.num != prev_num:
f.write(struct.pack('<H', NUM_CODE << 10 | anot.num))
prev_num = anot.num
if anot.subtype != 0:
f.write(struct.pack('<H', SUB_CODE << 10 | anot.subtype))
if anot.chan != prev_chn:
f.write(struct.pack('<H', CHN_CODE << 10 | anot.chan))
prev_chn = anot.chan
if anot.aux != None:
f.write(struct.pack('<H', AUX_CODE << 10 | len(anot.aux)))
aux = anot.aux if isinstance(anot.aux, bytes) else bytes(anot.aux, encoding='utf-8')
f.write(aux)
if len(anot.aux) % 2 != 0:
f.write(struct.pack('<b', 0))
f.write(struct.pack('<h', 0))
f.close()
</DeepExtract>
|
def convert_annots_freq(spath, sfreq, dpath, dfreq):
"""
Converts the frequency of an annotations file.
Parameters
----------
spath:
Path of the input annotations file.
sfreq:
Frequency in Hz used in the input annotations timing.
dpath:
Path where the new annotations will be stored.
dfreq:
Frequency in Hz used in the output annotations timing.
"""
result = []
f = open(spath, 'rb')
num = 0
chan = 0
displ = 0
while True:
bann = f.read(2)
if not bann:
break
(b0, b1) = struct.unpack('bb', bann)
A = (b1 & 255) >> 2
I = (b1 & 3) << 8 | 255 & b0
if A == SKIP_CODE and I == 0:
(b0, b1, b2, b3) = struct.unpack('4b', f.read(4))
displ = b1 << 24 | (b0 & 255) << 16 | (b3 & 255) << 8 | b2 & 255
elif A is NUM_CODE:
num = I
result[-1].num = num
elif A is SUB_CODE:
result[-1].subtype = I
elif A is CHN_CODE:
chan = I
result[-1].chan = chan
elif A is AUX_CODE:
result[-1].aux = f.read(I)
if I % 2 != 0:
f.read(1)
elif A == I == 0:
break
else:
result.append(MITAnnotation(code=A, time=I + displ, chan=chan, num=num))
displ = 0
f.close()
abs_time = 0
for annot in result:
abs_time += annot.time
annot.time = max(0, abs_time)
annots = result
for ann in annots:
ann.time = int(ann.time / float(sfreq) * float(dfreq))
annots = sorted(annots)
f = open(dpath, 'wb')
prev_time = 0
prev_num = 0
prev_chn = 0
for anot in annots:
rel_time = anot.time - prev_time
if rel_time > SKIP_TIME:
f.write(struct.pack('>H', SKIP_CODE << 2))
f.write(struct.pack('<H', rel_time >> 16))
f.write(struct.pack('<H', rel_time & 65535))
rel_time = 0
f.write(struct.pack('<H', anot.code << 10 | rel_time))
prev_time = anot.time
if anot.num != prev_num:
f.write(struct.pack('<H', NUM_CODE << 10 | anot.num))
prev_num = anot.num
if anot.subtype != 0:
f.write(struct.pack('<H', SUB_CODE << 10 | anot.subtype))
if anot.chan != prev_chn:
f.write(struct.pack('<H', CHN_CODE << 10 | anot.chan))
prev_chn = anot.chan
if anot.aux != None:
f.write(struct.pack('<H', AUX_CODE << 10 | len(anot.aux)))
aux = anot.aux if isinstance(anot.aux, bytes) else bytes(anot.aux, encoding='utf-8')
f.write(aux)
if len(anot.aux) % 2 != 0:
f.write(struct.pack('<b', 0))
f.write(struct.pack('<h', 0))
f.close()
</DeepExtract>
|
construe
|
positive
|
def test_call_closed_rpc_cancelled(self):
<DeepExtract>
async def create():
port = find_unused_port()
server = await aiozmq.rpc.serve_rpc(MyHandler(self.loop), bind='tcp://127.0.0.1:{}'.format(port), loop=self.loop if use_loop else None, log_exceptions=log_exceptions, exclude_log_exceptions=exclude_log_exceptions)
client = await aiozmq.rpc.connect_rpc(connect='tcp://127.0.0.1:{}'.format(port), loop=self.loop if use_loop else None, error_table=error_table, timeout=timeout)
(client, server) = (client, server)
(self.client, self.server) = self.loop.run_until_complete(create())
(client, server) = (self.client, self.server)
</DeepExtract>
async def communicate():
server.close()
waiter = client.call.func()
server.close()
await server.wait_closed()
client.close()
await client.wait_closed()
with self.assertRaises(asyncio.CancelledError):
await waiter
self.loop.run_until_complete(communicate())
|
def test_call_closed_rpc_cancelled(self):
async def create():
port = find_unused_port()
server = await aiozmq.rpc.serve_rpc(MyHandler(self.loop), bind='tcp://127.0.0.1:{}'.format(port), loop=self.loop if use_loop else None, log_exceptions=log_exceptions, exclude_log_exceptions=exclude_log_exceptions)
client = await aiozmq.rpc.connect_rpc(connect='tcp://127.0.0.1:{}'.format(port), loop=self.loop if use_loop else None, error_table=error_table, timeout=timeout)
(client, server) = (client, server)
(self.client, self.server) = self.loop.run_until_complete(create())
(client, server) = (self.client, self.server)
async def communicate():
server.close()
waiter = client.call.func()
server.close()
await server.wait_closed()
client.close()
await client.wait_closed()
with self.assertRaises(asyncio.CancelledError):
await waiter
self.loop.run_until_complete(communicate())
|
aiozmq
|
positive
|
def load_detector_legacy(filepath: Union[str, os.PathLike], suffix: str, **kwargs) -> Detector:
"""
Legacy function to load outlier, drift or adversarial detectors stored dill or pickle files.
Warning
-------
This function will be removed in a future version.
Parameters
----------
filepath
Load directory.
suffix
File suffix for meta and state files. Either `'.dill'` or `'.pickle'`.
Returns
-------
Loaded outlier or adversarial detector object.
"""
warnings.warn('Loading of meta.dill and meta.pickle files will be removed in a future version.', DeprecationWarning)
if kwargs:
k = list(kwargs.keys())
else:
k = []
filepath = Path(filepath)
if not filepath.is_dir():
raise FileNotFoundError(f'{filepath} does not exist.')
meta_dict = dill.load(open(filepath.joinpath('meta' + suffix), 'rb'))
try:
if meta_dict['version'] != __version__:
warnings.warn(f"Trying to load detector from version {meta_dict['version']} when using version {__version__}. This may lead to breaking code or invalid results.")
except KeyError:
warnings.warn('Trying to load detector from an older version.This may lead to breaking code or invalid results.')
if 'backend' in list(meta_dict.keys()) and meta_dict['backend'] == Framework.PYTORCH:
raise NotImplementedError('Detectors with PyTorch backend are not yet supported.')
detector_name = meta_dict['name']
if detector_name not in [detector for detector in VALID_DETECTORS]:
raise NotImplementedError(f'{detector_name} is not supported by `load_detector`.')
state_dict = dill.load(open(filepath.joinpath(detector_name + suffix), 'rb'))
if 'kwargs' in state_dict and 'other' in state_dict:
if 'x_ref_preprocessed' not in state_dict['kwargs']:
state_dict['kwargs']['x_ref_preprocessed'] = True
state_dict['kwargs']['preprocess_x_ref'] = state_dict['other']['preprocess_x_ref']
model_dir = filepath.joinpath('model')
detector: Optional[Detector] = None
if detector_name == 'OutlierAE':
<DeepExtract>
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder or ae found in {}.'.format(model_dir))
ae = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
ae = AE(encoder_net, decoder_net)
ae.load_weights(model_dir.joinpath('ae.ckpt'))
ae = ae
</DeepExtract>
<DeepExtract>
od = OutlierAE(threshold=state_dict['threshold'], ae=ae)
detector = od
</DeepExtract>
elif detector_name == 'OutlierVAE':
<DeepExtract>
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder or vae found in {}.'.format(model_dir))
vae = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
vae = VAE(encoder_net, decoder_net, state_dict['latent_dim'], beta=state_dict['beta'])
vae.load_weights(model_dir.joinpath('vae.ckpt'))
vae = vae
</DeepExtract>
<DeepExtract>
od = OutlierVAE(threshold=state_dict['threshold'], score_type=state_dict['score_type'], vae=vae, samples=state_dict['samples'])
detector = od
</DeepExtract>
elif detector_name == 'Mahalanobis':
<DeepExtract>
od = Mahalanobis(threshold=state_dict['threshold'], n_components=state_dict['n_components'], std_clip=state_dict['std_clip'], start_clip=state_dict['start_clip'], max_n=state_dict['max_n'], cat_vars=state_dict['cat_vars'], ohe=state_dict['ohe'])
od.d_abs = state_dict['d_abs']
od.clip = state_dict['clip']
od.mean = state_dict['mean']
od.C = state_dict['C']
od.n = state_dict['n']
detector = od
</DeepExtract>
elif detector_name == 'IForest':
<DeepExtract>
od = IForest(threshold=state_dict['threshold'])
od.isolationforest = state_dict['isolationforest']
detector = od
</DeepExtract>
elif detector_name == 'OutlierAEGMM':
<DeepExtract>
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder, gmm density net or aegmm found in {}.'.format(model_dir))
aegmm = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
gmm_density_net = tf.keras.models.load_model(model_dir.joinpath('gmm_density_net.h5'))
aegmm = AEGMM(encoder_net, decoder_net, gmm_density_net, state_dict['n_gmm'], state_dict['recon_features'])
aegmm.load_weights(model_dir.joinpath('aegmm.ckpt'))
aegmm = aegmm
</DeepExtract>
<DeepExtract>
od = OutlierAEGMM(threshold=state_dict['threshold'], aegmm=aegmm)
od.phi = state_dict['phi']
od.mu = state_dict['mu']
od.cov = state_dict['cov']
od.L = state_dict['L']
od.log_det_cov = state_dict['log_det_cov']
if not all((tf.is_tensor(_) for _ in [od.phi, od.mu, od.cov, od.L, od.log_det_cov])):
logger.warning('Loaded AEGMM detector has not been fit.')
detector = od
</DeepExtract>
elif detector_name == 'OutlierVAEGMM':
<DeepExtract>
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder, gmm density net or vaegmm found in {}.'.format(model_dir))
vaegmm = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
gmm_density_net = tf.keras.models.load_model(model_dir.joinpath('gmm_density_net.h5'))
vaegmm = VAEGMM(encoder_net, decoder_net, gmm_density_net, state_dict['n_gmm'], state_dict['latent_dim'], state_dict['recon_features'], state_dict['beta'])
vaegmm.load_weights(model_dir.joinpath('vaegmm.ckpt'))
vaegmm = vaegmm
</DeepExtract>
<DeepExtract>
od = OutlierVAEGMM(threshold=state_dict['threshold'], vaegmm=vaegmm, samples=state_dict['samples'])
od.phi = state_dict['phi']
od.mu = state_dict['mu']
od.cov = state_dict['cov']
od.L = state_dict['L']
od.log_det_cov = state_dict['log_det_cov']
if not all((tf.is_tensor(_) for _ in [od.phi, od.mu, od.cov, od.L, od.log_det_cov])):
logger.warning('Loaded VAEGMM detector has not been fit.')
detector = od
</DeepExtract>
elif detector_name == 'AdversarialAE':
<DeepExtract>
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder or ae found in {}.'.format(model_dir))
ae = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
ae = AE(encoder_net, decoder_net)
ae.load_weights(model_dir.joinpath('ae.ckpt'))
ae = ae
</DeepExtract>
custom_objects = kwargs['custom_objects'] if 'custom_objects' in k else None
<DeepExtract>
model_dir = Path(model_dir)
model_name = filename + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
model = model
</DeepExtract>
<DeepExtract>
model_dir = Path(filepath).joinpath('model')
hidden_layer_kld = state_dict['hidden_layer_kld']
if not hidden_layer_kld:
model_hl = []
model_hl = []
for (i, (hidden_layer, output_dim)) in enumerate(hidden_layer_kld.items()):
m = DenseHidden(model, hidden_layer, output_dim)
m.load_weights(model_dir.joinpath('model_hl_' + str(i) + '.ckpt'))
model_hl.append(m)
model_hl = model_hl
</DeepExtract>
<DeepExtract>
ad = AdversarialAE(threshold=state_dict['threshold'], ae=ae, model=model, model_hl=model_hl, w_model_hl=state_dict['w_model_hl'], temperature=state_dict['temperature'])
detector = ad
</DeepExtract>
elif detector_name == 'ModelDistillation':
<DeepExtract>
model_dir = Path(model_dir)
model_name = 'distilled_model' + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
md = model
</DeepExtract>
custom_objects = kwargs['custom_objects'] if 'custom_objects' in k else None
<DeepExtract>
model_dir = Path(model_dir)
model_name = filename + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
model = model
</DeepExtract>
<DeepExtract>
ad = ModelDistillation(threshold=state_dict['threshold'], distilled_model=md, model=model, temperature=state_dict['temperature'], loss_type=state_dict['loss_type'])
detector = ad
</DeepExtract>
elif detector_name == 'OutlierProphet':
<DeepExtract>
od = OutlierProphet(cap=state_dict['cap'])
od.model = state_dict['model']
detector = od
</DeepExtract>
elif detector_name == 'SpectralResidual':
<DeepExtract>
od = SpectralResidual(threshold=state_dict['threshold'], window_amp=state_dict['window_amp'], window_local=state_dict['window_local'], n_est_points=state_dict['n_est_points'], n_grad_points=state_dict['n_grad_points'])
detector = od
</DeepExtract>
elif detector_name == 'OutlierSeq2Seq':
<DeepExtract>
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No seq2seq or threshold estimation net found in {}.'.format(model_dir))
seq2seq = None
threshold_net = tf.keras.models.load_model(model_dir.joinpath('threshold_net.h5'), compile=False)
latent_dim = state_dict['latent_dim']
n_features = state_dict['shape'][-1]
encoder_net = EncoderLSTM(latent_dim)
decoder_net = DecoderLSTM(latent_dim, n_features, state_dict['output_activation'])
seq2seq = Seq2Seq(encoder_net, decoder_net, threshold_net, n_features, beta=state_dict['beta'])
seq2seq.load_weights(model_dir.joinpath('seq2seq.ckpt'))
seq2seq = seq2seq
</DeepExtract>
<DeepExtract>
(seq_len, n_features) = state_dict['shape'][1:]
od = OutlierSeq2Seq(n_features, seq_len, threshold=state_dict['threshold'], seq2seq=seq2seq, latent_dim=state_dict['latent_dim'], output_activation=state_dict['output_activation'])
detector = od
</DeepExtract>
elif detector_name in ['ChiSquareDrift', 'ClassifierDriftTF', 'KSDrift', 'MMDDriftTF', 'TabularDrift']:
(emb, tokenizer) = (None, None)
if state_dict['other']['load_text_embedding']:
<DeepExtract>
model_dir = Path(filepath).joinpath(load_dir)
tokenizer = AutoTokenizer.from_pretrained(str(model_dir.resolve()))
args = dill.load(open(model_dir.joinpath('embedding.dill'), 'rb'))
emb = TransformerEmbedding(str(model_dir.resolve()), embedding_type=args['embedding_type'], layers=args['layers'])
(emb, tokenizer) = (emb, tokenizer)
</DeepExtract>
try:
<DeepExtract>
model_dir = Path(model_dir)
model_name = 'encoder' + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
model = model
</DeepExtract>
except FileNotFoundError:
logger.warning('No model found in {}, setting `model` to `None`.'.format(model_dir))
model = None
if detector_name == 'KSDrift':
load_fn = init_cd_ksdrift
elif detector_name == 'MMDDriftTF':
load_fn = init_cd_mmddrift
elif detector_name == 'ChiSquareDrift':
load_fn = init_cd_chisquaredrift
elif detector_name == 'TabularDrift':
load_fn = init_cd_tabulardrift
elif detector_name == 'ClassifierDriftTF':
<DeepExtract>
model_dir = Path(model_dir)
model_name = 'clf_drift' + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
clf_drift = model
</DeepExtract>
load_fn = partial(init_cd_classifierdrift, clf_drift)
else:
raise NotImplementedError
detector = load_fn(state_dict, model, emb, tokenizer, **kwargs)
elif detector_name == 'LLR':
<DeepExtract>
model_dir = Path(filepath).joinpath('model')
h5files = [f.name for f in model_dir.glob('[!.]*.h5')]
if 'model_s.h5' in h5files and 'model_b.h5' in h5files:
(model_s, dist_s) = build_model(dist_s, input_shape, str(model_dir.joinpath('model_s.h5').resolve()))
(model_b, dist_b) = build_model(dist_b, input_shape, str(model_dir.joinpath('model_b.h5').resolve()))
models = (dist_s, dist_b, model_s, model_b)
else:
dist_s = tf.keras.models.load_model(model_dir.joinpath('model.h5'), compile=False)
if 'model_background.h5' in h5files:
dist_b = tf.keras.models.load_model(model_dir.joinpath('model_background.h5'), compile=False)
else:
dist_b = None
models = (dist_s, dist_b, None, None)
</DeepExtract>
<DeepExtract>
od = LLR(threshold=state_dict['threshold'], model=models[0], model_background=models[1], log_prob=state_dict['log_prob'], sequential=state_dict['sequential'])
if models[2] is not None and models[3] is not None:
od.model_s = models[2]
od.model_b = models[3]
detector = od
</DeepExtract>
else:
raise NotImplementedError
detector.meta = meta_dict
logger.info('Finished loading detector.')
return detector
|
def load_detector_legacy(filepath: Union[str, os.PathLike], suffix: str, **kwargs) -> Detector:
"""
Legacy function to load outlier, drift or adversarial detectors stored dill or pickle files.
Warning
-------
This function will be removed in a future version.
Parameters
----------
filepath
Load directory.
suffix
File suffix for meta and state files. Either `'.dill'` or `'.pickle'`.
Returns
-------
Loaded outlier or adversarial detector object.
"""
warnings.warn('Loading of meta.dill and meta.pickle files will be removed in a future version.', DeprecationWarning)
if kwargs:
k = list(kwargs.keys())
else:
k = []
filepath = Path(filepath)
if not filepath.is_dir():
raise FileNotFoundError(f'{filepath} does not exist.')
meta_dict = dill.load(open(filepath.joinpath('meta' + suffix), 'rb'))
try:
if meta_dict['version'] != __version__:
warnings.warn(f"Trying to load detector from version {meta_dict['version']} when using version {__version__}. This may lead to breaking code or invalid results.")
except KeyError:
warnings.warn('Trying to load detector from an older version.This may lead to breaking code or invalid results.')
if 'backend' in list(meta_dict.keys()) and meta_dict['backend'] == Framework.PYTORCH:
raise NotImplementedError('Detectors with PyTorch backend are not yet supported.')
detector_name = meta_dict['name']
if detector_name not in [detector for detector in VALID_DETECTORS]:
raise NotImplementedError(f'{detector_name} is not supported by `load_detector`.')
state_dict = dill.load(open(filepath.joinpath(detector_name + suffix), 'rb'))
if 'kwargs' in state_dict and 'other' in state_dict:
if 'x_ref_preprocessed' not in state_dict['kwargs']:
state_dict['kwargs']['x_ref_preprocessed'] = True
state_dict['kwargs']['preprocess_x_ref'] = state_dict['other']['preprocess_x_ref']
model_dir = filepath.joinpath('model')
detector: Optional[Detector] = None
if detector_name == 'OutlierAE':
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder or ae found in {}.'.format(model_dir))
ae = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
ae = AE(encoder_net, decoder_net)
ae.load_weights(model_dir.joinpath('ae.ckpt'))
ae = ae
od = OutlierAE(threshold=state_dict['threshold'], ae=ae)
detector = od
elif detector_name == 'OutlierVAE':
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder or vae found in {}.'.format(model_dir))
vae = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
vae = VAE(encoder_net, decoder_net, state_dict['latent_dim'], beta=state_dict['beta'])
vae.load_weights(model_dir.joinpath('vae.ckpt'))
vae = vae
od = OutlierVAE(threshold=state_dict['threshold'], score_type=state_dict['score_type'], vae=vae, samples=state_dict['samples'])
detector = od
elif detector_name == 'Mahalanobis':
od = Mahalanobis(threshold=state_dict['threshold'], n_components=state_dict['n_components'], std_clip=state_dict['std_clip'], start_clip=state_dict['start_clip'], max_n=state_dict['max_n'], cat_vars=state_dict['cat_vars'], ohe=state_dict['ohe'])
od.d_abs = state_dict['d_abs']
od.clip = state_dict['clip']
od.mean = state_dict['mean']
od.C = state_dict['C']
od.n = state_dict['n']
detector = od
elif detector_name == 'IForest':
od = IForest(threshold=state_dict['threshold'])
od.isolationforest = state_dict['isolationforest']
detector = od
elif detector_name == 'OutlierAEGMM':
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder, gmm density net or aegmm found in {}.'.format(model_dir))
aegmm = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
gmm_density_net = tf.keras.models.load_model(model_dir.joinpath('gmm_density_net.h5'))
aegmm = AEGMM(encoder_net, decoder_net, gmm_density_net, state_dict['n_gmm'], state_dict['recon_features'])
aegmm.load_weights(model_dir.joinpath('aegmm.ckpt'))
aegmm = aegmm
od = OutlierAEGMM(threshold=state_dict['threshold'], aegmm=aegmm)
od.phi = state_dict['phi']
od.mu = state_dict['mu']
od.cov = state_dict['cov']
od.L = state_dict['L']
od.log_det_cov = state_dict['log_det_cov']
if not all((tf.is_tensor(_) for _ in [od.phi, od.mu, od.cov, od.L, od.log_det_cov])):
logger.warning('Loaded AEGMM detector has not been fit.')
detector = od
elif detector_name == 'OutlierVAEGMM':
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder, gmm density net or vaegmm found in {}.'.format(model_dir))
vaegmm = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
gmm_density_net = tf.keras.models.load_model(model_dir.joinpath('gmm_density_net.h5'))
vaegmm = VAEGMM(encoder_net, decoder_net, gmm_density_net, state_dict['n_gmm'], state_dict['latent_dim'], state_dict['recon_features'], state_dict['beta'])
vaegmm.load_weights(model_dir.joinpath('vaegmm.ckpt'))
vaegmm = vaegmm
od = OutlierVAEGMM(threshold=state_dict['threshold'], vaegmm=vaegmm, samples=state_dict['samples'])
od.phi = state_dict['phi']
od.mu = state_dict['mu']
od.cov = state_dict['cov']
od.L = state_dict['L']
od.log_det_cov = state_dict['log_det_cov']
if not all((tf.is_tensor(_) for _ in [od.phi, od.mu, od.cov, od.L, od.log_det_cov])):
logger.warning('Loaded VAEGMM detector has not been fit.')
detector = od
elif detector_name == 'AdversarialAE':
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No encoder, decoder or ae found in {}.'.format(model_dir))
ae = None
encoder_net = tf.keras.models.load_model(model_dir.joinpath('encoder_net.h5'))
decoder_net = tf.keras.models.load_model(model_dir.joinpath('decoder_net.h5'))
ae = AE(encoder_net, decoder_net)
ae.load_weights(model_dir.joinpath('ae.ckpt'))
ae = ae
custom_objects = kwargs['custom_objects'] if 'custom_objects' in k else None
model_dir = Path(model_dir)
model_name = filename + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
model = model
model_dir = Path(filepath).joinpath('model')
hidden_layer_kld = state_dict['hidden_layer_kld']
if not hidden_layer_kld:
model_hl = []
model_hl = []
for (i, (hidden_layer, output_dim)) in enumerate(hidden_layer_kld.items()):
m = DenseHidden(model, hidden_layer, output_dim)
m.load_weights(model_dir.joinpath('model_hl_' + str(i) + '.ckpt'))
model_hl.append(m)
model_hl = model_hl
ad = AdversarialAE(threshold=state_dict['threshold'], ae=ae, model=model, model_hl=model_hl, w_model_hl=state_dict['w_model_hl'], temperature=state_dict['temperature'])
detector = ad
elif detector_name == 'ModelDistillation':
model_dir = Path(model_dir)
model_name = 'distilled_model' + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
md = model
custom_objects = kwargs['custom_objects'] if 'custom_objects' in k else None
model_dir = Path(model_dir)
model_name = filename + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
model = model
ad = ModelDistillation(threshold=state_dict['threshold'], distilled_model=md, model=model, temperature=state_dict['temperature'], loss_type=state_dict['loss_type'])
detector = ad
elif detector_name == 'OutlierProphet':
od = OutlierProphet(cap=state_dict['cap'])
od.model = state_dict['model']
detector = od
elif detector_name == 'SpectralResidual':
od = SpectralResidual(threshold=state_dict['threshold'], window_amp=state_dict['window_amp'], window_local=state_dict['window_local'], n_est_points=state_dict['n_est_points'], n_grad_points=state_dict['n_grad_points'])
detector = od
elif detector_name == 'OutlierSeq2Seq':
model_dir = Path(filepath).joinpath('model')
if not [f.name for f in model_dir.glob('[!.]*.h5')]:
logger.warning('No seq2seq or threshold estimation net found in {}.'.format(model_dir))
seq2seq = None
threshold_net = tf.keras.models.load_model(model_dir.joinpath('threshold_net.h5'), compile=False)
latent_dim = state_dict['latent_dim']
n_features = state_dict['shape'][-1]
encoder_net = EncoderLSTM(latent_dim)
decoder_net = DecoderLSTM(latent_dim, n_features, state_dict['output_activation'])
seq2seq = Seq2Seq(encoder_net, decoder_net, threshold_net, n_features, beta=state_dict['beta'])
seq2seq.load_weights(model_dir.joinpath('seq2seq.ckpt'))
seq2seq = seq2seq
(seq_len, n_features) = state_dict['shape'][1:]
od = OutlierSeq2Seq(n_features, seq_len, threshold=state_dict['threshold'], seq2seq=seq2seq, latent_dim=state_dict['latent_dim'], output_activation=state_dict['output_activation'])
detector = od
elif detector_name in ['ChiSquareDrift', 'ClassifierDriftTF', 'KSDrift', 'MMDDriftTF', 'TabularDrift']:
(emb, tokenizer) = (None, None)
if state_dict['other']['load_text_embedding']:
model_dir = Path(filepath).joinpath(load_dir)
tokenizer = AutoTokenizer.from_pretrained(str(model_dir.resolve()))
args = dill.load(open(model_dir.joinpath('embedding.dill'), 'rb'))
emb = TransformerEmbedding(str(model_dir.resolve()), embedding_type=args['embedding_type'], layers=args['layers'])
(emb, tokenizer) = (emb, tokenizer)
try:
model_dir = Path(model_dir)
model_name = 'encoder' + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
model = model
except FileNotFoundError:
logger.warning('No model found in {}, setting `model` to `None`.'.format(model_dir))
model = None
if detector_name == 'KSDrift':
load_fn = init_cd_ksdrift
elif detector_name == 'MMDDriftTF':
load_fn = init_cd_mmddrift
elif detector_name == 'ChiSquareDrift':
load_fn = init_cd_chisquaredrift
elif detector_name == 'TabularDrift':
load_fn = init_cd_tabulardrift
elif detector_name == 'ClassifierDriftTF':
model_dir = Path(model_dir)
model_name = 'clf_drift' + '.h5'
if model_name not in [f.name for f in model_dir.glob('[!.]*.h5')]:
raise FileNotFoundError(f'{model_name} not found in {model_dir.resolve()}.')
model = tf.keras.models.load_model(model_dir.joinpath(model_name), custom_objects=custom_objects)
if isinstance(layer, int):
model = HiddenOutput(model, layer=layer)
clf_drift = model
load_fn = partial(init_cd_classifierdrift, clf_drift)
else:
raise NotImplementedError
detector = load_fn(state_dict, model, emb, tokenizer, **kwargs)
elif detector_name == 'LLR':
model_dir = Path(filepath).joinpath('model')
h5files = [f.name for f in model_dir.glob('[!.]*.h5')]
if 'model_s.h5' in h5files and 'model_b.h5' in h5files:
(model_s, dist_s) = build_model(dist_s, input_shape, str(model_dir.joinpath('model_s.h5').resolve()))
(model_b, dist_b) = build_model(dist_b, input_shape, str(model_dir.joinpath('model_b.h5').resolve()))
models = (dist_s, dist_b, model_s, model_b)
else:
dist_s = tf.keras.models.load_model(model_dir.joinpath('model.h5'), compile=False)
if 'model_background.h5' in h5files:
dist_b = tf.keras.models.load_model(model_dir.joinpath('model_background.h5'), compile=False)
else:
dist_b = None
models = (dist_s, dist_b, None, None)
od = LLR(threshold=state_dict['threshold'], model=models[0], model_background=models[1], log_prob=state_dict['log_prob'], sequential=state_dict['sequential'])
if models[2] is not None and models[3] is not None:
od.model_s = models[2]
od.model_b = models[3]
detector = od
else:
raise NotImplementedError
detector.meta = meta_dict
logger.info('Finished loading detector.')
return detector
|
alibi-detect
|
positive
|
def test_save_and_load_tokenizer(self):
<DeepExtract>
raise NotImplementedError
</DeepExtract>
before_tokens = tokenizer.encode(u'He is very happy, UNwantéd,running')
with TemporaryDirectory() as tmpdirname:
tokenizer.save_pretrained(tmpdirname)
tokenizer = tokenizer.from_pretrained(tmpdirname)
after_tokens = tokenizer.encode(u'He is very happy, UNwantéd,running')
self.assertListEqual(before_tokens, after_tokens)
|
def test_save_and_load_tokenizer(self):
raise NotImplementedError
before_tokens = tokenizer.encode(u'He is very happy, UNwantéd,running')
with TemporaryDirectory() as tmpdirname:
tokenizer.save_pretrained(tmpdirname)
tokenizer = tokenizer.from_pretrained(tmpdirname)
after_tokens = tokenizer.encode(u'He is very happy, UNwantéd,running')
self.assertListEqual(before_tokens, after_tokens)
|
CCF-BDCI-Sentiment-Analysis-Baseline
|
positive
|
def get_network_interface(component_key, vm_config, subnet_name, public_ip_name, security_group_association_name, index):
<DeepExtract>
config = select_first(self.docs, lambda x: x.kind == 'infrastructure/network-interface')
if config is None:
config = load_schema_obj(schema_types.DEFAULT, 'azure', 'infrastructure/network-interface')
config['version'] = VERSION
network_interface = config
</DeepExtract>
network_interface.specification.name = resource_name(self.cluster_prefix, self.cluster_name, 'nic' + '-' + str(index), component_key)
network_interface.specification.use_network_security_groups = self.use_network_security_groups
network_interface.specification.security_group_association_name = security_group_association_name
network_interface.specification.ip_configuration_name = resource_name(self.cluster_prefix, self.cluster_name, 'ipconf' + '-' + str(index), component_key)
network_interface.specification.subnet_name = subnet_name
network_interface.specification.use_public_ip = self.cluster_model.specification.cloud.use_public_ips
network_interface.specification.public_ip_name = public_ip_name
network_interface.specification.enable_accelerated_networking = vm_config.specification.network_interface.enable_accelerated_networking
return network_interface
|
def get_network_interface(component_key, vm_config, subnet_name, public_ip_name, security_group_association_name, index):
config = select_first(self.docs, lambda x: x.kind == 'infrastructure/network-interface')
if config is None:
config = load_schema_obj(schema_types.DEFAULT, 'azure', 'infrastructure/network-interface')
config['version'] = VERSION
network_interface = config
network_interface.specification.name = resource_name(self.cluster_prefix, self.cluster_name, 'nic' + '-' + str(index), component_key)
network_interface.specification.use_network_security_groups = self.use_network_security_groups
network_interface.specification.security_group_association_name = security_group_association_name
network_interface.specification.ip_configuration_name = resource_name(self.cluster_prefix, self.cluster_name, 'ipconf' + '-' + str(index), component_key)
network_interface.specification.subnet_name = subnet_name
network_interface.specification.use_public_ip = self.cluster_model.specification.cloud.use_public_ips
network_interface.specification.public_ip_name = public_ip_name
network_interface.specification.enable_accelerated_networking = vm_config.specification.network_interface.enable_accelerated_networking
return network_interface
|
epiphany
|
positive
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.