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 apply_bbox_cutout(image, bboxes, pad_fraction): 'Applies cutout to a single bounding box within image.' random_index = tf.random_uniform(shape=[], maxval=tf.shape(bboxes)[0], dtype=tf.int32) chosen_bbox = tf.gather(bboxes, random_index) (mask, mean) = _cutout_inside_bbox(image, chosen_bbox, pad_frac...
-3,658,342,878,226,009,000
Applies cutout to a single bounding box within image.
efficientdet/aug/autoaugment.py
apply_bbox_cutout
datawowio/automl
python
def apply_bbox_cutout(image, bboxes, pad_fraction): random_index = tf.random_uniform(shape=[], maxval=tf.shape(bboxes)[0], dtype=tf.int32) chosen_bbox = tf.gather(bboxes, random_index) (mask, mean) = _cutout_inside_bbox(image, chosen_bbox, pad_fraction) replace = (mean if replace_with_mean else 128...
@badpenny.periodic_task(seconds=TASK_TIME_OUT) def cleanup_old_tasks(job_status): 'delete any tracker task if it is older than the time a task can live for.' session = current_app.db.session('relengapi') expiry_cutoff = (now() - datetime.timedelta(seconds=TASK_TIME_OUT)) table = tables.ArchiverTask ...
-4,374,379,887,311,869,400
delete any tracker task if it is older than the time a task can live for.
relengapi/blueprints/archiver/__init__.py
cleanup_old_tasks
lundjordan/build-relengapi
python
@badpenny.periodic_task(seconds=TASK_TIME_OUT) def cleanup_old_tasks(job_status): session = current_app.db.session('relengapi') expiry_cutoff = (now() - datetime.timedelta(seconds=TASK_TIME_OUT)) table = tables.ArchiverTask for tracker in session.query(table).order_by(table.created_at): if ...
@bp.route('/status/<task_id>') @api.apimethod(MozharnessArchiveTask, unicode) def task_status(task_id): "\n Check and return the current state of the create_and_upload_archive celery task with task id\n of <task_id>.\n\n If the task is unknown, state will be PENDING. Once the task starts it will be updated...
2,060,864,171,519,897,900
Check and return the current state of the create_and_upload_archive celery task with task id of <task_id>. If the task is unknown, state will be PENDING. Once the task starts it will be updated to STARTED and finally, if it completes, it will be either SUCCESS (no exceptions), or FAILURE. See update_state() within cr...
relengapi/blueprints/archiver/__init__.py
task_status
lundjordan/build-relengapi
python
@bp.route('/status/<task_id>') @api.apimethod(MozharnessArchiveTask, unicode) def task_status(task_id): "\n Check and return the current state of the create_and_upload_archive celery task with task id\n of <task_id>.\n\n If the task is unknown, state will be PENDING. Once the task starts it will be updated...
@bp.route('/hgmo/<path:repo>/<rev>') @api.apimethod(None, unicode, unicode, unicode, unicode, unicode, status_code=302) def get_hgmo_archive(repo, rev, subdir=None, suffix='tar.gz', preferred_region=None): '\n An archiver for hg.mozilla.org related requests. Uses relengapi.blueprints.archiver.get_archive\n\n ...
-5,873,509,484,656,335,000
An archiver for hg.mozilla.org related requests. Uses relengapi.blueprints.archiver.get_archive :param repo: the repo location off of hg.mozilla.org/ :param rev: the rev associated with the repo :param subdir: optional subdir path to only archive a portion of the repo :param suffix: the archive extension type. default...
relengapi/blueprints/archiver/__init__.py
get_hgmo_archive
lundjordan/build-relengapi
python
@bp.route('/hgmo/<path:repo>/<rev>') @api.apimethod(None, unicode, unicode, unicode, unicode, unicode, status_code=302) def get_hgmo_archive(repo, rev, subdir=None, suffix='tar.gz', preferred_region=None): '\n An archiver for hg.mozilla.org related requests. Uses relengapi.blueprints.archiver.get_archive\n\n ...
def get_archive(src_url, key, preferred_region): '\n A generic getter for retrieving an s3 location of an archive where the archive is based off a\n src_url.\n\n sub-dir: hg.mozilla.org supports archives of sub directories within a repository. This\n flexibility allows for creating archives of only a po...
-6,013,747,439,112,581,000
A generic getter for retrieving an s3 location of an archive where the archive is based off a src_url. sub-dir: hg.mozilla.org supports archives of sub directories within a repository. This flexibility allows for creating archives of only a portion of what would normally be an entire repo archive. logic flow: If the...
relengapi/blueprints/archiver/__init__.py
get_archive
lundjordan/build-relengapi
python
def get_archive(src_url, key, preferred_region): '\n A generic getter for retrieving an s3 location of an archive where the archive is based off a\n src_url.\n\n sub-dir: hg.mozilla.org supports archives of sub directories within a repository. This\n flexibility allows for creating archives of only a po...
def test_exists() -> None: ' Program exists ' assert os.path.isfile(PRG)
-4,827,572,837,640,662,000
Program exists
09_grph/tests/grph_test.py
test_exists
BioPeterson/biofx_python
python
def test_exists() -> None: ' ' assert os.path.isfile(PRG)
def test_usage() -> None: ' Usage ' (rv, out) = getstatusoutput(RUN) assert (rv > 0) assert out.lower().startswith('usage:')
9,113,665,449,928,071,000
Usage
09_grph/tests/grph_test.py
test_usage
BioPeterson/biofx_python
python
def test_usage() -> None: ' ' (rv, out) = getstatusoutput(RUN) assert (rv > 0) assert out.lower().startswith('usage:')
def test_bad_k() -> None: ' Dies on bad k ' k = random.choice(range((- 10), 1)) (rv, out) = getstatusoutput(f'{RUN} -k {k} {SAMPLE1}') assert (rv != 0) assert out.lower().startswith('usage:') assert re.search(f'-k "{k}" must be > 0', out)
-1,136,513,366,063,022,600
Dies on bad k
09_grph/tests/grph_test.py
test_bad_k
BioPeterson/biofx_python
python
def test_bad_k() -> None: ' ' k = random.choice(range((- 10), 1)) (rv, out) = getstatusoutput(f'{RUN} -k {k} {SAMPLE1}') assert (rv != 0) assert out.lower().startswith('usage:') assert re.search(f'-k "{k}" must be > 0', out)
def test_bad_file() -> None: ' Dies on bad file ' bad = random_string() (rv, out) = getstatusoutput('{} {}'.format(RUN, bad)) assert (rv != 0) assert out.lower().startswith('usage:') assert re.search(f"No such file or directory: '{bad}'", out)
3,688,796,799,715,212,300
Dies on bad file
09_grph/tests/grph_test.py
test_bad_file
BioPeterson/biofx_python
python
def test_bad_file() -> None: ' ' bad = random_string() (rv, out) = getstatusoutput('{} {}'.format(RUN, bad)) assert (rv != 0) assert out.lower().startswith('usage:') assert re.search(f"No such file or directory: '{bad}'", out)
def run(in_file: str, k: int) -> None: ' Run with args ' out_file = '.'.join([in_file, str(k), 'out']) assert os.path.isfile(out_file) expected = open(out_file).read().rstrip() cmd = '{} -k {} {} | sort'.format(RUN, k, in_file) (rv, out) = getstatusoutput(cmd) assert (rv == 0) assert (ou...
2,782,652,345,295,144,400
Run with args
09_grph/tests/grph_test.py
run
BioPeterson/biofx_python
python
def run(in_file: str, k: int) -> None: ' ' out_file = '.'.join([in_file, str(k), 'out']) assert os.path.isfile(out_file) expected = open(out_file).read().rstrip() cmd = '{} -k {} {} | sort'.format(RUN, k, in_file) (rv, out) = getstatusoutput(cmd) assert (rv == 0) assert (out.rstrip() ==...
def test_01(): ' Runs OK ' run(SAMPLE1, 3)
4,297,253,423,442,003,500
Runs OK
09_grph/tests/grph_test.py
test_01
BioPeterson/biofx_python
python
def test_01(): ' ' run(SAMPLE1, 3)
def test_02() -> None: ' Runs OK ' run(SAMPLE1, 4)
8,518,686,450,370,489,000
Runs OK
09_grph/tests/grph_test.py
test_02
BioPeterson/biofx_python
python
def test_02() -> None: ' ' run(SAMPLE1, 4)
def test_03() -> None: ' Runs OK ' run(SAMPLE1, 5)
7,497,294,204,659,460,000
Runs OK
09_grph/tests/grph_test.py
test_03
BioPeterson/biofx_python
python
def test_03() -> None: ' ' run(SAMPLE1, 5)
def test_04() -> None: ' Runs OK ' run(SAMPLE2, 3)
-278,510,080,884,287,400
Runs OK
09_grph/tests/grph_test.py
test_04
BioPeterson/biofx_python
python
def test_04() -> None: ' ' run(SAMPLE2, 3)
def test_05() -> None: ' Runs OK ' run(SAMPLE2, 4)
-451,182,995,679,305,300
Runs OK
09_grph/tests/grph_test.py
test_05
BioPeterson/biofx_python
python
def test_05() -> None: ' ' run(SAMPLE2, 4)
def test_06() -> None: ' Runs OK ' run(SAMPLE2, 5)
-4,800,970,842,889,804,000
Runs OK
09_grph/tests/grph_test.py
test_06
BioPeterson/biofx_python
python
def test_06() -> None: ' ' run(SAMPLE2, 5)
def test_07() -> None: ' Runs OK ' run(SAMPLE3, 3)
5,923,181,508,090,840,000
Runs OK
09_grph/tests/grph_test.py
test_07
BioPeterson/biofx_python
python
def test_07() -> None: ' ' run(SAMPLE3, 3)
def test_08() -> None: ' Runs OK ' run(SAMPLE3, 4)
-9,171,916,681,065,659,000
Runs OK
09_grph/tests/grph_test.py
test_08
BioPeterson/biofx_python
python
def test_08() -> None: ' ' run(SAMPLE3, 4)
def test_09() -> None: ' Runs OK ' run(SAMPLE3, 5)
-4,117,453,768,972,889,000
Runs OK
09_grph/tests/grph_test.py
test_09
BioPeterson/biofx_python
python
def test_09() -> None: ' ' run(SAMPLE3, 5)
def random_string() -> str: 'Generate a random string' return ''.join(random.sample((string.ascii_letters + string.digits), k=random.randint(5, 10)))
-4,268,000,723,444,968,400
Generate a random string
09_grph/tests/grph_test.py
random_string
BioPeterson/biofx_python
python
def random_string() -> str: return .join(random.sample((string.ascii_letters + string.digits), k=random.randint(5, 10)))
def create_pipeline() -> pipeline_pb2.Pipeline: 'Creates an async pipeline for testing.' example_gen = _example_gen().with_id('my_example_gen') transform = _transform(examples=example_gen.outputs['examples'], a_param=10).with_id('my_transform') trainer = _trainer(examples=example_gen.outputs['examples']...
-8,291,859,342,785,953,000
Creates an async pipeline for testing.
tfx/orchestration/experimental/core/testing/test_async_pipeline.py
create_pipeline
Avnish327030/tfx
python
def create_pipeline() -> pipeline_pb2.Pipeline: example_gen = _example_gen().with_id('my_example_gen') transform = _transform(examples=example_gen.outputs['examples'], a_param=10).with_id('my_transform') trainer = _trainer(examples=example_gen.outputs['examples'], transform_graph=transform.outputs['tra...
def is_absolute_uri(url: ParseResult) -> bool: '\n Returns True if the parsed result is an "absolute URI".\n\n We define an "absolute URI" as containing at mimimum a **scheme** and an\n **host** (a.k.a., an authority).\n\n It must contain SH according to the nomenclature defined in this proposal:\n h...
-397,197,891,575,155,200
Returns True if the parsed result is an "absolute URI". We define an "absolute URI" as containing at mimimum a **scheme** and an **host** (a.k.a., an authority). It must contain SH according to the nomenclature defined in this proposal: https://gist.github.com/andrewdotn/eebeaa60d48c3c0f6f9fc75f0ede8d03#proposal Exa...
src/CreeDictionary/CreeDictionary/templatetags/url_extras.py
is_absolute_uri
Madoshakalaka/morphodict
python
def is_absolute_uri(url: ParseResult) -> bool: '\n Returns True if the parsed result is an "absolute URI".\n\n We define an "absolute URI" as containing at mimimum a **scheme** and an\n **host** (a.k.a., an authority).\n\n It must contain SH according to the nomenclature defined in this proposal:\n h...
def to_pf_url(url: ParseResult): '\n Returns *P*ath and *F*ile as defined here:\n https://gist.github.com/andrewdotn/eebeaa60d48c3c0f6f9fc75f0ede8d03#proposal\n ' return urlunparse(url._replace(scheme='', netloc=''))
249,949,858,676,596,380
Returns *P*ath and *F*ile as defined here: https://gist.github.com/andrewdotn/eebeaa60d48c3c0f6f9fc75f0ede8d03#proposal
src/CreeDictionary/CreeDictionary/templatetags/url_extras.py
to_pf_url
Madoshakalaka/morphodict
python
def to_pf_url(url: ParseResult): '\n Returns *P*ath and *F*ile as defined here:\n https://gist.github.com/andrewdotn/eebeaa60d48c3c0f6f9fc75f0ede8d03#proposal\n ' return urlunparse(url._replace(scheme=, netloc=))
@register.tag def abstatic(parser, token): '\n Given a relative path to a static asset, return the absolute path to the\n asset.\n\n Derived from: https://github.com/django/django/blob/635d53a86a36cde7866b9caefeb64d809e6bfcd9/django/templatetags/static.py#L143-L159\n ' return AbstaticNode.handle_tok...
-6,947,781,304,580,890,000
Given a relative path to a static asset, return the absolute path to the asset. Derived from: https://github.com/django/django/blob/635d53a86a36cde7866b9caefeb64d809e6bfcd9/django/templatetags/static.py#L143-L159
src/CreeDictionary/CreeDictionary/templatetags/url_extras.py
abstatic
Madoshakalaka/morphodict
python
@register.tag def abstatic(parser, token): '\n Given a relative path to a static asset, return the absolute path to the\n asset.\n\n Derived from: https://github.com/django/django/blob/635d53a86a36cde7866b9caefeb64d809e6bfcd9/django/templatetags/static.py#L143-L159\n ' return AbstaticNode.handle_tok...
def _get_path(self, subpath: str) -> str: 'get full subpath' return f"engagements/v{(self.options.get('version') or ENGAGEMENTS_API_VERSION)}/{subpath}"
-5,392,205,939,925,482,000
get full subpath
hubspot3/engagements.py
_get_path
benaduggan/hubspot3
python
def _get_path(self, subpath: str) -> str: return f"engagements/v{(self.options.get('version') or ENGAGEMENTS_API_VERSION)}/{subpath}"
def get(self, engagement_id, **options): 'Get a HubSpot engagement.' return self._call(f'engagements/{engagement_id}', method='GET', **options)
-5,515,921,273,092,089,000
Get a HubSpot engagement.
hubspot3/engagements.py
get
benaduggan/hubspot3
python
def get(self, engagement_id, **options): return self._call(f'engagements/{engagement_id}', method='GET', **options)
def get_associated(self, object_type, object_id, **options) -> List[Dict]: '\n get all engagements associated with the given object\n :param object_type: type of object to get associations on [CONTACT, COMPANY, DEAL]\n :param object_id: ID of the object to get associations on\n ' fin...
892,432,714,481,501,600
get all engagements associated with the given object :param object_type: type of object to get associations on [CONTACT, COMPANY, DEAL] :param object_id: ID of the object to get associations on
hubspot3/engagements.py
get_associated
benaduggan/hubspot3
python
def get_associated(self, object_type, object_id, **options) -> List[Dict]: '\n get all engagements associated with the given object\n :param object_type: type of object to get associations on [CONTACT, COMPANY, DEAL]\n :param object_id: ID of the object to get associations on\n ' fin...
def get_all(self, **options) -> List[Dict]: 'get all engagements' finished = False output = [] query_limit = 250 offset = 0 while (not finished): batch = self._call('engagements/paged', method='GET', params={'limit': query_limit, 'offset': offset}, **options) output.extend(batch[...
-8,089,323,220,531,312,000
get all engagements
hubspot3/engagements.py
get_all
benaduggan/hubspot3
python
def get_all(self, **options) -> List[Dict]: finished = False output = [] query_limit = 250 offset = 0 while (not finished): batch = self._call('engagements/paged', method='GET', params={'limit': query_limit, 'offset': offset}, **options) output.extend(batch['results']) f...
def get_recently_modified(self, since, **options) -> List[Dict]: 'get recently modified engagements' finished = False output = [] query_limit = 100 offset = 0 while (not finished): batch = self._call('engagements/recent/modified', method='GET', params={'limit': query_limit, 'offset': off...
2,372,618,434,490,447,400
get recently modified engagements
hubspot3/engagements.py
get_recently_modified
benaduggan/hubspot3
python
def get_recently_modified(self, since, **options) -> List[Dict]: finished = False output = [] query_limit = 100 offset = 0 while (not finished): batch = self._call('engagements/recent/modified', method='GET', params={'limit': query_limit, 'offset': offset, 'since': since}, **options) ...
def __init__(self, batch_token=None): '\n V1ListItemsRequest - 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 ...
8,804,516,505,985,339,000
V1ListItemsRequest - 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.
squareconnect/models/v1_list_items_request.py
__init__
reduceus/connect-python-sdk
python
def __init__(self, batch_token=None): '\n V1ListItemsRequest - 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 batch_token(self): '\n Gets the batch_token of this V1ListItemsRequest.\n A pagination cursor to retrieve the next set of results for your original query to the endpoint.\n\n :return: The batch_token of this V1ListItemsRequest.\n :rtype: str\n ' return self._batc...
-8,642,177,761,913,007,000
Gets the batch_token of this V1ListItemsRequest. A pagination cursor to retrieve the next set of results for your original query to the endpoint. :return: The batch_token of this V1ListItemsRequest. :rtype: str
squareconnect/models/v1_list_items_request.py
batch_token
reduceus/connect-python-sdk
python
@property def batch_token(self): '\n Gets the batch_token of this V1ListItemsRequest.\n A pagination cursor to retrieve the next set of results for your original query to the endpoint.\n\n :return: The batch_token of this V1ListItemsRequest.\n :rtype: str\n ' return self._batc...
@batch_token.setter def batch_token(self, batch_token): '\n Sets the batch_token of this V1ListItemsRequest.\n A pagination cursor to retrieve the next set of results for your original query to the endpoint.\n\n :param batch_token: The batch_token of this V1ListItemsRequest.\n :type: str...
-956,991,087,329,217,000
Sets the batch_token of this V1ListItemsRequest. A pagination cursor to retrieve the next set of results for your original query to the endpoint. :param batch_token: The batch_token of this V1ListItemsRequest. :type: str
squareconnect/models/v1_list_items_request.py
batch_token
reduceus/connect-python-sdk
python
@batch_token.setter def batch_token(self, batch_token): '\n Sets the batch_token of this V1ListItemsRequest.\n A pagination cursor to retrieve the next set of results for your original query to the endpoint.\n\n :param batch_token: The batch_token of this V1ListItemsRequest.\n :type: str...
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
squareconnect/models/v1_list_items_request.py
to_dict
reduceus/connect-python-sdk
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
squareconnect/models/v1_list_items_request.py
to_str
reduceus/connect-python-sdk
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`
squareconnect/models/v1_list_items_request.py
__repr__
reduceus/connect-python-sdk
python
def __repr__(self): '\n \n ' return self.to_str()
def __eq__(self, other): '\n Returns true if both objects are equal\n ' return (self.__dict__ == other.__dict__)
3,599,733,221,149,238,300
Returns true if both objects are equal
squareconnect/models/v1_list_items_request.py
__eq__
reduceus/connect-python-sdk
python
def __eq__(self, other): '\n \n ' 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
squareconnect/models/v1_list_items_request.py
__ne__
reduceus/connect-python-sdk
python
def __ne__(self, other): '\n \n ' return (not (self == other))
def make_instance(self, include_optional): 'Test Queue\n include_option is a boolean, when False only required\n params are included, when True both required and\n optional params are included ' if include_optional: return Queue(_class='', items=[openapi_client.models.qu...
-8,577,424,846,062,078,000
Test Queue include_option is a boolean, when False only required params are included, when True both required and optional params are included
clients/python-legacy/generated/test/test_queue.py
make_instance
cliffano/jenkins-api-clients-generator
python
def make_instance(self, include_optional): 'Test Queue\n include_option is a boolean, when False only required\n params are included, when True both required and\n optional params are included ' if include_optional: return Queue(_class=, items=[openapi_client.models.queu...
def testQueue(self): 'Test Queue' inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True)
-1,662,886,051,552,567,000
Test Queue
clients/python-legacy/generated/test/test_queue.py
testQueue
cliffano/jenkins-api-clients-generator
python
def testQueue(self): inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True)
def index_of_masked_word(sentence, bert): "Return index of the masked word in `sentence` using `bert`'s' tokenizer.\n\n We use this function to calculate the linear distance between the target\n and controller as BERT sees it.\n\n Parameters\n ----------\n sentence : str\n\n Returns\n -------\n...
-5,210,766,759,479,877,000
Return index of the masked word in `sentence` using `bert`'s' tokenizer. We use this function to calculate the linear distance between the target and controller as BERT sees it. Parameters ---------- sentence : str Returns ------- int
src/experiment.py
index_of_masked_word
geoffbacon/does-bert-agree
python
def index_of_masked_word(sentence, bert): "Return index of the masked word in `sentence` using `bert`'s' tokenizer.\n\n We use this function to calculate the linear distance between the target\n and controller as BERT sees it.\n\n Parameters\n ----------\n sentence : str\n\n Returns\n -------\n...
def run(language, force_multilingual=False, fold_case=True, gpu=True): 'Run the experiment for `language`.\n\n Parameters\n ----------\n language : str\n force_multilingual : bool\n Whether to use the multilingual model even on English\n fold_case : bool\n Whether to ignore caseing diff...
-3,874,926,264,927,106,000
Run the experiment for `language`. Parameters ---------- language : str force_multilingual : bool Whether to use the multilingual model even on English fold_case : bool Whether to ignore caseing differences after making predictions gpu : bool Whether to run on GPU or not (useful for debugging) Returns ---...
src/experiment.py
run
geoffbacon/does-bert-agree
python
def run(language, force_multilingual=False, fold_case=True, gpu=True): 'Run the experiment for `language`.\n\n Parameters\n ----------\n language : str\n force_multilingual : bool\n Whether to use the multilingual model even on English\n fold_case : bool\n Whether to ignore caseing diff...
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): '\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n ' plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt....
-5,036,289,120,716,576,000
This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`.
TrainValue/multiclass_svm.py
plot_confusion_matrix
xuanthuong/DOU-SI
python
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): '\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n ' plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt....
def heading_deg(self): ' Calculate heading in degrees of vector from origin ' heading_rad = math.atan2(self.x, self.y) heading_deg_normalised = ((math.degrees(heading_rad) + 360) % 360) return heading_deg_normalised
4,203,066,159,195,690,500
Calculate heading in degrees of vector from origin
gym_jsbsim/properties.py
heading_deg
songhyonkim/gym-ai-pilot
python
def heading_deg(self): ' ' heading_rad = math.atan2(self.x, self.y) heading_deg_normalised = ((math.degrees(heading_rad) + 360) % 360) return heading_deg_normalised
def heading_deg_to(self, destination: 'GeodeticPosition') -> float: ' Determines heading in degrees of course between self and destination ' difference_vector = (destination - self) return difference_vector.heading_deg()
662,026,814,692,946,400
Determines heading in degrees of course between self and destination
gym_jsbsim/properties.py
heading_deg_to
songhyonkim/gym-ai-pilot
python
def heading_deg_to(self, destination: 'GeodeticPosition') -> float: ' ' difference_vector = (destination - self) return difference_vector.heading_deg()
@staticmethod def from_sim(sim: 'simulation.Simulation') -> 'GeodeticPosition': ' Return a GeodeticPosition object with lat and lon from simulation ' lat_deg = sim[lat_geod_deg] lon_deg = sim[lng_geoc_deg] return GeodeticPosition(lat_deg, lon_deg)
6,759,532,399,933,314,000
Return a GeodeticPosition object with lat and lon from simulation
gym_jsbsim/properties.py
from_sim
songhyonkim/gym-ai-pilot
python
@staticmethod def from_sim(sim: 'simulation.Simulation') -> 'GeodeticPosition': ' ' lat_deg = sim[lat_geod_deg] lon_deg = sim[lng_geoc_deg] return GeodeticPosition(lat_deg, lon_deg)
def __sub__(self, other) -> Vector2: ' Returns difference between two coords as (delta_lat, delta_long) ' return Vector2((self.lon - other.lon), (self.lat - other.lat))
-3,347,112,684,996,750,300
Returns difference between two coords as (delta_lat, delta_long)
gym_jsbsim/properties.py
__sub__
songhyonkim/gym-ai-pilot
python
def __sub__(self, other) -> Vector2: ' ' return Vector2((self.lon - other.lon), (self.lat - other.lat))
@pytest.fixture def mock_publish(hass): 'Initialize components.' (yield hass.loop.run_until_complete(async_mock_mqtt_component(hass)))
3,935,108,766,096,235,000
Initialize components.
tests/components/mqtt/test_switch.py
mock_publish
BobbyBleacher/home-assistant
python
@pytest.fixture def mock_publish(hass): (yield hass.loop.run_until_complete(async_mock_mqtt_component(hass)))
async def test_controlling_state_via_topic(hass, mock_publish): 'Test the controlling state via topic.' assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'payload_on': 1, 'payload_off': 0}...
8,155,222,178,456,217,000
Test the controlling state via topic.
tests/components/mqtt/test_switch.py
test_controlling_state_via_topic
BobbyBleacher/home-assistant
python
async def test_controlling_state_via_topic(hass, mock_publish): assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'payload_on': 1, 'payload_off': 0}})) state = hass.states.get('switch...
async def test_sending_mqtt_commands_and_optimistic(hass, mock_publish): 'Test the sending MQTT commands in optimistic mode.' fake_state = ha.State('switch.test', 'on') with patch('homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state', return_value=mock_coro(fake_state)): assert (a...
-1,817,929,223,250,078,200
Test the sending MQTT commands in optimistic mode.
tests/components/mqtt/test_switch.py
test_sending_mqtt_commands_and_optimistic
BobbyBleacher/home-assistant
python
async def test_sending_mqtt_commands_and_optimistic(hass, mock_publish): fake_state = ha.State('switch.test', 'on') with patch('homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state', return_value=mock_coro(fake_state)): assert (await async_setup_component(hass, switch.DOMAIN, {swi...
async def test_controlling_state_via_topic_and_json_message(hass, mock_publish): 'Test the controlling state via topic and JSON message.' assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', ...
-2,006,936,702,478,254,000
Test the controlling state via topic and JSON message.
tests/components/mqtt/test_switch.py
test_controlling_state_via_topic_and_json_message
BobbyBleacher/home-assistant
python
async def test_controlling_state_via_topic_and_json_message(hass, mock_publish): assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'payload_on': 'beer on', 'payload_off': 'beer off', 'val...
async def test_default_availability_payload(hass, mock_publish): 'Test the availability payload.' assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'availability_topic': 'availability_topi...
-3,038,129,219,349,842,400
Test the availability payload.
tests/components/mqtt/test_switch.py
test_default_availability_payload
BobbyBleacher/home-assistant
python
async def test_default_availability_payload(hass, mock_publish): assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'availability_topic': 'availability_topic', 'payload_on': 1, 'payload_of...
async def test_custom_availability_payload(hass, mock_publish): 'Test the availability payload.' assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'availability_topic': 'availability_topic...
2,127,276,169,409,135,600
Test the availability payload.
tests/components/mqtt/test_switch.py
test_custom_availability_payload
BobbyBleacher/home-assistant
python
async def test_custom_availability_payload(hass, mock_publish): assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'availability_topic': 'availability_topic', 'payload_on': 1, 'payload_off...
async def test_custom_state_payload(hass, mock_publish): 'Test the state payload.' assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'payload_on': 1, 'payload_off': 0, 'state_on': 'HIGH', ...
-7,688,893,017,872,148,000
Test the state payload.
tests/components/mqtt/test_switch.py
test_custom_state_payload
BobbyBleacher/home-assistant
python
async def test_custom_state_payload(hass, mock_publish): assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'payload_on': 1, 'payload_off': 0, 'state_on': 'HIGH', 'state_off': 'LOW'}})) ...
async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock): 'Test the setting of attribute via MQTT with JSON payload.' assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'command_topic': 'test-topic', 'json_attributes_topic': 'attr-topic'}...
177,271,805,859,749,000
Test the setting of attribute via MQTT with JSON payload.
tests/components/mqtt/test_switch.py
test_setting_attribute_via_mqtt_json_message
BobbyBleacher/home-assistant
python
async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock): assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'command_topic': 'test-topic', 'json_attributes_topic': 'attr-topic'}})) async_fire_mqtt_message(hass, 'attr-topic', '{ "val...
async def test_update_with_json_attrs_not_dict(hass, mqtt_mock, caplog): 'Test attributes get extracted from a JSON result.' assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'command_topic': 'test-topic', 'json_attributes_topic': 'attr-topic'}})) ...
-1,280,874,276,873,739,300
Test attributes get extracted from a JSON result.
tests/components/mqtt/test_switch.py
test_update_with_json_attrs_not_dict
BobbyBleacher/home-assistant
python
async def test_update_with_json_attrs_not_dict(hass, mqtt_mock, caplog): assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'command_topic': 'test-topic', 'json_attributes_topic': 'attr-topic'}})) async_fire_mqtt_message(hass, 'attr-topic', '[ "lis...
async def test_update_with_json_attrs_bad_JSON(hass, mqtt_mock, caplog): 'Test attributes get extracted from a JSON result.' assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'command_topic': 'test-topic', 'json_attributes_topic': 'attr-topic'}})) ...
586,962,458,147,496,800
Test attributes get extracted from a JSON result.
tests/components/mqtt/test_switch.py
test_update_with_json_attrs_bad_JSON
BobbyBleacher/home-assistant
python
async def test_update_with_json_attrs_bad_JSON(hass, mqtt_mock, caplog): assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'command_topic': 'test-topic', 'json_attributes_topic': 'attr-topic'}})) async_fire_mqtt_message(hass, 'attr-topic', 'This i...
async def test_discovery_update_attr(hass, mqtt_mock, caplog): 'Test update of discovered MQTTAttributes.' entry = MockConfigEntry(domain=mqtt.DOMAIN) (await async_start(hass, 'homeassistant', {}, entry)) data1 = '{ "name": "Beer", "command_topic": "test_topic", "json_attributes_topic": "attr-topic1" ...
-5,929,376,502,707,091,000
Test update of discovered MQTTAttributes.
tests/components/mqtt/test_switch.py
test_discovery_update_attr
BobbyBleacher/home-assistant
python
async def test_discovery_update_attr(hass, mqtt_mock, caplog): entry = MockConfigEntry(domain=mqtt.DOMAIN) (await async_start(hass, 'homeassistant', {}, entry)) data1 = '{ "name": "Beer", "command_topic": "test_topic", "json_attributes_topic": "attr-topic1" }' data2 = '{ "name": "Beer", "command...
async def test_unique_id(hass): 'Test unique id option only creates one switch per unique_id.' (await async_mock_mqtt_component(hass)) assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: [{'platform': 'mqtt', 'name': 'Test 1', 'state_topic': 'test-topic', 'command_topic': 'command-topic...
5,170,561,312,111,095,000
Test unique id option only creates one switch per unique_id.
tests/components/mqtt/test_switch.py
test_unique_id
BobbyBleacher/home-assistant
python
async def test_unique_id(hass): (await async_mock_mqtt_component(hass)) assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: [{'platform': 'mqtt', 'name': 'Test 1', 'state_topic': 'test-topic', 'command_topic': 'command-topic', 'unique_id': 'TOTALLY_UNIQUE'}, {'platform': 'mqtt', 'name'...
async def test_discovery_removal_switch(hass, mqtt_mock, caplog): 'Test removal of discovered switch.' entry = MockConfigEntry(domain=mqtt.DOMAIN) (await async_start(hass, 'homeassistant', {}, entry)) data = '{ "name": "Beer", "state_topic": "test_topic", "command_topic": "test_topic" }' async_fir...
1,035,768,021,042,002,600
Test removal of discovered switch.
tests/components/mqtt/test_switch.py
test_discovery_removal_switch
BobbyBleacher/home-assistant
python
async def test_discovery_removal_switch(hass, mqtt_mock, caplog): entry = MockConfigEntry(domain=mqtt.DOMAIN) (await async_start(hass, 'homeassistant', {}, entry)) data = '{ "name": "Beer", "state_topic": "test_topic", "command_topic": "test_topic" }' async_fire_mqtt_message(hass, 'homeassistant/...
async def test_discovery_update_switch(hass, mqtt_mock, caplog): 'Test update of discovered switch.' entry = MockConfigEntry(domain=mqtt.DOMAIN) (await async_start(hass, 'homeassistant', {}, entry)) data1 = '{ "name": "Beer", "state_topic": "test_topic", "command_topic": "test_topic" }' data2 = '{...
-1,301,209,773,686,279,000
Test update of discovered switch.
tests/components/mqtt/test_switch.py
test_discovery_update_switch
BobbyBleacher/home-assistant
python
async def test_discovery_update_switch(hass, mqtt_mock, caplog): entry = MockConfigEntry(domain=mqtt.DOMAIN) (await async_start(hass, 'homeassistant', {}, entry)) data1 = '{ "name": "Beer", "state_topic": "test_topic", "command_topic": "test_topic" }' data2 = '{ "name": "Milk", "state_topic": "t...
async def test_discovery_broken(hass, mqtt_mock, caplog): 'Test handling of bad discovery message.' entry = MockConfigEntry(domain=mqtt.DOMAIN) (await async_start(hass, 'homeassistant', {}, entry)) data1 = '{ "name": "Beer" }' data2 = '{ "name": "Milk", "state_topic": "test_topic", "command_topic"...
959,381,512,160,867,500
Test handling of bad discovery message.
tests/components/mqtt/test_switch.py
test_discovery_broken
BobbyBleacher/home-assistant
python
async def test_discovery_broken(hass, mqtt_mock, caplog): entry = MockConfigEntry(domain=mqtt.DOMAIN) (await async_start(hass, 'homeassistant', {}, entry)) data1 = '{ "name": "Beer" }' data2 = '{ "name": "Milk", "state_topic": "test_topic", "command_topic": "test_topic" }' async_fire_mqtt_mes...
async def test_entity_device_info_with_identifier(hass, mqtt_mock): 'Test MQTT switch device registry integration.' entry = MockConfigEntry(domain=mqtt.DOMAIN) entry.add_to_hass(hass) (await async_start(hass, 'homeassistant', {}, entry)) registry = (await hass.helpers.device_registry.async_get_regis...
9,132,497,107,045,344,000
Test MQTT switch device registry integration.
tests/components/mqtt/test_switch.py
test_entity_device_info_with_identifier
BobbyBleacher/home-assistant
python
async def test_entity_device_info_with_identifier(hass, mqtt_mock): entry = MockConfigEntry(domain=mqtt.DOMAIN) entry.add_to_hass(hass) (await async_start(hass, 'homeassistant', {}, entry)) registry = (await hass.helpers.device_registry.async_get_registry()) data = json.dumps({'platform': 'mqtt...
async def test_entity_device_info_update(hass, mqtt_mock): 'Test device registry update.' entry = MockConfigEntry(domain=mqtt.DOMAIN) entry.add_to_hass(hass) (await async_start(hass, 'homeassistant', {}, entry)) registry = (await hass.helpers.device_registry.async_get_registry()) config = {'plat...
1,981,086,579,315,102,700
Test device registry update.
tests/components/mqtt/test_switch.py
test_entity_device_info_update
BobbyBleacher/home-assistant
python
async def test_entity_device_info_update(hass, mqtt_mock): entry = MockConfigEntry(domain=mqtt.DOMAIN) entry.add_to_hass(hass) (await async_start(hass, 'homeassistant', {}, entry)) registry = (await hass.helpers.device_registry.async_get_registry()) config = {'platform': 'mqtt', 'name': 'Test 1...
async def test_entity_id_update(hass, mqtt_mock): 'Test MQTT subscriptions are managed when entity_id is updated.' registry = mock_registry(hass, {}) mock_mqtt = (await async_mock_mqtt_component(hass)) assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: [{'platform': 'mqtt', 'name':...
2,420,902,222,189,967,000
Test MQTT subscriptions are managed when entity_id is updated.
tests/components/mqtt/test_switch.py
test_entity_id_update
BobbyBleacher/home-assistant
python
async def test_entity_id_update(hass, mqtt_mock): registry = mock_registry(hass, {}) mock_mqtt = (await async_mock_mqtt_component(hass)) assert (await async_setup_component(hass, switch.DOMAIN, {switch.DOMAIN: [{'platform': 'mqtt', 'name': 'beer', 'state_topic': 'test-topic', 'command_topic': 'command-...
def greedy_feedback(distmat, q_pids, g_pids, positive_indices, negative_indices, inplace=True): '\n Update positive_indices, negative_indices with one round of feedback. Provide feedback for top-ranked gallery.\n Note that distmat is corrupted if inplace=True.\n\n :param distmat: q x g Tensor (adjusted que...
4,714,801,363,259,745,000
Update positive_indices, negative_indices with one round of feedback. Provide feedback for top-ranked gallery. Note that distmat is corrupted if inplace=True. :param distmat: q x g Tensor (adjusted query to gallery) :param q_pids: q :param g_pids: g :param positive_indices: q x g :param negative_indices: q x g :return...
hitl/feedback.py
greedy_feedback
itsnamgyu/reid-metric
python
def greedy_feedback(distmat, q_pids, g_pids, positive_indices, negative_indices, inplace=True): '\n Update positive_indices, negative_indices with one round of feedback. Provide feedback for top-ranked gallery.\n Note that distmat is corrupted if inplace=True.\n\n :param distmat: q x g Tensor (adjusted que...
def naive_round(qf, gf, q_pids, g_pids, positive_indices=None, negative_indices=None, inplace=True, previous_distmat=None, device=None): '\n qf: q x m\n gf: g x m\n q_pids: q\n g_pids: g\n positive_indices: q x g\n negative_indices: q x g\n previous_distmat: adjusted distmat (== compute_distmat...
-8,445,332,685,900,629,000
qf: q x m gf: g x m q_pids: q g_pids: g positive_indices: q x g negative_indices: q x g previous_distmat: adjusted distmat (== compute_distmat(qf, gf) only at init)
hitl/feedback.py
naive_round
itsnamgyu/reid-metric
python
def naive_round(qf, gf, q_pids, g_pids, positive_indices=None, negative_indices=None, inplace=True, previous_distmat=None, device=None): '\n qf: q x m\n gf: g x m\n q_pids: q\n g_pids: g\n positive_indices: q x g\n negative_indices: q x g\n previous_distmat: adjusted distmat (== compute_distmat...
@staticmethod def _read_image_and_resize(img_entry: Union[(str, 'numpy.array')], img_width: int, img_height: int, should_resize: bool, num_channels: int, resize_method: str, user_specified_num_channels: int): "\n :param img_entry Union[str, 'numpy.array']: if str file path to the\n image else ...
3,679,320,613,820,813,300
:param img_entry Union[str, 'numpy.array']: if str file path to the image else numpy.array of the image itself :param img_width: expected width of the image :param img_height: expected height of the image :param should_resize: Should the image be resized? :param resize_method: type of resizing method :param num...
ludwig/features/image_feature.py
_read_image_and_resize
Yard1/ludwig
python
@staticmethod def _read_image_and_resize(img_entry: Union[(str, 'numpy.array')], img_width: int, img_height: int, should_resize: bool, num_channels: int, resize_method: str, user_specified_num_channels: int): "\n :param img_entry Union[str, 'numpy.array']: if str file path to the\n image else ...
@staticmethod def _finalize_preprocessing_parameters(preprocessing_parameters: dict, first_img_entry: Union[(str, 'numpy.array')], src_path: str, input_feature_col: np.array): '\n Helper method to determine the height, width and number of channels for\n preprocessing the image data. This is achieved b...
6,889,128,509,968,942,000
Helper method to determine the height, width and number of channels for preprocessing the image data. This is achieved by looking at the parameters provided by the user. When there are some missing parameters, we fall back on to the first image in the dataset. The assumption being that all the images in the data are ex...
ludwig/features/image_feature.py
_finalize_preprocessing_parameters
Yard1/ludwig
python
@staticmethod def _finalize_preprocessing_parameters(preprocessing_parameters: dict, first_img_entry: Union[(str, 'numpy.array')], src_path: str, input_feature_col: np.array): '\n Helper method to determine the height, width and number of channels for\n preprocessing the image data. This is achieved b...
@lD.log((logBase + '.getAllData')) def getAllData(logger, query, values=None, dbName=None): 'query data from the database\n \n Query the data over here. If there is a problem with the data, it is going \n to return the value of None, and log the error. Your program needs to check \n whether there was a...
-2,191,366,141,799,859,500
query data from the database Query the data over here. If there is a problem with the data, it is going to return the value of None, and log the error. Your program needs to check whether there was an error with the query by checking for a None return value. Note that the location of the dataabses are assumed to b...
src/lib/databaseIO/sqLiteIO.py
getAllData
madelinelimm/newcookiectest
python
@lD.log((logBase + '.getAllData')) def getAllData(logger, query, values=None, dbName=None): 'query data from the database\n \n Query the data over here. If there is a problem with the data, it is going \n to return the value of None, and log the error. Your program needs to check \n whether there was a...
@lD.log((logBase + '.getDataIterator')) def getDataIterator(logger, query, values=None, chunks=100, dbName=None): 'Create an iterator from a largish query\n \n This is a generator that returns values in chunks of chunksize ``chunks``.\n \n Parameters\n ----------\n logger : {logging.logger}\n ...
4,075,178,327,135,300,000
Create an iterator from a largish query This is a generator that returns values in chunks of chunksize ``chunks``. Parameters ---------- logger : {logging.logger} logging element query : {str} The query to be made to the databse values : {tuple or list-like}, optional Additional values to be passed to th...
src/lib/databaseIO/sqLiteIO.py
getDataIterator
madelinelimm/newcookiectest
python
@lD.log((logBase + '.getDataIterator')) def getDataIterator(logger, query, values=None, chunks=100, dbName=None): 'Create an iterator from a largish query\n \n This is a generator that returns values in chunks of chunksize ``chunks``.\n \n Parameters\n ----------\n logger : {logging.logger}\n ...
@lD.log((logBase + '.getSingleDataIterator')) def getSingleDataIterator(logger, query, values=None, dbName=None): 'Create an iterator from a largish query\n \n This is a generator that returns values in chunks of chunksize 1.\n \n Parameters\n ----------\n logger : {logging.logger}\n loggin...
1,734,528,024,462,529,000
Create an iterator from a largish query This is a generator that returns values in chunks of chunksize 1. Parameters ---------- logger : {logging.logger} logging element query : {str} The query to be made to the databse values : {tuple or list-like}, optional Additional values to be passed to the query (...
src/lib/databaseIO/sqLiteIO.py
getSingleDataIterator
madelinelimm/newcookiectest
python
@lD.log((logBase + '.getSingleDataIterator')) def getSingleDataIterator(logger, query, values=None, dbName=None): 'Create an iterator from a largish query\n \n This is a generator that returns values in chunks of chunksize 1.\n \n Parameters\n ----------\n logger : {logging.logger}\n loggin...
@lD.log((logBase + '.commitData')) def commitData(logger, query, values=None, dbName=None): 'query data from the database\n \n Query the data over here. If there is a problem with\n the data, it is going to return the value of ``None``, and\n log the error. Your program needs to check whether \n ther...
5,148,623,577,417,340,000
query data from the database Query the data over here. If there is a problem with the data, it is going to return the value of ``None``, and log the error. Your program needs to check whether there was an error with the query by checking for a ``None`` return value Parameters ---------- logger : {logging.logger} ...
src/lib/databaseIO/sqLiteIO.py
commitData
madelinelimm/newcookiectest
python
@lD.log((logBase + '.commitData')) def commitData(logger, query, values=None, dbName=None): 'query data from the database\n \n Query the data over here. If there is a problem with\n the data, it is going to return the value of ``None``, and\n log the error. Your program needs to check whether \n ther...
@lD.log((logBase + '.commitDataList')) def commitDataList(logger, query, values, dbName=None): 'query data from the database\n \n Query the data over here. If there is a problem with\n the data, it is going to return the value of None, and\n log the error. Your program needs to check whether \n there...
4,836,143,481,288,761,000
query data from the database Query the data over here. If there is a problem with the data, it is going to return the value of None, and log the error. Your program needs to check whether there was an error with the query by checking for a ``None`` return value Parameters ---------- logger : {logging.logger} log...
src/lib/databaseIO/sqLiteIO.py
commitDataList
madelinelimm/newcookiectest
python
@lD.log((logBase + '.commitDataList')) def commitDataList(logger, query, values, dbName=None): 'query data from the database\n \n Query the data over here. If there is a problem with\n the data, it is going to return the value of None, and\n log the error. Your program needs to check whether \n there...
def a_vector_OLS_and_LP(m_dict, bounds, boundedness, term_limit, term_lower_bound, fit_method, alpha, diff_error=0.001, diff_step=0.001): " Main workhorse function of pymetalog package.\n Called during metalog.__init__ method call.\n\n Args:\n m_dict (:obj:`dict` with keys ['params', 'dataValues', ...
6,141,652,472,069,626,000
Main workhorse function of pymetalog package. Called during metalog.__init__ method call. Args: m_dict (:obj:`dict` with keys ['params', 'dataValues', 'Y']): Initialized output_dict variable from metalog class. - m_dict['params']: (:obj:`dict` with keys ['bounds', 'boundedness', 'term_limit', 'term_low...
pymetalog/a_vector.py
a_vector_OLS_and_LP
sives5/pymetalog
python
def a_vector_OLS_and_LP(m_dict, bounds, boundedness, term_limit, term_lower_bound, fit_method, alpha, diff_error=0.001, diff_step=0.001): " Main workhorse function of pymetalog package.\n Called during metalog.__init__ method call.\n\n Args:\n m_dict (:obj:`dict` with keys ['params', 'dataValues', ...
def a_vector_LP(m_dict, term_limit, term_lower_bound, diff_error=0.001, diff_step=0.001): 'TODO: write docstring\n\n ' cnames = np.array([]) for i in range(term_lower_bound, (term_limit + 1)): Y = m_dict['Y'].iloc[:, 0:i] z = m_dict['dataValues']['z'] Y_neg = (- Y) new_Y =...
-768,892,783,951,292,000
TODO: write docstring
pymetalog/a_vector.py
a_vector_LP
sives5/pymetalog
python
def a_vector_LP(m_dict, term_limit, term_lower_bound, diff_error=0.001, diff_step=0.001): '\n\n ' cnames = np.array([]) for i in range(term_lower_bound, (term_limit + 1)): Y = m_dict['Y'].iloc[:, 0:i] z = m_dict['dataValues']['z'] Y_neg = (- Y) new_Y = pd.DataFrame({'y1': ...
def a_vector_MLE(a, y, term, m_dict, bounds, boundedness): 'TODO: write docstring\n\n ' ym = [newtons_method_metalog(a, xi, term, bounds, boundedness) for xi in m_dict['dataValues']['x']] def MLE_quantile_constraints(x): M = [quantileMetalog(x[:term], yi, term, bounds=bounds, boundedness=bounded...
7,889,138,763,662,265,000
TODO: write docstring
pymetalog/a_vector.py
a_vector_MLE
sives5/pymetalog
python
def a_vector_MLE(a, y, term, m_dict, bounds, boundedness): '\n\n ' ym = [newtons_method_metalog(a, xi, term, bounds, boundedness) for xi in m_dict['dataValues']['x']] def MLE_quantile_constraints(x): M = [quantileMetalog(x[:term], yi, term, bounds=bounds, boundedness=boundedness) for yi in x[ter...
def test_alap_pass(self): 'Test ALAP scheduling.' q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.u2(3.14, 1.57, q[0]) qc.u2(0.5, 0.25, q[1]) qc.barrier(q[1]) qc.u2(0.5, 0.25, q[1]) qc.barrier(q[0], q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) sch...
-1,342,313,367,346,715,600
Test ALAP scheduling.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_alap_pass
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_alap_pass(self): q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.u2(3.14, 1.57, q[0]) qc.u2(0.5, 0.25, q[1]) qc.barrier(q[1]) qc.u2(0.5, 0.25, q[1]) qc.barrier(q[0], q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self....
def test_alap_with_barriers(self): 'Test that ALAP respects barriers on new qubits.' q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.u2(0, 0, q[0]) qc.barrier(q[0], q[1]) qc.u2(0, 0, q[1]) sched = schedule(qc, self.backend, method='alap') expected = Sched...
-8,490,361,027,831,596,000
Test that ALAP respects barriers on new qubits.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_alap_with_barriers
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_alap_with_barriers(self): q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.u2(0, 0, q[0]) qc.barrier(q[0], q[1]) qc.u2(0, 0, q[1]) sched = schedule(qc, self.backend, method='alap') expected = Schedule(self.cmd_def.get('u2', [0], 0, 0), (28, self....
def test_alap_aligns_end(self): 'Test that ALAP always acts as though there is a final global barrier.' q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.u3(0, 0, 0, q[0]) qc.u2(0, 0, q[1]) sched = schedule(qc, self.backend, method='alap') expected_sched = Sche...
7,536,511,695,377,579,000
Test that ALAP always acts as though there is a final global barrier.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_alap_aligns_end
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_alap_aligns_end(self): q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.u3(0, 0, 0, q[0]) qc.u2(0, 0, q[1]) sched = schedule(qc, self.backend, method='alap') expected_sched = Schedule(self.cmd_def.get('u2', [1], 0, 0), (26, self.cmd_def.get('u3', [0]...
def test_asap_pass(self): 'Test ASAP scheduling.' q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.u2(3.14, 1.57, q[0]) qc.u2(0.5, 0.25, q[1]) qc.barrier(q[1]) qc.u2(0.5, 0.25, q[1]) qc.barrier(q[0], q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) sch...
-1,838,080,591,864,963,300
Test ASAP scheduling.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_asap_pass
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_asap_pass(self): q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.u2(3.14, 1.57, q[0]) qc.u2(0.5, 0.25, q[1]) qc.barrier(q[1]) qc.u2(0.5, 0.25, q[1]) qc.barrier(q[0], q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self....
def test_alap_resource_respecting(self): "Test that the ALAP pass properly respects busy resources when backwards scheduling.\n For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits'\n timeline." q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircui...
-4,846,775,682,320,039,000
Test that the ALAP pass properly respects busy resources when backwards scheduling. For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits' timeline.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_alap_resource_respecting
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_alap_resource_respecting(self): "Test that the ALAP pass properly respects busy resources when backwards scheduling.\n For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits'\n timeline." q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircui...
def test_cmd_def_schedules_unaltered(self): "Test that forward scheduling doesn't change relative timing with a command." q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) sched1 = schedule(qc, self.backend, method='as_soon_as_possible') sched2 = sch...
6,633,446,773,433,102,000
Test that forward scheduling doesn't change relative timing with a command.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_cmd_def_schedules_unaltered
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_cmd_def_schedules_unaltered(self): q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) sched1 = schedule(qc, self.backend, method='as_soon_as_possible') sched2 = schedule(qc, self.backend, method='as_late_as_possible') self.assertEqual(sc...
def test_measure_combined(self): '\n Test to check for measure on the same qubit which generated another measure schedule.\n\n The measures on different qubits are combined, but measures on the same qubit\n adds another measure to the schedule.\n ' q = QuantumRegister(2) c = Clas...
-8,182,329,726,274,524,000
Test to check for measure on the same qubit which generated another measure schedule. The measures on different qubits are combined, but measures on the same qubit adds another measure to the schedule.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_measure_combined
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_measure_combined(self): '\n Test to check for measure on the same qubit which generated another measure schedule.\n\n The measures on different qubits are combined, but measures on the same qubit\n adds another measure to the schedule.\n ' q = QuantumRegister(2) c = Clas...
def test_3q_schedule(self): 'Test a schedule that was recommended by David McKay :D ' backend = FakeOpenPulse3Q() cmd_def = backend.defaults().build_cmd_def() q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.u2(0.778, 0.122, q[2]) qc.u3(3...
-2,168,647,660,574,186,000
Test a schedule that was recommended by David McKay :D
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_3q_schedule
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_3q_schedule(self): ' ' backend = FakeOpenPulse3Q() cmd_def = backend.defaults().build_cmd_def() q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.u2(0.778, 0.122, q[2]) qc.u3(3.14, 1.57, 0.0, q[0]) qc.u2(3.14, 1.57, q[1]) ...
def test_schedule_multi(self): 'Test scheduling multiple circuits at once.' q = QuantumRegister(2) c = ClassicalRegister(2) qc0 = QuantumCircuit(q, c) qc0.cx(q[0], q[1]) qc1 = QuantumCircuit(q, c) qc1.cx(q[0], q[1]) schedules = schedule([qc0, qc1], self.backend) expected_insts = sche...
2,331,117,832,550,685,000
Test scheduling multiple circuits at once.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_schedule_multi
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_schedule_multi(self): q = QuantumRegister(2) c = ClassicalRegister(2) qc0 = QuantumCircuit(q, c) qc0.cx(q[0], q[1]) qc1 = QuantumCircuit(q, c) qc1.cx(q[0], q[1]) schedules = schedule([qc0, qc1], self.backend) expected_insts = schedule(qc0, self.backend).instructions sel...
def test_circuit_name_kept(self): 'Test that the new schedule gets its name from the circuit.' q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c, name='CIRCNAME') qc.cx(q[0], q[1]) sched = schedule(qc, self.backend, method='asap') self.assertEqual(sched.name, qc.name) ...
4,632,417,592,669,203,000
Test that the new schedule gets its name from the circuit.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_circuit_name_kept
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_circuit_name_kept(self): q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c, name='CIRCNAME') qc.cx(q[0], q[1]) sched = schedule(qc, self.backend, method='asap') self.assertEqual(sched.name, qc.name) sched = schedule(qc, self.backend, method='alap') se...
def test_can_add_gates_into_free_space(self): 'The scheduler does some time bookkeeping to know when qubits are free to be\n scheduled. Make sure this works for qubits that are used in the future. This was\n a bug, uncovered by this example:\n\n q0 = - - - - |X|\n q1 = |X| |u2| |X...
-2,730,611,971,349,152,300
The scheduler does some time bookkeeping to know when qubits are free to be scheduled. Make sure this works for qubits that are used in the future. This was a bug, uncovered by this example: q0 = - - - - |X| q1 = |X| |u2| |X| In ALAP scheduling, the next operation on qubit 0 would be added at t=0 rather than i...
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_can_add_gates_into_free_space
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_can_add_gates_into_free_space(self): 'The scheduler does some time bookkeeping to know when qubits are free to be\n scheduled. Make sure this works for qubits that are used in the future. This was\n a bug, uncovered by this example:\n\n q0 = - - - - |X|\n q1 = |X| |u2| |X...
def test_barriers_in_middle(self): 'As a follow on to `test_can_add_gates_into_free_space`, similar issues\n arose for barriers, specifically.\n ' qr = QuantumRegister(2) qc = QuantumCircuit(qr) for i in range(2): qc.u2(0, 0, [qr[i]]) qc.barrier(qr[i]) qc.u1(3.14, [...
-3,675,416,939,452,719,600
As a follow on to `test_can_add_gates_into_free_space`, similar issues arose for barriers, specifically.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_barriers_in_middle
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_barriers_in_middle(self): 'As a follow on to `test_can_add_gates_into_free_space`, similar issues\n arose for barriers, specifically.\n ' qr = QuantumRegister(2) qc = QuantumCircuit(qr) for i in range(2): qc.u2(0, 0, [qr[i]]) qc.barrier(qr[i]) qc.u1(3.14, [...
def test_only_needed_measures(self): 'Test that `MeasureChannel`s are only added for measured qubits.' q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.measure(q[1], c[1]) sched_all_channels = schedule(qc, self.backend, method='as_soon_as_possible').channels delet...
-2,662,223,638,239,911,000
Test that `MeasureChannel`s are only added for measured qubits.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_only_needed_measures
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_only_needed_measures(self): q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.measure(q[1], c[1]) sched_all_channels = schedule(qc, self.backend, method='as_soon_as_possible').channels deleted_channels = [MeasureChannel(0)] self.assertNotIn(sched_all_...
def test_user_mapping_for_memslots(self): '\n Test that the new schedule only has required `MeasureChannel`s and that the\n `MemorySlot`s are mapped according to the input circuit.\n ' q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.measure(q[0], c[1...
-4,664,338,327,747,616,000
Test that the new schedule only has required `MeasureChannel`s and that the `MemorySlot`s are mapped according to the input circuit.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_user_mapping_for_memslots
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_user_mapping_for_memslots(self): '\n Test that the new schedule only has required `MeasureChannel`s and that the\n `MemorySlot`s are mapped according to the input circuit.\n ' q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.measure(q[0], c[1...
def test_user_mapping_for_memslots_3Q(self): 'Test measuring two of three qubits.' backend = FakeOpenPulse3Q() cmd_def = backend.defaults().build_cmd_def() q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.measure(q[1], c[2]) qc.measure(q[2], c[0]) sched = ...
5,272,640,111,508,526,000
Test measuring two of three qubits.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_user_mapping_for_memslots_3Q
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_user_mapping_for_memslots_3Q(self): backend = FakeOpenPulse3Q() cmd_def = backend.defaults().build_cmd_def() q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.measure(q[1], c[2]) qc.measure(q[2], c[0]) sched = schedule(qc, backend) expected = ...
def test_multiple_measure_in_3Q(self): 'Test multiple measure, user memslot mapping, 3Q.' backend = FakeOpenPulse3Q() cmd_def = backend.defaults().build_cmd_def() q = QuantumRegister(3) c = ClassicalRegister(5) qc = QuantumCircuit(q, c) qc.measure(q[0], c[2]) qc.measure(q[0], c[4]) s...
2,211,987,329,034,881,300
Test multiple measure, user memslot mapping, 3Q.
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
test_multiple_measure_in_3Q
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_multiple_measure_in_3Q(self): backend = FakeOpenPulse3Q() cmd_def = backend.defaults().build_cmd_def() q = QuantumRegister(3) c = ClassicalRegister(5) qc = QuantumCircuit(q, c) qc.measure(q[0], c[2]) qc.measure(q[0], c[4]) sched = schedule(qc, backend) expected = Schedu...
def dav_index(context, data): 'List files in a WebDAV directory.' url = data.get('url') context.log.info(('Fetching WebDAV path: %s' % url)) result = context.http.request('PROPFIND', url) for resp in result.xml.findall('./{DAV:}response'): href = resp.findtext('./{DAV:}href') if (hre...
8,402,320,049,363,877,000
List files in a WebDAV directory.
memorious/operations/webdav.py
dav_index
Rosencrantz/memorious
python
def dav_index(context, data): url = data.get('url') context.log.info(('Fetching WebDAV path: %s' % url)) result = context.http.request('PROPFIND', url) for resp in result.xml.findall('./{DAV:}response'): href = resp.findtext('./{DAV:}href') if (href is None): continue ...
def default_data_collator(features: List[InputDataClass]) -> Dict[(str, torch.Tensor)]: "\n Very simple data collator that simply collates batches of dict-like objects and performs special handling for\n potential keys named:\n\n - ``label``: handles a single value (int or float) per object\n - ...
-5,154,268,821,003,138,000
Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named: - ``label``: handles a single value (int or float) per object - ``label_ids``: handles a list of values per object Does not do any additional preprocessing: property names of the...
src/transformers/data/data_collator.py
default_data_collator
21jun/transformers
python
def default_data_collator(features: List[InputDataClass]) -> Dict[(str, torch.Tensor)]: "\n Very simple data collator that simply collates batches of dict-like objects and performs special handling for\n potential keys named:\n\n - ``label``: handles a single value (int or float) per object\n - ...
def _collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int]=None): 'Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.' if isinstance(examples[0], (list, tuple)): examples = [torch.tensor(e, dtype=torch.long) for e in examples] length_of_fir...
9,111,441,324,026,435,000
Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.
src/transformers/data/data_collator.py
_collate_batch
21jun/transformers
python
def _collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int]=None): if isinstance(examples[0], (list, tuple)): examples = [torch.tensor(e, dtype=torch.long) for e in examples] length_of_first = examples[0].size(0) are_tensors_same_length = all(((x.size(0) == length_of_first) for x ...
def mask_tokens(self, inputs: torch.Tensor, special_tokens_mask: Optional[torch.Tensor]=None) -> Tuple[(torch.Tensor, torch.Tensor)]: '\n Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.\n ' labels = inputs.clone() probability_matrix = torch...
-6,466,449,275,945,545,000
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
src/transformers/data/data_collator.py
mask_tokens
21jun/transformers
python
def mask_tokens(self, inputs: torch.Tensor, special_tokens_mask: Optional[torch.Tensor]=None) -> Tuple[(torch.Tensor, torch.Tensor)]: '\n \n ' labels = inputs.clone() probability_matrix = torch.full(labels.shape, self.mlm_probability) if (special_tokens_mask is None): special_token...
def _whole_word_mask(self, input_tokens: List[str], max_predictions=512): '\n Get 0/1 labels for masked tokens with whole word mask proxy\n ' if (not isinstance(self.tokenizer, (BertTokenizer, BertTokenizerFast))): warnings.warn('DataCollatorForWholeWordMask is only suitable for BertTokeni...
-4,265,430,114,033,264,000
Get 0/1 labels for masked tokens with whole word mask proxy
src/transformers/data/data_collator.py
_whole_word_mask
21jun/transformers
python
def _whole_word_mask(self, input_tokens: List[str], max_predictions=512): '\n \n ' if (not isinstance(self.tokenizer, (BertTokenizer, BertTokenizerFast))): warnings.warn('DataCollatorForWholeWordMask is only suitable for BertTokenizer-like tokenizers.Please refer to the documentation for m...
def mask_tokens(self, inputs: torch.Tensor, mask_labels: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor)]: "\n Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set\n 'mask_labels' means we use whole word mask (wwm), we directly mask idxs accordi...
-6,416,139,270,136,281,000
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set 'mask_labels' means we use whole word mask (wwm), we directly mask idxs according to it's ref.
src/transformers/data/data_collator.py
mask_tokens
21jun/transformers
python
def mask_tokens(self, inputs: torch.Tensor, mask_labels: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor)]: "\n Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set\n 'mask_labels' means we use whole word mask (wwm), we directly mask idxs accordi...
def mask_tokens(self, inputs: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]: '\n Prepare masked tokens inputs/labels/attention_mask for masked language modeling: 80% MASK, 10% random, 10%\n original. N-gram not applied yet.\n ' if (self.tokenizer.mask_token is None): ...
6,151,136,398,149,454,000
Prepare masked tokens inputs/labels/attention_mask for masked language modeling: 80% MASK, 10% random, 10% original. N-gram not applied yet.
src/transformers/data/data_collator.py
mask_tokens
21jun/transformers
python
def mask_tokens(self, inputs: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]: '\n Prepare masked tokens inputs/labels/attention_mask for masked language modeling: 80% MASK, 10% random, 10%\n original. N-gram not applied yet.\n ' if (self.tokenizer.mask_token is None): ...
def mask_tokens(self, inputs: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)]: '\n The masked tokens to be predicted for a particular sequence are determined by the following algorithm:\n\n 0. Start from the beginning of the sequence by setting ``cur_len = 0`` (num...
-8,821,713,950,774,863,000
The masked tokens to be predicted for a particular sequence are determined by the following algorithm: 0. Start from the beginning of the sequence by setting ``cur_len = 0`` (number of tokens processed so far). 1. Sample a ``span_length`` from the interval ``[1, max_span_length]`` (length of span of tokens to ...
src/transformers/data/data_collator.py
mask_tokens
21jun/transformers
python
def mask_tokens(self, inputs: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)]: '\n The masked tokens to be predicted for a particular sequence are determined by the following algorithm:\n\n 0. Start from the beginning of the sequence by setting ``cur_len = 0`` (num...