body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def test_simple_grad(): 'Test the use of jax.grad' dev = qml.device('default.mixed', wires=2) @qml.qnode(dev, interface='jax', diff_method='parameter-shift') def circuit(weights): qml.RX(weights[0], wires=0) qml.RZ(weights[1], wires=1) return qml.expval((qml.PauliZ(0) @ qml.Paul...
8,963,306,386,412,158,000
Test the use of jax.grad
tests/tape/interfaces/test_qnode_jax.py
test_simple_grad
PritishSehzpaul/pennylane
python
def test_simple_grad(): dev = qml.device('default.mixed', wires=2) @qml.qnode(dev, interface='jax', diff_method='parameter-shift') def circuit(weights): qml.RX(weights[0], wires=0) qml.RZ(weights[1], wires=1) return qml.expval((qml.PauliZ(0) @ qml.PauliZ(1))) weights = jnp....
@pytest.mark.parametrize('diff_method', ['parameter-shift', 'finite-diff']) def test_differentiable_expand(diff_method): 'Test that operation and nested tapes expansion\n is differentiable' class U3(qml.U3): def expand(self): (theta, phi, lam) = self.data wires = self.wires ...
-6,303,920,968,199,098,000
Test that operation and nested tapes expansion is differentiable
tests/tape/interfaces/test_qnode_jax.py
test_differentiable_expand
PritishSehzpaul/pennylane
python
@pytest.mark.parametrize('diff_method', ['parameter-shift', 'finite-diff']) def test_differentiable_expand(diff_method): 'Test that operation and nested tapes expansion\n is differentiable' class U3(qml.U3): def expand(self): (theta, phi, lam) = self.data wires = self.wires ...
def qtransform(qnode, a, framework=jnp): 'Transforms every RY(y) gate in a circuit to RX(-a*cos(y))' def construct(self, args, kwargs): 'New quantum tape construct method, that performs\n the transform on the tape in a define-by-run manner' t_op = [] QNode.construct(self, args, k...
7,020,693,661,897,376,000
Transforms every RY(y) gate in a circuit to RX(-a*cos(y))
tests/tape/interfaces/test_qnode_jax.py
qtransform
PritishSehzpaul/pennylane
python
def qtransform(qnode, a, framework=jnp): def construct(self, args, kwargs): 'New quantum tape construct method, that performs\n the transform on the tape in a define-by-run manner' t_op = [] QNode.construct(self, args, kwargs) new_ops = [] for o in self.qtape.ope...
@pytest.mark.parametrize('dev_name,diff_method', [('default.mixed', 'finite-diff'), ('default.qubit.autograd', 'parameter-shift')]) def test_transform(dev_name, diff_method, monkeypatch, tol): 'Test an example transform' monkeypatch.setattr(qml.operation.Operation, 'do_check_domain', False) dev = qml.device...
3,371,618,771,618,339,000
Test an example transform
tests/tape/interfaces/test_qnode_jax.py
test_transform
PritishSehzpaul/pennylane
python
@pytest.mark.parametrize('dev_name,diff_method', [('default.mixed', 'finite-diff'), ('default.qubit.autograd', 'parameter-shift')]) def test_transform(dev_name, diff_method, monkeypatch, tol): monkeypatch.setattr(qml.operation.Operation, 'do_check_domain', False) dev = qml.device(dev_name, wires=1) @q...
def construct(self, args, kwargs): 'New quantum tape construct method, that performs\n the transform on the tape in a define-by-run manner' t_op = [] QNode.construct(self, args, kwargs) new_ops = [] for o in self.qtape.operations: if isinstance(o, qml.RY): t_op.append(qml....
5,238,125,990,119,009,000
New quantum tape construct method, that performs the transform on the tape in a define-by-run manner
tests/tape/interfaces/test_qnode_jax.py
construct
PritishSehzpaul/pennylane
python
def construct(self, args, kwargs): 'New quantum tape construct method, that performs\n the transform on the tape in a define-by-run manner' t_op = [] QNode.construct(self, args, kwargs) new_ops = [] for o in self.qtape.operations: if isinstance(o, qml.RY): t_op.append(qml....
def testDocxSetHeaderRequest(self): 'Test DocxSetHeaderRequest' pass
-4,734,426,132,462,906,000
Test DocxSetHeaderRequest
test/test_docx_set_header_request.py
testDocxSetHeaderRequest
Cloudmersive/Cloudmersive.APIClient.Python.Convert
python
def testDocxSetHeaderRequest(self): pass
@staticmethod def updateCouplings(connection): '\n The shape has changed, which means couplings might have to change, be added or removed.\n To be sure all couplings in this connection are deleted and then build up from scratch.\n ' 'Remove all old couplings.' for coupling in connection...
1,902,094,766,423,032,800
The shape has changed, which means couplings might have to change, be added or removed. To be sure all couplings in this connection are deleted and then build up from scratch.
Sea/adapter/connections/Connection.py
updateCouplings
FRidh/Sea
python
@staticmethod def updateCouplings(connection): '\n The shape has changed, which means couplings might have to change, be added or removed.\n To be sure all couplings in this connection are deleted and then build up from scratch.\n ' 'Remove all old couplings.' for coupling in connection...
@staticmethod def addCouplings(connection): '\n Add couplings to the :attr:`connection`.\n \n :param connection: an instance of :class:`Sea.adapter.baseclasses.Connection`\n ' for (comp_from, comp_to) in itertools.permutations(connection.Components, 2): coupling_sort = Connec...
-1,349,375,267,989,642,800
Add couplings to the :attr:`connection`. :param connection: an instance of :class:`Sea.adapter.baseclasses.Connection`
Sea/adapter/connections/Connection.py
addCouplings
FRidh/Sea
python
@staticmethod def addCouplings(connection): '\n Add couplings to the :attr:`connection`.\n \n :param connection: an instance of :class:`Sea.adapter.baseclasses.Connection`\n ' for (comp_from, comp_to) in itertools.permutations(connection.Components, 2): coupling_sort = Connec...
@staticmethod def determineCouplingType(connection_type, component_from, component_to): '\n Determine the type of coupling. Detects what type of connection the components have.\n Based on the type of connection and on the types of components a coupling is returned.\n \n :param component_...
-5,089,945,891,643,414,000
Determine the type of coupling. Detects what type of connection the components have. Based on the type of connection and on the types of components a coupling is returned. :param component_from: an instance of a child of :class:`Sea.adapter.baseclasses.Component` :param component_to: an instance of a child of :class:`...
Sea/adapter/connections/Connection.py
determineCouplingType
FRidh/Sea
python
@staticmethod def determineCouplingType(connection_type, component_from, component_to): '\n Determine the type of coupling. Detects what type of connection the components have.\n Based on the type of connection and on the types of components a coupling is returned.\n \n :param component_...
@staticmethod def makeCoupling(connection, subsystem_from, subsystem_to, sort): '\n Add a coupling to system.\n \n :param connection: an instance of :class:`Sea.adapter.baseclasses.Connection`\n :param component_from: an instance of a child of :class:`Sea.adapter.baseclasses.Component`\n...
-7,819,181,587,509,591,000
Add a coupling to system. :param connection: an instance of :class:`Sea.adapter.baseclasses.Connection` :param component_from: an instance of a child of :class:`Sea.adapter.baseclasses.Component` :param subsystem_from: string representing the type of subsystem :param component_to: an instance of a child of :class:`Sea...
Sea/adapter/connections/Connection.py
makeCoupling
FRidh/Sea
python
@staticmethod def makeCoupling(connection, subsystem_from, subsystem_to, sort): '\n Add a coupling to system.\n \n :param connection: an instance of :class:`Sea.adapter.baseclasses.Connection`\n :param component_from: an instance of a child of :class:`Sea.adapter.baseclasses.Component`\n...
@test_util.run_v1_only('b/120545219') def testControlFlowInitialization(self): 'Expects an error if an initializer is in a control-flow scope.' def cond(i, _): return (i < 10) def body(i, _): zero = array_ops.zeros([], dtype=dtypes.int32) v = variables.Variable(initial_value=zero) ...
-3,174,679,683,478,967,000
Expects an error if an initializer is in a control-flow scope.
tensorflow/python/kernel_tests/variables_test.py
testControlFlowInitialization
ArnovanHilten/tensorflow
python
@test_util.run_v1_only('b/120545219') def testControlFlowInitialization(self): def cond(i, _): return (i < 10) def body(i, _): zero = array_ops.zeros([], dtype=dtypes.int32) v = variables.Variable(initial_value=zero) return ((i + 1), v.read_value()) with self.assertRai...
def search(taxonKey=None, repatriated=None, kingdomKey=None, phylumKey=None, classKey=None, orderKey=None, familyKey=None, genusKey=None, subgenusKey=None, scientificName=None, country=None, publishingCountry=None, hasCoordinate=None, typeStatus=None, recordNumber=None, lastInterpreted=None, continent=None, geometry=No...
2,407,195,931,292,612,000
Search GBIF occurrences :param taxonKey: [int] A GBIF occurrence identifier :param q: [str] Simple search parameter. The value for this parameter can be a simple word or a phrase. :param spellCheck: [bool] If ``True`` ask GBIF to check your spelling of the value passed to the ``search`` parameter. IMPORTANT: This ...
pygbif/occurrences/search.py
search
livatras/pygbif
python
def search(taxonKey=None, repatriated=None, kingdomKey=None, phylumKey=None, classKey=None, orderKey=None, familyKey=None, genusKey=None, subgenusKey=None, scientificName=None, country=None, publishingCountry=None, hasCoordinate=None, typeStatus=None, recordNumber=None, lastInterpreted=None, continent=None, geometry=No...
def __init__(self, id=None, data=None): '\n DestinationIdSchema - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n ...
-1,036,892,525,717,189,400
DestinationIdSchema - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
rustici_software_cloud_v2/models/destination_id_schema.py
__init__
ryanhope2/scormcloud-api-v2-client-python
python
def __init__(self, id=None, data=None): '\n DestinationIdSchema - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n ...
@property def id(self): '\n Gets the id of this DestinationIdSchema.\n \n\n :return: The id of this DestinationIdSchema.\n :rtype: str\n ' return self._id
-4,756,714,808,268,342,000
Gets the id of this DestinationIdSchema. :return: The id of this DestinationIdSchema. :rtype: str
rustici_software_cloud_v2/models/destination_id_schema.py
id
ryanhope2/scormcloud-api-v2-client-python
python
@property def id(self): '\n Gets the id of this DestinationIdSchema.\n \n\n :return: The id of this DestinationIdSchema.\n :rtype: str\n ' return self._id
@id.setter def id(self, id): '\n Sets the id of this DestinationIdSchema.\n \n\n :param id: The id of this DestinationIdSchema.\n :type: str\n ' self._id = id
-2,075,493,263,701,627,100
Sets the id of this DestinationIdSchema. :param id: The id of this DestinationIdSchema. :type: str
rustici_software_cloud_v2/models/destination_id_schema.py
id
ryanhope2/scormcloud-api-v2-client-python
python
@id.setter def id(self, id): '\n Sets the id of this DestinationIdSchema.\n \n\n :param id: The id of this DestinationIdSchema.\n :type: str\n ' self._id = id
@property def data(self): '\n Gets the data of this DestinationIdSchema.\n\n :return: The data of this DestinationIdSchema.\n :rtype: DestinationSchema\n ' return self._data
6,491,617,717,676,747,000
Gets the data of this DestinationIdSchema. :return: The data of this DestinationIdSchema. :rtype: DestinationSchema
rustici_software_cloud_v2/models/destination_id_schema.py
data
ryanhope2/scormcloud-api-v2-client-python
python
@property def data(self): '\n Gets the data of this DestinationIdSchema.\n\n :return: The data of this DestinationIdSchema.\n :rtype: DestinationSchema\n ' return self._data
@data.setter def data(self, data): '\n Sets the data of this DestinationIdSchema.\n\n :param data: The data of this DestinationIdSchema.\n :type: DestinationSchema\n ' self._data = data
-7,656,567,686,224,259,000
Sets the data of this DestinationIdSchema. :param data: The data of this DestinationIdSchema. :type: DestinationSchema
rustici_software_cloud_v2/models/destination_id_schema.py
data
ryanhope2/scormcloud-api-v2-client-python
python
@data.setter def data(self, data): '\n Sets the data of this DestinationIdSchema.\n\n :param data: The data of this DestinationIdSchema.\n :type: DestinationSchema\n ' self._data = data
def to_dict(self): '\n Returns the model properties as a dict\n ' result = {} for (attr, _) in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), v...
2,191,974,537,531,847,000
Returns the model properties as a dict
rustici_software_cloud_v2/models/destination_id_schema.py
to_dict
ryanhope2/scormcloud-api-v2-client-python
python
def to_dict(self): '\n \n ' result = {} for (attr, _) in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to...
def to_str(self): '\n Returns the string representation of the model\n ' return pformat(self.to_dict())
-3,531,024,894,346,511,000
Returns the string representation of the model
rustici_software_cloud_v2/models/destination_id_schema.py
to_str
ryanhope2/scormcloud-api-v2-client-python
python
def to_str(self): '\n \n ' return pformat(self.to_dict())
def __repr__(self): '\n For `print` and `pprint`\n ' return self.to_str()
5,853,962,500,611,353,000
For `print` and `pprint`
rustici_software_cloud_v2/models/destination_id_schema.py
__repr__
ryanhope2/scormcloud-api-v2-client-python
python
def __repr__(self): '\n \n ' return self.to_str()
def __eq__(self, other): '\n Returns true if both objects are equal\n ' if (not isinstance(other, DestinationIdSchema)): return False return (self.__dict__ == other.__dict__)
5,572,630,834,681,360,000
Returns true if both objects are equal
rustici_software_cloud_v2/models/destination_id_schema.py
__eq__
ryanhope2/scormcloud-api-v2-client-python
python
def __eq__(self, other): '\n \n ' if (not isinstance(other, DestinationIdSchema)): return False return (self.__dict__ == other.__dict__)
def __ne__(self, other): '\n Returns true if both objects are not equal\n ' return (not (self == other))
3,600,423,175,817,510,400
Returns true if both objects are not equal
rustici_software_cloud_v2/models/destination_id_schema.py
__ne__
ryanhope2/scormcloud-api-v2-client-python
python
def __ne__(self, other): '\n \n ' return (not (self == other))
def load_data(data_dir): 'Load the train/val data.' data_transforms = {'train': transforms.Compose([transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]), 'val': transforms.Compose([transforms.Resize(256)...
2,688,968,184,329,373,000
Load the train/val data.
azure-ml-pipelines/pytorch/training-folder/pytorch_train.py
load_data
hudua/azureml
python
def load_data(data_dir): data_transforms = {'train': transforms.Compose([transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]), 'val': transforms.Compose([transforms.Resize(256), transforms.CenterCrop(22...
def train_model(model, criterion, optimizer, scheduler, num_epochs, data_dir): 'Train the model.' (dataloaders, dataset_sizes, class_names) = load_data(data_dir) device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) since = time.time() best_model_wts = copy.deepcopy(model.state_d...
-1,306,633,351,554,523,000
Train the model.
azure-ml-pipelines/pytorch/training-folder/pytorch_train.py
train_model
hudua/azureml
python
def train_model(model, criterion, optimizer, scheduler, num_epochs, data_dir): (dataloaders, dataset_sizes, class_names) = load_data(data_dir) device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_ac...
def fine_tune_model(num_epochs, data_dir, learning_rate, momentum): 'Load a pretrained model and reset the final fully connected layer.' run.log('lr', np.float(learning_rate)) run.log('momentum', np.float(momentum)) model_ft = models.resnet18(pretrained=True) num_ftrs = model_ft.fc.in_features m...
7,668,973,453,640,657,000
Load a pretrained model and reset the final fully connected layer.
azure-ml-pipelines/pytorch/training-folder/pytorch_train.py
fine_tune_model
hudua/azureml
python
def fine_tune_model(num_epochs, data_dir, learning_rate, momentum): run.log('lr', np.float(learning_rate)) run.log('momentum', np.float(momentum)) model_ft = models.resnet18(pretrained=True) num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs, 2) device = torch.device(('cuda...
def load_model(model_path: str) -> None: '\n 模型加载\n @param model_path: 模型文件夹路径\n @return:\n ' global kge_model, entity2id, id2entity, relation2id, all_true_triples, args args = DotMap(json.load(codecs.open(os.path.join(model_path, 'config.json'), 'r', encoding='utf-8'))) (entity2id, id2entit...
-1,381,956,851,112,199,000
模型加载 @param model_path: 模型文件夹路径 @return:
project/knowledge_graph_embedding/project_distmult_rotate_transe/service.py
load_model
Jianhan-Liu/solid_ai_waddle
python
def load_model(model_path: str) -> None: '\n 模型加载\n @param model_path: 模型文件夹路径\n @return:\n ' global kge_model, entity2id, id2entity, relation2id, all_true_triples, args args = DotMap(json.load(codecs.open(os.path.join(model_path, 'config.json'), 'r', encoding='utf-8'))) (entity2id, id2entit...
def inference(target_triple: str) -> Dict: "\n 推理函数\n @param target_triple: 目标需预测三元组:'头实体 关系 尾实体'\n @return: 头尾实体的10个预测结果\n " if (kge_model is None): return {'预测结果': '提醒:模型未加载'} try: target_triple = target_triple.split() head = entity2id[target_triple[0]] tail = e...
-4,453,249,678,169,298,400
推理函数 @param target_triple: 目标需预测三元组:'头实体 关系 尾实体' @return: 头尾实体的10个预测结果
project/knowledge_graph_embedding/project_distmult_rotate_transe/service.py
inference
Jianhan-Liu/solid_ai_waddle
python
def inference(target_triple: str) -> Dict: "\n 推理函数\n @param target_triple: 目标需预测三元组:'头实体 关系 尾实体'\n @return: 头尾实体的10个预测结果\n " if (kge_model is None): return {'预测结果': '提醒:模型未加载'} try: target_triple = target_triple.split() head = entity2id[target_triple[0]] tail = e...
def _looks_like_asgi3(app): '\n Try to figure out if an application object supports ASGI3.\n\n This is how uvicorn figures out the application version as well.\n ' if inspect.isclass(app): return hasattr(app, '__await__') elif inspect.isfunction(app): return asyncio.iscoroutinefunct...
-1,719,280,184,835,323,600
Try to figure out if an application object supports ASGI3. This is how uvicorn figures out the application version as well.
sentry_sdk/integrations/asgi.py
_looks_like_asgi3
cuenca-mx/sentry-python
python
def _looks_like_asgi3(app): '\n Try to figure out if an application object supports ASGI3.\n\n This is how uvicorn figures out the application version as well.\n ' if inspect.isclass(app): return hasattr(app, '__await__') elif inspect.isfunction(app): return asyncio.iscoroutinefunct...
def __init__(self, app, unsafe_context_data=False): '\n Instrument an ASGI application with Sentry. Provides HTTP/websocket\n data to sent events and basic handling for exceptions bubbling up\n through the middleware.\n\n :param unsafe_context_data: Disable errors when a proper contextva...
4,878,474,847,215,512,000
Instrument an ASGI application with Sentry. Provides HTTP/websocket data to sent events and basic handling for exceptions bubbling up through the middleware. :param unsafe_context_data: Disable errors when a proper contextvars installation could not be found. We do not recommend changing this from the default.
sentry_sdk/integrations/asgi.py
__init__
cuenca-mx/sentry-python
python
def __init__(self, app, unsafe_context_data=False): '\n Instrument an ASGI application with Sentry. Provides HTTP/websocket\n data to sent events and basic handling for exceptions bubbling up\n through the middleware.\n\n :param unsafe_context_data: Disable errors when a proper contextva...
def _get_url(self, scope, default_scheme, host): '\n Extract URL from the ASGI scope, without also including the querystring.\n ' scheme = scope.get('scheme', default_scheme) server = scope.get('server', None) path = (scope.get('root_path', '') + scope.get('path', '')) if host: ...
456,696,316,022,871,940
Extract URL from the ASGI scope, without also including the querystring.
sentry_sdk/integrations/asgi.py
_get_url
cuenca-mx/sentry-python
python
def _get_url(self, scope, default_scheme, host): '\n \n ' scheme = scope.get('scheme', default_scheme) server = scope.get('server', None) path = (scope.get('root_path', ) + scope.get('path', )) if host: return ('%s://%s%s' % (scheme, host, path)) if (server is not None): ...
def _get_query(self, scope): '\n Extract querystring from the ASGI scope, in the format that the Sentry protocol expects.\n ' qs = scope.get('query_string') if (not qs): return None return urllib.parse.unquote(qs.decode('latin-1'))
-3,749,750,348,190,675,000
Extract querystring from the ASGI scope, in the format that the Sentry protocol expects.
sentry_sdk/integrations/asgi.py
_get_query
cuenca-mx/sentry-python
python
def _get_query(self, scope): '\n \n ' qs = scope.get('query_string') if (not qs): return None return urllib.parse.unquote(qs.decode('latin-1'))
def _get_headers(self, scope): '\n Extract headers from the ASGI scope, in the format that the Sentry protocol expects.\n ' headers = {} for (raw_key, raw_value) in scope['headers']: key = raw_key.decode('latin-1') value = raw_value.decode('latin-1') if (key in headers)...
-2,763,036,242,865,239,000
Extract headers from the ASGI scope, in the format that the Sentry protocol expects.
sentry_sdk/integrations/asgi.py
_get_headers
cuenca-mx/sentry-python
python
def _get_headers(self, scope): '\n \n ' headers = {} for (raw_key, raw_value) in scope['headers']: key = raw_key.decode('latin-1') value = raw_value.decode('latin-1') if (key in headers): headers[key] = ((headers[key] + ', ') + value) else: ...
def text2phone(text, language): '\n Convert graphemes to phonemes.\n ' seperator = phonemizer.separator.Separator(' |', '', '|') punctuations = re.findall(PHONEME_PUNCTUATION_PATTERN, text) if (version.parse(phonemizer.__version__) < version.parse('2.1')): ph = phonemize(text, separator=se...
-8,971,153,413,979,716,000
Convert graphemes to phonemes.
utils/text/__init__.py
text2phone
DanBmh/TTS
python
def text2phone(text, language): '\n \n ' seperator = phonemizer.separator.Separator(' |', , '|') punctuations = re.findall(PHONEME_PUNCTUATION_PATTERN, text) if (version.parse(phonemizer.__version__) < version.parse('2.1')): ph = phonemize(text, separator=seperator, strip=False, njobs=1, b...
def sequence_to_phoneme(sequence, tp=None): 'Converts a sequence of IDs back to a string' global _id_to_phonemes result = '' if tp: (_, _phonemes) = make_symbols(**tp) _id_to_phonemes = {i: s for (i, s) in enumerate(_phonemes)} for symbol_id in sequence: if (symbol_id in _id_...
6,434,912,201,758,388,000
Converts a sequence of IDs back to a string
utils/text/__init__.py
sequence_to_phoneme
DanBmh/TTS
python
def sequence_to_phoneme(sequence, tp=None): global _id_to_phonemes result = if tp: (_, _phonemes) = make_symbols(**tp) _id_to_phonemes = {i: s for (i, s) in enumerate(_phonemes)} for symbol_id in sequence: if (symbol_id in _id_to_phonemes): s = _id_to_phonemes[s...
def text_to_sequence(text, cleaner_names, tp=None): 'Converts a string of text to a sequence of IDs corresponding to the symbols in the text.\n\n The text can optionally have ARPAbet sequences enclosed in curly braces embedded\n in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street."\n\n Args...
-863,534,234,504,303,600
Converts a string of text to a sequence of IDs corresponding to the symbols in the text. The text can optionally have ARPAbet sequences enclosed in curly braces embedded in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street." Args: text: string to convert to a sequence cleaner_names: names of the cleaner ...
utils/text/__init__.py
text_to_sequence
DanBmh/TTS
python
def text_to_sequence(text, cleaner_names, tp=None): 'Converts a string of text to a sequence of IDs corresponding to the symbols in the text.\n\n The text can optionally have ARPAbet sequences enclosed in curly braces embedded\n in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street."\n\n Args...
def sequence_to_text(sequence, tp=None): 'Converts a sequence of IDs back to a string' global _id_to_symbol if tp: (_symbols, _) = make_symbols(**tp) _id_to_symbol = {i: s for (i, s) in enumerate(_symbols)} result = '' for symbol_id in sequence: if (symbol_id in _id_to_symbol...
-3,614,943,435,538,793,500
Converts a sequence of IDs back to a string
utils/text/__init__.py
sequence_to_text
DanBmh/TTS
python
def sequence_to_text(sequence, tp=None): global _id_to_symbol if tp: (_symbols, _) = make_symbols(**tp) _id_to_symbol = {i: s for (i, s) in enumerate(_symbols)} result = for symbol_id in sequence: if (symbol_id in _id_to_symbol): s = _id_to_symbol[symbol_id] ...
def validate_subdirectory_string(subdirectory_str): ' Validate subdirectory string ' if (not subdirectory_str.isascii()): raise argparse.ArgumentTypeError(('%s contains non ascii characters' % subdirectory_str)) if subdirectory_str.startswith('/'): subdirectory_str = subdirectory_str[1:] ...
9,133,025,839,659,418,000
Validate subdirectory string
update-attack.py
validate_subdirectory_string
Alexander-RB/attack-website
python
def validate_subdirectory_string(subdirectory_str): ' ' if (not subdirectory_str.isascii()): raise argparse.ArgumentTypeError(('%s contains non ascii characters' % subdirectory_str)) if subdirectory_str.startswith('/'): subdirectory_str = subdirectory_str[1:] if subdirectory_str.endswit...
def get_parsed_args(): 'Create argument parser and parse arguments' parser = argparse.ArgumentParser(description='Build the ATT&CK website.\nAll flags are optional. If you run the build without flags, the modules that pertain to the ATT&CK dataset will be ran. If you would like to run extra modules, opt-in thes...
3,227,462,813,491,606,500
Create argument parser and parse arguments
update-attack.py
get_parsed_args
Alexander-RB/attack-website
python
def get_parsed_args(): parser = argparse.ArgumentParser(description='Build the ATT&CK website.\nAll flags are optional. If you run the build without flags, the modules that pertain to the ATT&CK dataset will be ran. If you would like to run extra modules, opt-in these modules with the--extras flag.') parse...
def remove_from_build(arg_modules, arg_extras): ' Given a list of modules from command line, remove modules that appear in module\n directory that are not in list.\n ' def remove_from_running_pool(): ' Remove modules from running pool if they are not in modules list from argument ' co...
-4,698,552,695,145,996,000
Given a list of modules from command line, remove modules that appear in module directory that are not in list.
update-attack.py
remove_from_build
Alexander-RB/attack-website
python
def remove_from_build(arg_modules, arg_extras): ' Given a list of modules from command line, remove modules that appear in module\n directory that are not in list.\n ' def remove_from_running_pool(): ' Remove modules from running pool if they are not in modules list from argument ' co...
def remove_from_running_pool(): ' Remove modules from running pool if they are not in modules list from argument ' copy_of_modules = [] for module in modules.run_ptr: if (module['name'].lower() in arg_modules): copy_of_modules.append(module) modules.run_ptr = copy_of_modules
-6,515,811,293,937,717,000
Remove modules from running pool if they are not in modules list from argument
update-attack.py
remove_from_running_pool
Alexander-RB/attack-website
python
def remove_from_running_pool(): ' ' copy_of_modules = [] for module in modules.run_ptr: if (module['name'].lower() in arg_modules): copy_of_modules.append(module) modules.run_ptr = copy_of_modules
def remove_from_menu(): ' Remove modules from menu if they are not in modules list from argument ' copy_of_menu = [] for module in modules.menu_ptr: if (module['name'].lower() in arg_modules): copy_of_menu.append(module) modules.menu_ptr = copy_of_menu
-6,787,491,815,310,537,000
Remove modules from menu if they are not in modules list from argument
update-attack.py
remove_from_menu
Alexander-RB/attack-website
python
def remove_from_menu(): ' ' copy_of_menu = [] for module in modules.menu_ptr: if (module['name'].lower() in arg_modules): copy_of_menu.append(module) modules.menu_ptr = copy_of_menu
def run_command(command, display_cmd=False, ignore_error=False, print_to_console=True): 'Run bash command and print output to stdout\n ' if (display_cmd == True): click.echo((click.style('Running command: ', fg='cyan') + click.style(command, fg='green'))) proc = subprocess.Popen(command, shell=Tr...
3,621,573,615,239,375,400
Run bash command and print output to stdout
show/plugins/mlnx.py
run_command
AshokDaparthi/sonic-utilities
python
def run_command(command, display_cmd=False, ignore_error=False, print_to_console=True): '\n ' if (display_cmd == True): click.echo((click.style('Running command: ', fg='cyan') + click.style(command, fg='green'))) proc = subprocess.Popen(command, shell=True, text=True, stdout=subprocess.PIPE) ...
@click.group() def mlnx(): ' Show Mellanox platform information ' pass
-8,046,836,575,544,220,000
Show Mellanox platform information
show/plugins/mlnx.py
mlnx
AshokDaparthi/sonic-utilities
python
@click.group() def mlnx(): ' ' pass
def is_issu_status_enabled(): ' This function parses the SAI XML profile used for mlnx to\n get whether ISSU is enabled or disabled\n @return: True/False\n ' issu_enabled = False sai_profile_path = '/{}/sai.profile'.format(HWSKU_PATH) DOCKER_CAT_COMMAND = 'docker exec {container_name} cat {path...
8,463,833,370,658,066,000
This function parses the SAI XML profile used for mlnx to get whether ISSU is enabled or disabled @return: True/False
show/plugins/mlnx.py
is_issu_status_enabled
AshokDaparthi/sonic-utilities
python
def is_issu_status_enabled(): ' This function parses the SAI XML profile used for mlnx to\n get whether ISSU is enabled or disabled\n @return: True/False\n ' issu_enabled = False sai_profile_path = '/{}/sai.profile'.format(HWSKU_PATH) DOCKER_CAT_COMMAND = 'docker exec {container_name} cat {path...
@mlnx.command('sniffer') def sniffer_status(): ' Show sniffer status ' components = ['sdk'] env_variable_strings = [ENV_VARIABLE_SX_SNIFFER] for index in range(len(components)): enabled = sniffer_status_get(env_variable_strings[index]) if (enabled is True): click.echo((compon...
131,115,497,342,275,740
Show sniffer status
show/plugins/mlnx.py
sniffer_status
AshokDaparthi/sonic-utilities
python
@mlnx.command('sniffer') def sniffer_status(): ' ' components = ['sdk'] env_variable_strings = [ENV_VARIABLE_SX_SNIFFER] for index in range(len(components)): enabled = sniffer_status_get(env_variable_strings[index]) if (enabled is True): click.echo((components[index] + ' sni...
@mlnx.command('issu') def issu_status(): ' Show ISSU status ' res = is_issu_status_enabled() click.echo(('ISSU is enabled' if res else 'ISSU is disabled'))
-331,031,383,470,014,140
Show ISSU status
show/plugins/mlnx.py
issu_status
AshokDaparthi/sonic-utilities
python
@mlnx.command('issu') def issu_status(): ' ' res = is_issu_status_enabled() click.echo(('ISSU is enabled' if res else 'ISSU is disabled'))
def make_meshgrid(x, y, h=0.02): 'Create a mesh of points to plot in\n\n Parameters\n ----------\n x: data to base x-axis meshgrid on\n y: data to base y-axis meshgrid on\n h: stepsize for meshgrid, optional\n\n Returns\n -------\n xx, yy : ndarray\n ' ...
-4,317,779,463,543,041,500
Create a mesh of points to plot in Parameters ---------- x: data to base x-axis meshgrid on y: data to base y-axis meshgrid on h: stepsize for meshgrid, optional Returns ------- xx, yy : ndarray
main.py
make_meshgrid
MartimChaves/ret_detect
python
def make_meshgrid(x, y, h=0.02): 'Create a mesh of points to plot in\n\n Parameters\n ----------\n x: data to base x-axis meshgrid on\n y: data to base y-axis meshgrid on\n h: stepsize for meshgrid, optional\n\n Returns\n -------\n xx, yy : ndarray\n ' ...
def plot_contours(ax, clf, xx, yy, proba=False, **params): 'Plot the decision boundaries for a classifier.\n\n Parameters\n ----------\n ax: matplotlib axes object\n clf: a classifier\n xx: meshgrid ndarray\n yy: meshgrid ndarray\n params: dictionary of params to pas...
-8,037,834,054,018,846,000
Plot the decision boundaries for a classifier. Parameters ---------- ax: matplotlib axes object clf: a classifier xx: meshgrid ndarray yy: meshgrid ndarray params: dictionary of params to pass to contourf, optional
main.py
plot_contours
MartimChaves/ret_detect
python
def plot_contours(ax, clf, xx, yy, proba=False, **params): 'Plot the decision boundaries for a classifier.\n\n Parameters\n ----------\n ax: matplotlib axes object\n clf: a classifier\n xx: meshgrid ndarray\n yy: meshgrid ndarray\n params: dictionary of params to pas...
def apply(self, context, clear, split, check_for_existing=True, **kwargs): 'Extract Candidates from a Context' if (not isinstance(context, Sentence)): raise NotImplementedError(('%s is currently only implemented for Sentence contexts.' % self.__name__)) entity_idxs = dict(((et, defaultdict(list)) fo...
7,479,512,621,843,678,000
Extract Candidates from a Context
snorkel/candidates.py
apply
ailabx/snorkel
python
def apply(self, context, clear, split, check_for_existing=True, **kwargs): if (not isinstance(context, Sentence)): raise NotImplementedError(('%s is currently only implemented for Sentence contexts.' % self.__name__)) entity_idxs = dict(((et, defaultdict(list)) for et in set(self.entity_types))) ...
def read_inputs(self, name: str): '\n read circuit graphs\n ' top_ports = [] ports_weight = {} for (node, attr) in self.G.nodes(data=True): if ('source' in attr['inst_type']): for source_nets in self.G.neighbors(node): top_ports.append(source_nets) ...
-3,506,295,908,788,865,500
read circuit graphs
align/compiler/create_database.py
read_inputs
mabrains/ALIGN-public
python
def read_inputs(self, name: str): '\n \n ' top_ports = [] ports_weight = {} for (node, attr) in self.G.nodes(data=True): if ('source' in attr['inst_type']): for source_nets in self.G.neighbors(node): top_ports.append(source_nets) elif ('net_type'...
def _traverse_hier_in_graph(self, G): '\n Recusively reads all hierachies in the graph and convert them to dictionary\n ' for (node, attr) in G.nodes(data=True): if (('sub_graph' in attr) and attr['sub_graph']): logger.debug(f"Traversing sub graph: {node} {attr['inst_type']} {a...
66,405,325,679,430,640
Recusively reads all hierachies in the graph and convert them to dictionary
align/compiler/create_database.py
_traverse_hier_in_graph
mabrains/ALIGN-public
python
def _traverse_hier_in_graph(self, G): '\n \n ' for (node, attr) in G.nodes(data=True): if (('sub_graph' in attr) and attr['sub_graph']): logger.debug(f"Traversing sub graph: {node} {attr['inst_type']} {attr['ports']}") sub_ports = [] ports_weight = {} ...
def run(self, loaderFunc): 'Called when execution of a feeder element is desired.' if (loaderFunc == Type.kIntake): if ((self.xboxMap.getDriveLeftTrig() > 0) and (self.xboxMap.getDriveRightTrig() == 0)): self.intakeMotor.runIntake(self.intakeMotorSpeed, Direction.kForwards) log.d...
4,227,365,644,385,983,500
Called when execution of a feeder element is desired.
components/Actuators/HighLevel/feederMap.py
run
Raptacon/Robot-2022
python
def run(self, loaderFunc): if (loaderFunc == Type.kIntake): if ((self.xboxMap.getDriveLeftTrig() > 0) and (self.xboxMap.getDriveRightTrig() == 0)): self.intakeMotor.runIntake(self.intakeMotorSpeed, Direction.kForwards) log.debug('right trig intake', self.xboxMap.getMechRightTrig...
def __init__(self, graph=None): '\n Initializes the CASE document.\n Args:\n graph: The graph to populate (instance of rdflib.Graph)\n If not provided, a graph in memory will be used.\n ' if (not graph): graph = rdflib.Graph() graph.namespace_manager...
-570,383,764,642,344,300
Initializes the CASE document. Args: graph: The graph to populate (instance of rdflib.Graph) If not provided, a graph in memory will be used.
example/case_example.py
__init__
casework/CASE-API-Python
python
def __init__(self, graph=None): '\n Initializes the CASE document.\n Args:\n graph: The graph to populate (instance of rdflib.Graph)\n If not provided, a graph in memory will be used.\n ' if (not graph): graph = rdflib.Graph() graph.namespace_manager...
def _sanitize_triple(self, triple): 'Santizes the triple to contains pure rdflib terms.' (s, p, o) = triple if isinstance(s, Node): s = s._node if isinstance(o, Node): o = o._node elif ((o is not None) and (not isinstance(o, rdflib.term.Node))): o = rdflib.Literal(o) if (...
-2,340,009,076,956,215,300
Santizes the triple to contains pure rdflib terms.
example/case_example.py
_sanitize_triple
casework/CASE-API-Python
python
def _sanitize_triple(self, triple): (s, p, o) = triple if isinstance(s, Node): s = s._node if isinstance(o, Node): o = o._node elif ((o is not None) and (not isinstance(o, rdflib.term.Node))): o = rdflib.Literal(o) if ((p is not None) and (not isinstance(p, rdflib.term.N...
def __iter__(self): 'Wrapper for iterating over all triples in the graph' return iter(self.graph)
3,017,913,809,145,363,000
Wrapper for iterating over all triples in the graph
example/case_example.py
__iter__
casework/CASE-API-Python
python
def __iter__(self): return iter(self.graph)
def __contains__(self, triple): 'Wrapper for checking if triple is contained in the graph.' return (self._sanitize_triple(triple) in self.graph)
-3,107,036,654,600,936,000
Wrapper for checking if triple is contained in the graph.
example/case_example.py
__contains__
casework/CASE-API-Python
python
def __contains__(self, triple): return (self._sanitize_triple(triple) in self.graph)
def triples(self, triple): 'Generator over the triple store in graph.' return self.graph.triples(self._sanitize_triple(triple))
1,302,646,430,989,216,500
Generator over the triple store in graph.
example/case_example.py
triples
casework/CASE-API-Python
python
def triples(self, triple): return self.graph.triples(self._sanitize_triple(triple))
def serialize(self, format='json-ld', **kwargs): "Serializes the document's graph to a destination.\n (Follows same arguments as rdflib.Graph().serialize())" if (format == 'json-ld'): if ('context' not in kwargs): kwargs['context'] = self._json_ld_context() if ('auto_compact' ...
-4,027,732,136,207,101,400
Serializes the document's graph to a destination. (Follows same arguments as rdflib.Graph().serialize())
example/case_example.py
serialize
casework/CASE-API-Python
python
def serialize(self, format='json-ld', **kwargs): "Serializes the document's graph to a destination.\n (Follows same arguments as rdflib.Graph().serialize())" if (format == 'json-ld'): if ('context' not in kwargs): kwargs['context'] = self._json_ld_context() if ('auto_compact' ...
def create_CoreObject(self, _type=None, **kwargs): '\n Creates and returns a CoreObject.\n ' return CoreObject(self.graph, rdf_type=_type, **kwargs)
-7,912,393,568,977,087,000
Creates and returns a CoreObject.
example/case_example.py
create_CoreObject
casework/CASE-API-Python
python
def create_CoreObject(self, _type=None, **kwargs): '\n \n ' return CoreObject(self.graph, rdf_type=_type, **kwargs)
def create_ContextObject(self, _type=None, **kwargs): '\n Creates and returns a Context.\n This class may not have PropertyBundles.\n ' return ContextObject(self.graph, rdf_type=_type, **kwargs)
-7,159,098,150,300,702,000
Creates and returns a Context. This class may not have PropertyBundles.
example/case_example.py
create_ContextObject
casework/CASE-API-Python
python
def create_ContextObject(self, _type=None, **kwargs): '\n Creates and returns a Context.\n This class may not have PropertyBundles.\n ' return ContextObject(self.graph, rdf_type=_type, **kwargs)
def create_SubObject(self, _type=None, **kwargs): '\n Creates and returns a Sub.\n This class is for children of one of the above CASE classes.\n This class may not have PropertyBundles.\n ' return SubObject(self.graph, rdf_type=_type, **kwargs)
6,910,321,356,426,898,000
Creates and returns a Sub. This class is for children of one of the above CASE classes. This class may not have PropertyBundles.
example/case_example.py
create_SubObject
casework/CASE-API-Python
python
def create_SubObject(self, _type=None, **kwargs): '\n Creates and returns a Sub.\n This class is for children of one of the above CASE classes.\n This class may not have PropertyBundles.\n ' return SubObject(self.graph, rdf_type=_type, **kwargs)
def create_DuckObject(self, _type=None, **kwargs): '\n Creates and returns a Duck.\n These lonely Ducks have no parents and are fully duck-typed.\n This class may not have PropertyBundles.\n ' return DuckObject(self.graph, rdf_type=_type, **kwargs)
4,973,963,120,371,535,000
Creates and returns a Duck. These lonely Ducks have no parents and are fully duck-typed. This class may not have PropertyBundles.
example/case_example.py
create_DuckObject
casework/CASE-API-Python
python
def create_DuckObject(self, _type=None, **kwargs): '\n Creates and returns a Duck.\n These lonely Ducks have no parents and are fully duck-typed.\n This class may not have PropertyBundles.\n ' return DuckObject(self.graph, rdf_type=_type, **kwargs)
def __init__(self, graph, uri=None, bnode=False, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n\n NOTE: At least the type or a property must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib...
8,967,509,059,899,799,000
Initializes and adds a node to the graph. NOTE: At least the type or a property must be supplied for the Node to exist in the graph. Args: graph: The graph to add this node to. (instance of rdflib.Graph) uri: Optional string to set th URI to. (If not provided a UUID will be generated.) bnode: Whether to c...
example/case_example.py
__init__
casework/CASE-API-Python
python
def __init__(self, graph, uri=None, bnode=False, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n\n NOTE: At least the type or a property must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib...
def add(self, property, value): 'Adds a property and its value to the node.' if (value is None): return if isinstance(value, (list, tuple, set)): for item in value: self.add(property, item) return if isinstance(value, Node): value = value._node elif (not i...
4,964,973,318,960,611,000
Adds a property and its value to the node.
example/case_example.py
add
casework/CASE-API-Python
python
def add(self, property, value): if (value is None): return if isinstance(value, (list, tuple, set)): for item in value: self.add(property, item) return if isinstance(value, Node): value = value._node elif (not isinstance(value, rdflib.term.Node)): ...
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type or a property must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_...
7,103,185,099,151,627,000
Initializes and adds a node to the graph. NOTE: At least the type or a property must be supplied for the Node to exist in the graph. Args: graph: The graph to add this node to. (instance of rdflib.Graph) rdf_type: The RDF type to set this node to. properties: Extra properties to add to this node. (More...
example/case_example.py
__init__
casework/CASE-API-Python
python
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type or a property must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_...
def create_PropertyBundle(self, prop_type=None, **kwargs): 'Convenience function for adding property bundles to this Trace.\n\n Args:\n type: The @type of property bundle (can be of type rdflib.URIRef or string).\n properties: Properties to add to the created property bundle.\n\n ...
8,454,463,926,833,009,000
Convenience function for adding property bundles to this Trace. Args: type: The @type of property bundle (can be of type rdflib.URIRef or string). properties: Properties to add to the created property bundle. Returns: The property bundle created (instance of PropertyBundle).
example/case_example.py
create_PropertyBundle
casework/CASE-API-Python
python
def create_PropertyBundle(self, prop_type=None, **kwargs): 'Convenience function for adding property bundles to this Trace.\n\n Args:\n type: The @type of property bundle (can be of type rdflib.URIRef or string).\n properties: Properties to add to the created property bundle.\n\n ...
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type or a property must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_...
26,501,929,538,819,850
Initializes and adds a node to the graph. NOTE: At least the type or a property must be supplied for the Node to exist in the graph. Args: graph: The graph to add this node to. (instance of rdflib.Graph) rdf_type: The RDF type to set this node to. properties: Extra properties to add to this node. (More...
example/case_example.py
__init__
casework/CASE-API-Python
python
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type or a property must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_...
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_type: The RDF ...
-5,985,738,002,460,461,000
Initializes and adds a node to the graph. NOTE: At least the type must be supplied for the Node to exist in the graph. Args: graph: The graph to add this node to. (instance of rdflib.Graph) rdf_type: The RDF type to set this node to. properties: Extra properties to add to this node. (More properties ca...
example/case_example.py
__init__
casework/CASE-API-Python
python
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_type: The RDF ...
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_type: The RDF ...
3,458,609,786,989,587,000
Initializes and adds a node to the graph. NOTE: At least the type must be supplied for the Node to exist in the graph. Args: graph: The graph to add this node to. (instance of rdflib.Graph) rdf_type: The RDF type to set this node to. properties: Extra properties to add to this node. (More properties ca...
example/case_example.py
__init__
casework/CASE-API-Python
python
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_type: The RDF ...
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_type: The RDF ...
458,313,680,131,040,830
Initializes and adds a node to the graph. NOTE: At least the type must be supplied for the Node to exist in the graph. Args: graph: The graph to add this node to. (instance of rdflib.Graph) rdf_type: The RDF type to set this node to. properties: Extra properties to add to this node. (More properties ca...
example/case_example.py
__init__
casework/CASE-API-Python
python
def __init__(self, graph, rdf_type=None, **kwargs): 'Initializes and adds a node to the graph.\n NOTE: At least the type must be supplied for the Node\n to exist in the graph.\n\n Args:\n graph: The graph to add this node to. (instance of rdflib.Graph)\n rdf_type: The RDF ...
def create_map_job(config, internal_storage, executor_id, job_id, map_function, iterdata, runtime_meta, runtime_memory, extra_env, include_modules, exclude_modules, execution_timeout, extra_args=None, obj_chunk_size=None, obj_chunk_number=None, invoke_pool_threads=128): '\n Wrapper to create a map job. It integ...
-4,410,323,720,239,119,000
Wrapper to create a map job. It integrates COS logic to process objects.
lithops/job/job.py
create_map_job
pablogs98/lithops
python
def create_map_job(config, internal_storage, executor_id, job_id, map_function, iterdata, runtime_meta, runtime_memory, extra_env, include_modules, exclude_modules, execution_timeout, extra_args=None, obj_chunk_size=None, obj_chunk_number=None, invoke_pool_threads=128): '\n \n ' host_job_meta = {'host_job...
def create_reduce_job(config, internal_storage, executor_id, reduce_job_id, reduce_function, map_job, map_futures, runtime_meta, runtime_memory, reducer_one_per_object, extra_env, include_modules, exclude_modules, execution_timeout=None): '\n Wrapper to create a reduce job. Apply a function across all map future...
266,928,933,511,763,460
Wrapper to create a reduce job. Apply a function across all map futures.
lithops/job/job.py
create_reduce_job
pablogs98/lithops
python
def create_reduce_job(config, internal_storage, executor_id, reduce_job_id, reduce_function, map_job, map_futures, runtime_meta, runtime_memory, reducer_one_per_object, extra_env, include_modules, exclude_modules, execution_timeout=None): '\n \n ' host_job_meta = {'host_job_create_tstamp': time.time()} ...
def _create_job(config, internal_storage, executor_id, job_id, func, iterdata, runtime_meta, runtime_memory, extra_env, include_modules, exclude_modules, execution_timeout, host_job_meta, invoke_pool_threads=128): '\n :param func: the function to map over the data\n :param iterdata: An iterable of input data\...
5,071,671,900,706,446,000
:param func: the function to map over the data :param iterdata: An iterable of input data :param extra_env: Additional environment variables for CF environment. Default None. :param extra_meta: Additional metadata to pass to CF. Default None. :param remote_invocation: Enable remote invocation. Default False. :param inv...
lithops/job/job.py
_create_job
pablogs98/lithops
python
def _create_job(config, internal_storage, executor_id, job_id, func, iterdata, runtime_meta, runtime_memory, extra_env, include_modules, exclude_modules, execution_timeout, host_job_meta, invoke_pool_threads=128): '\n :param func: the function to map over the data\n :param iterdata: An iterable of input data\...
def untar(path, fname, deleteTar=True): '\n Unpacks the given archive file to the same directory, then (by default)\n deletes the archive file.\n ' print(('unpacking ' + fname)) fullpath = os.path.join(path, fname) shutil.unpack_archive(fullpath, path) if deleteTar: os.remove(fullpa...
-8,229,018,165,018,037,000
Unpacks the given archive file to the same directory, then (by default) deletes the archive file.
cogdl/datasets/gtn_data.py
untar
AlvinWen428/cogdl
python
def untar(path, fname, deleteTar=True): '\n Unpacks the given archive file to the same directory, then (by default)\n deletes the archive file.\n ' print(('unpacking ' + fname)) fullpath = os.path.join(path, fname) shutil.unpack_archive(fullpath, path) if deleteTar: os.remove(fullpa...
@property @abc.abstractmethod def uuid(self) -> Optional[str]: 'Return the unique identifier of the repository.'
4,545,748,468,575,769,000
Return the unique identifier of the repository.
aiida/repository/backend/abstract.py
uuid
azadoks/aiida-core
python
@property @abc.abstractmethod def uuid(self) -> Optional[str]:
@property @abc.abstractmethod def key_format(self) -> Optional[str]: 'Return the format for the keys of the repository.\n\n Important for when migrating between backends (e.g. archive -> main), as if they are not equal then it is\n necessary to re-compute all the `Node.repository_metadata` before impo...
-7,728,492,979,033,497,000
Return the format for the keys of the repository. Important for when migrating between backends (e.g. archive -> main), as if they are not equal then it is necessary to re-compute all the `Node.repository_metadata` before importing (otherwise they will not match with the repository).
aiida/repository/backend/abstract.py
key_format
azadoks/aiida-core
python
@property @abc.abstractmethod def key_format(self) -> Optional[str]: 'Return the format for the keys of the repository.\n\n Important for when migrating between backends (e.g. archive -> main), as if they are not equal then it is\n necessary to re-compute all the `Node.repository_metadata` before impo...
@abc.abstractmethod def initialise(self, **kwargs) -> None: "Initialise the repository if it hasn't already been initialised.\n\n :param kwargs: parameters for the initialisation.\n "
-6,842,518,518,233,794,000
Initialise the repository if it hasn't already been initialised. :param kwargs: parameters for the initialisation.
aiida/repository/backend/abstract.py
initialise
azadoks/aiida-core
python
@abc.abstractmethod def initialise(self, **kwargs) -> None: "Initialise the repository if it hasn't already been initialised.\n\n :param kwargs: parameters for the initialisation.\n "
@property @abc.abstractmethod def is_initialised(self) -> bool: 'Return whether the repository has been initialised.'
-8,991,978,196,976,154,000
Return whether the repository has been initialised.
aiida/repository/backend/abstract.py
is_initialised
azadoks/aiida-core
python
@property @abc.abstractmethod def is_initialised(self) -> bool:
@abc.abstractmethod def erase(self) -> None: 'Delete the repository itself and all its contents.\n\n .. note:: This should not merely delete the contents of the repository but any resources it created. For\n example, if the repository is essentially a folder on disk, the folder itself should also ...
8,501,606,104,825,531,000
Delete the repository itself and all its contents. .. note:: This should not merely delete the contents of the repository but any resources it created. For example, if the repository is essentially a folder on disk, the folder itself should also be deleted, not just its contents.
aiida/repository/backend/abstract.py
erase
azadoks/aiida-core
python
@abc.abstractmethod def erase(self) -> None: 'Delete the repository itself and all its contents.\n\n .. note:: This should not merely delete the contents of the repository but any resources it created. For\n example, if the repository is essentially a folder on disk, the folder itself should also ...
def put_object_from_filelike(self, handle: BinaryIO) -> str: 'Store the byte contents of a file in the repository.\n\n :param handle: filelike object with the byte content to be stored.\n :return: the generated fully qualified identifier for the object within the repository.\n :raises TypeError...
9,115,440,169,624,832,000
Store the byte contents of a file in the repository. :param handle: filelike object with the byte content to be stored. :return: the generated fully qualified identifier for the object within the repository. :raises TypeError: if the handle is not a byte stream.
aiida/repository/backend/abstract.py
put_object_from_filelike
azadoks/aiida-core
python
def put_object_from_filelike(self, handle: BinaryIO) -> str: 'Store the byte contents of a file in the repository.\n\n :param handle: filelike object with the byte content to be stored.\n :return: the generated fully qualified identifier for the object within the repository.\n :raises TypeError...
def put_object_from_file(self, filepath: Union[(str, pathlib.Path)]) -> str: 'Store a new object with contents of the file located at `filepath` on this file system.\n\n :param filepath: absolute path of file whose contents to copy to the repository.\n :return: the generated fully qualified identifier...
-7,005,207,975,189,346,000
Store a new object with contents of the file located at `filepath` on this file system. :param filepath: absolute path of file whose contents to copy to the repository. :return: the generated fully qualified identifier for the object within the repository. :raises TypeError: if the handle is not a byte stream.
aiida/repository/backend/abstract.py
put_object_from_file
azadoks/aiida-core
python
def put_object_from_file(self, filepath: Union[(str, pathlib.Path)]) -> str: 'Store a new object with contents of the file located at `filepath` on this file system.\n\n :param filepath: absolute path of file whose contents to copy to the repository.\n :return: the generated fully qualified identifier...
@abc.abstractmethod def has_objects(self, keys: List[str]) -> List[bool]: 'Return whether the repository has an object with the given key.\n\n :param keys:\n list of fully qualified identifiers for objects within the repository.\n :return:\n list of logicals, in the same order as...
-506,592,450,390,231,200
Return whether the repository has an object with the given key. :param keys: list of fully qualified identifiers for objects within the repository. :return: list of logicals, in the same order as the keys provided, with value True if the respective object exists and False otherwise.
aiida/repository/backend/abstract.py
has_objects
azadoks/aiida-core
python
@abc.abstractmethod def has_objects(self, keys: List[str]) -> List[bool]: 'Return whether the repository has an object with the given key.\n\n :param keys:\n list of fully qualified identifiers for objects within the repository.\n :return:\n list of logicals, in the same order as...
def has_object(self, key: str) -> bool: 'Return whether the repository has an object with the given key.\n\n :param key: fully qualified identifier for the object within the repository.\n :return: True if the object exists, False otherwise.\n ' return self.has_objects([key])[0]
8,852,391,107,573,442,000
Return whether the repository has an object with the given key. :param key: fully qualified identifier for the object within the repository. :return: True if the object exists, False otherwise.
aiida/repository/backend/abstract.py
has_object
azadoks/aiida-core
python
def has_object(self, key: str) -> bool: 'Return whether the repository has an object with the given key.\n\n :param key: fully qualified identifier for the object within the repository.\n :return: True if the object exists, False otherwise.\n ' return self.has_objects([key])[0]
@abc.abstractmethod def list_objects(self) -> Iterable[str]: 'Return iterable that yields all available objects by key.\n\n :return: An iterable for all the available object keys.\n '
-939,318,421,040,364,300
Return iterable that yields all available objects by key. :return: An iterable for all the available object keys.
aiida/repository/backend/abstract.py
list_objects
azadoks/aiida-core
python
@abc.abstractmethod def list_objects(self) -> Iterable[str]: 'Return iterable that yields all available objects by key.\n\n :return: An iterable for all the available object keys.\n '
@contextlib.contextmanager def open(self, key: str) -> Iterator[BinaryIO]: 'Open a file handle to an object stored under the given key.\n\n .. note:: this should only be used to open a handle to read an existing file. To write a new file use the method\n ``put_object_from_filelike`` instead.\n\n ...
3,297,650,485,873,668,000
Open a file handle to an object stored under the given key. .. note:: this should only be used to open a handle to read an existing file. To write a new file use the method ``put_object_from_filelike`` instead. :param key: fully qualified identifier for the object within the repository. :return: yield a byte stre...
aiida/repository/backend/abstract.py
open
azadoks/aiida-core
python
@contextlib.contextmanager def open(self, key: str) -> Iterator[BinaryIO]: 'Open a file handle to an object stored under the given key.\n\n .. note:: this should only be used to open a handle to read an existing file. To write a new file use the method\n ``put_object_from_filelike`` instead.\n\n ...
def get_object_content(self, key: str) -> bytes: 'Return the content of a object identified by key.\n\n :param key: fully qualified identifier for the object within the repository.\n :raise FileNotFoundError: if the file does not exist.\n :raise OSError: if the file could not be opened.\n ...
8,643,959,129,101,297,000
Return the content of a object identified by key. :param key: fully qualified identifier for the object within the repository. :raise FileNotFoundError: if the file does not exist. :raise OSError: if the file could not be opened.
aiida/repository/backend/abstract.py
get_object_content
azadoks/aiida-core
python
def get_object_content(self, key: str) -> bytes: 'Return the content of a object identified by key.\n\n :param key: fully qualified identifier for the object within the repository.\n :raise FileNotFoundError: if the file does not exist.\n :raise OSError: if the file could not be opened.\n ...
@abc.abstractmethod def iter_object_streams(self, keys: List[str]) -> Iterator[Tuple[(str, BinaryIO)]]: 'Return an iterator over the (read-only) byte streams of objects identified by key.\n\n .. note:: handles should only be read within the context of this iterator.\n\n :param keys: fully qualified id...
-8,532,632,070,989,044,000
Return an iterator over the (read-only) byte streams of objects identified by key. .. note:: handles should only be read within the context of this iterator. :param keys: fully qualified identifiers for the objects within the repository. :return: an iterator over the object byte streams. :raise FileNotFoundError: if ...
aiida/repository/backend/abstract.py
iter_object_streams
azadoks/aiida-core
python
@abc.abstractmethod def iter_object_streams(self, keys: List[str]) -> Iterator[Tuple[(str, BinaryIO)]]: 'Return an iterator over the (read-only) byte streams of objects identified by key.\n\n .. note:: handles should only be read within the context of this iterator.\n\n :param keys: fully qualified id...
def get_object_hash(self, key: str) -> str: 'Return the SHA-256 hash of an object stored under the given key.\n\n .. important::\n A SHA-256 hash should always be returned,\n to ensure consistency across different repository implementations.\n\n :param key: fully qualified identi...
-5,363,301,719,493,803,000
Return the SHA-256 hash of an object stored under the given key. .. important:: A SHA-256 hash should always be returned, to ensure consistency across different repository implementations. :param key: fully qualified identifier for the object within the repository. :raise FileNotFoundError: if the file does n...
aiida/repository/backend/abstract.py
get_object_hash
azadoks/aiida-core
python
def get_object_hash(self, key: str) -> str: 'Return the SHA-256 hash of an object stored under the given key.\n\n .. important::\n A SHA-256 hash should always be returned,\n to ensure consistency across different repository implementations.\n\n :param key: fully qualified identi...
@abc.abstractmethod def delete_objects(self, keys: List[str]) -> None: 'Delete the objects from the repository.\n\n :param keys: list of fully qualified identifiers for the objects within the repository.\n :raise FileNotFoundError: if any of the files does not exist.\n :raise OSError: if any of...
6,488,864,614,444,447,000
Delete the objects from the repository. :param keys: list of fully qualified identifiers for the objects within the repository. :raise FileNotFoundError: if any of the files does not exist. :raise OSError: if any of the files could not be deleted.
aiida/repository/backend/abstract.py
delete_objects
azadoks/aiida-core
python
@abc.abstractmethod def delete_objects(self, keys: List[str]) -> None: 'Delete the objects from the repository.\n\n :param keys: list of fully qualified identifiers for the objects within the repository.\n :raise FileNotFoundError: if any of the files does not exist.\n :raise OSError: if any of...
def delete_object(self, key: str) -> None: 'Delete the object from the repository.\n\n :param key: fully qualified identifier for the object within the repository.\n :raise FileNotFoundError: if the file does not exist.\n :raise OSError: if the file could not be deleted.\n ' return s...
2,549,091,568,805,183,000
Delete the object from the repository. :param key: fully qualified identifier for the object within the repository. :raise FileNotFoundError: if the file does not exist. :raise OSError: if the file could not be deleted.
aiida/repository/backend/abstract.py
delete_object
azadoks/aiida-core
python
def delete_object(self, key: str) -> None: 'Delete the object from the repository.\n\n :param key: fully qualified identifier for the object within the repository.\n :raise FileNotFoundError: if the file does not exist.\n :raise OSError: if the file could not be deleted.\n ' return s...
@classmethod def setUpClass(cls): 'Launch the webdriver of choice with selected options(see browserconfig.py).\n Then login using pickled cookies(see tests/pickledlogin.py).' if (browserconfig.current_browser in ['chrome', 'firefox']): cls.driver = browserconfig.driver_runner(executable_path=brow...
547,812,806,824,385,660
Launch the webdriver of choice with selected options(see browserconfig.py). Then login using pickled cookies(see tests/pickledlogin.py).
tests/test_headerpage.py
setUpClass
BradleyPelton/NetflixSelenium
python
@classmethod def setUpClass(cls): 'Launch the webdriver of choice with selected options(see browserconfig.py).\n Then login using pickled cookies(see tests/pickledlogin.py).' if (browserconfig.current_browser in ['chrome', 'firefox']): cls.driver = browserconfig.driver_runner(executable_path=brow...
@classmethod def tearDownClass(cls): 'Closes the browser and shuts down the driver executable.' cls.driver.quit()
1,645,581,262,967,605,800
Closes the browser and shuts down the driver executable.
tests/test_headerpage.py
tearDownClass
BradleyPelton/NetflixSelenium
python
@classmethod def tearDownClass(cls): cls.driver.quit()
def setUp(self): 'Return to the home page, netflix.com/browse, the staging place for header tests.' self.driver.get('https://netflix.com/browse')
3,288,124,154,217,542,700
Return to the home page, netflix.com/browse, the staging place for header tests.
tests/test_headerpage.py
setUp
BradleyPelton/NetflixSelenium
python
def setUp(self): self.driver.get('https://netflix.com/browse')
def test_logout_from_header(self): 'Logout from the header.' header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.logout() self.assertIn('logout', self.driver.current_url) tests.pickledlogin.pickled_login(self.driver)
2,353,134,763,560,939,000
Logout from the header.
tests/test_headerpage.py
test_logout_from_header
BradleyPelton/NetflixSelenium
python
def test_logout_from_header(self): header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.logout() self.assertIn('logout', self.driver.current_url) tests.pickledlogin.pickled_login(self.driver)
def test_navigate_home_from_my_list(self): 'Using the giant Netflix logo in the top left, navigate to the home page /browse/\n from the my-list page.' self.driver.get('https://www.netflix.com/browse/my-list') header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.navigate_to_home...
-5,558,719,885,448,803,000
Using the giant Netflix logo in the top left, navigate to the home page /browse/ from the my-list page.
tests/test_headerpage.py
test_navigate_home_from_my_list
BradleyPelton/NetflixSelenium
python
def test_navigate_home_from_my_list(self): 'Using the giant Netflix logo in the top left, navigate to the home page /browse/\n from the my-list page.' self.driver.get('https://www.netflix.com/browse/my-list') header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.navigate_to_home...
def test_navigate_to_manage_profile(self): 'Using the header account dropdown, navigate to the manage profile page.' header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.navigate_to_manage_profile() self.assertIn('profiles/manage', self.driver.current_url)
-6,285,243,719,116,505,000
Using the header account dropdown, navigate to the manage profile page.
tests/test_headerpage.py
test_navigate_to_manage_profile
BradleyPelton/NetflixSelenium
python
def test_navigate_to_manage_profile(self): header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.navigate_to_manage_profile() self.assertIn('profiles/manage', self.driver.current_url)
def test_search_for_shawshank(self): "Using the search field, search for 'shawshank' and assert that shawshank was found." header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.search('shawshank') self.assertIn('The Shawshank Redemption', self.driver.page_source)
428,388,069,566,930,800
Using the search field, search for 'shawshank' and assert that shawshank was found.
tests/test_headerpage.py
test_search_for_shawshank
BradleyPelton/NetflixSelenium
python
def test_search_for_shawshank(self): header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.search('shawshank') self.assertIn('The Shawshank Redemption', self.driver.page_source)
def test_click_top_notification(self): 'Click the top notification and assert that the page has changed.' header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.click_top_notification() self.assertTrue((('title' in self.driver.current_url) or ('notification' in self.driver.current_url))...
-6,941,320,859,743,506,000
Click the top notification and assert that the page has changed.
tests/test_headerpage.py
test_click_top_notification
BradleyPelton/NetflixSelenium
python
def test_click_top_notification(self): header_page = pagemodels.headerpage.HeaderPage(self.driver) header_page.click_top_notification() self.assertTrue((('title' in self.driver.current_url) or ('notification' in self.driver.current_url)))
def dnn(tensor_in, hidden_units, activation=nn.relu, dropout=None): 'Creates fully connected deep neural network subgraph.\n\n Args:\n tensor_in: tensor or placeholder for input features.\n hidden_units: list of counts of hidden units in each layer.\n activation: activation function between layers. Can be...
-8,516,419,455,471,346,000
Creates fully connected deep neural network subgraph. Args: tensor_in: tensor or placeholder for input features. hidden_units: list of counts of hidden units in each layer. activation: activation function between layers. Can be None. dropout: if not None, will add a dropout layer with given probability. Retur...
tensorflow/contrib/learn/python/learn/ops/dnn_ops.py
dnn
InfoPrice/tensorflow
python
def dnn(tensor_in, hidden_units, activation=nn.relu, dropout=None): 'Creates fully connected deep neural network subgraph.\n\n Args:\n tensor_in: tensor or placeholder for input features.\n hidden_units: list of counts of hidden units in each layer.\n activation: activation function between layers. Can be...
def __init__(self, parent=None, orientation='bottom', *args, **kargs): "\n The *orientation* argument may be 'bottom', 'top', 'left', or 'right' \n indicating whether the gradient is displayed horizontally (top, bottom)\n or vertically (left, right) and on what side of the gradient the editable...
3,786,569,015,888,706,600
The *orientation* argument may be 'bottom', 'top', 'left', or 'right' indicating whether the gradient is displayed horizontally (top, bottom) or vertically (left, right) and on what side of the gradient the editable ticks will appear. All other arguments are passed to :func:`GradientEditorItem.__init__ <pyqtgraph.G...
scripts/pyqtgraph-develop/pyqtgraph/widgets/GradientWidget.py
__init__
kuldeepaman/tf-pose
python
def __init__(self, parent=None, orientation='bottom', *args, **kargs): "\n The *orientation* argument may be 'bottom', 'top', 'left', or 'right' \n indicating whether the gradient is displayed horizontally (top, bottom)\n or vertically (left, right) and on what side of the gradient the editable...