body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
5d70dc6e08cc7c1257b31a4fef397266af96ba0ea6560443c3c2c88a10ca046b | def is_equal(self, state1, state2):
'Trivial implementation'
return (state1 == state2) | Trivial implementation | cam/sgnmt/predictors/structure.py | is_equal | cimeister/sgnmt | 59 | python | def is_equal(self, state1, state2):
return (state1 == state2) | def is_equal(self, state1, state2):
return (state1 == state2)<|docstring|>Trivial implementation<|endoftext|> |
062a78687c57476ee52503eca0817731886927e1ae7018a3f47ff72892b0362e | def queue_identification(self, queue, project):
'Restrictions on a project id & queue name pair.\n\n :param queue: Name of the queue\n :param project: Project id\n :raises ValidationFailed: if the `name` is longer than 64\n characters or contains anything other than ASCII digits and\... | Restrictions on a project id & queue name pair.
:param queue: Name of the queue
:param project: Project id
:raises ValidationFailed: if the `name` is longer than 64
characters or contains anything other than ASCII digits and
letters, underscores, and dashes. Also raises if `project`
is not None but longer... | zaqar/transport/validation.py | queue_identification | g894404753/zaqar | 97 | python | def queue_identification(self, queue, project):
'Restrictions on a project id & queue name pair.\n\n :param queue: Name of the queue\n :param project: Project id\n :raises ValidationFailed: if the `name` is longer than 64\n characters or contains anything other than ASCII digits and\... | def queue_identification(self, queue, project):
'Restrictions on a project id & queue name pair.\n\n :param queue: Name of the queue\n :param project: Project id\n :raises ValidationFailed: if the `name` is longer than 64\n characters or contains anything other than ASCII digits and\... |
c87cdd873c0acafa2d3e9a2ad1aec19689fac9b7759b29ae3e664fd8bab06694 | def _decode_json_pointer(self, pointer):
'Parse a json pointer.\n\n Json Pointers are defined in\n http://tools.ietf.org/html/draft-pbryan-zyp-json-pointer .\n The pointers use \'/\' for separation between object attributes, such\n that \'/A/B\' would evaluate to C in {"A": {"B": "C"}}. ... | Parse a json pointer.
Json Pointers are defined in
http://tools.ietf.org/html/draft-pbryan-zyp-json-pointer .
The pointers use '/' for separation between object attributes, such
that '/A/B' would evaluate to C in {"A": {"B": "C"}}. A '/' character
in an attribute name is encoded as "~1" and a '~' character is encoded
... | zaqar/transport/validation.py | _decode_json_pointer | g894404753/zaqar | 97 | python | def _decode_json_pointer(self, pointer):
'Parse a json pointer.\n\n Json Pointers are defined in\n http://tools.ietf.org/html/draft-pbryan-zyp-json-pointer .\n The pointers use \'/\' for separation between object attributes, such\n that \'/A/B\' would evaluate to C in {"A": {"B": "C"}}. ... | def _decode_json_pointer(self, pointer):
'Parse a json pointer.\n\n Json Pointers are defined in\n http://tools.ietf.org/html/draft-pbryan-zyp-json-pointer .\n The pointers use \'/\' for separation between object attributes, such\n that \'/A/B\' would evaluate to C in {"A": {"B": "C"}}. ... |
7c2ba4f94ceeb5341942226fe22e2c826c83b63dd3568dc813fa2c364aca944d | def _validate_json_pointer(self, pointer):
'Validate a json pointer.\n\n We only accept a limited form of json pointers.\n '
if (not pointer.startswith('/')):
msg = (_('Pointer `%s` does not start with "/".') % pointer)
raise ValidationFailed(msg)
if re.search('/\\s*?/', pointe... | Validate a json pointer.
We only accept a limited form of json pointers. | zaqar/transport/validation.py | _validate_json_pointer | g894404753/zaqar | 97 | python | def _validate_json_pointer(self, pointer):
'Validate a json pointer.\n\n We only accept a limited form of json pointers.\n '
if (not pointer.startswith('/')):
msg = (_('Pointer `%s` does not start with "/".') % pointer)
raise ValidationFailed(msg)
if re.search('/\\s*?/', pointe... | def _validate_json_pointer(self, pointer):
'Validate a json pointer.\n\n We only accept a limited form of json pointers.\n '
if (not pointer.startswith('/')):
msg = (_('Pointer `%s` does not start with "/".') % pointer)
raise ValidationFailed(msg)
if re.search('/\\s*?/', pointe... |
1a2394180e5ea132d30261fa03d406bc25d394da85581949782bd7bfe355857d | def queue_listing(self, limit=None, **kwargs):
'Restrictions involving a list of queues.\n\n :param limit: The expected number of queues in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limit... | Restrictions involving a list of queues.
:param limit: The expected number of queues in the list
:param kwargs: Ignored arguments passed to storage API
:raises ValidationFailed: if the limit is exceeded | zaqar/transport/validation.py | queue_listing | g894404753/zaqar | 97 | python | def queue_listing(self, limit=None, **kwargs):
'Restrictions involving a list of queues.\n\n :param limit: The expected number of queues in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limit... | def queue_listing(self, limit=None, **kwargs):
'Restrictions involving a list of queues.\n\n :param limit: The expected number of queues in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limit... |
c3abdf6ee14962b051ef989ee541e98efab718f57a8e412631f91a928cf9d2df | def queue_metadata_length(self, content_length):
"Restrictions on queue's length.\n\n :param content_length: Queue request's length.\n :raises ValidationFailed: if the metadata is oversize.\n "
if (content_length is None):
return
if (content_length > self._limits_conf.max_queue_... | Restrictions on queue's length.
:param content_length: Queue request's length.
:raises ValidationFailed: if the metadata is oversize. | zaqar/transport/validation.py | queue_metadata_length | g894404753/zaqar | 97 | python | def queue_metadata_length(self, content_length):
"Restrictions on queue's length.\n\n :param content_length: Queue request's length.\n :raises ValidationFailed: if the metadata is oversize.\n "
if (content_length is None):
return
if (content_length > self._limits_conf.max_queue_... | def queue_metadata_length(self, content_length):
"Restrictions on queue's length.\n\n :param content_length: Queue request's length.\n :raises ValidationFailed: if the metadata is oversize.\n "
if (content_length is None):
return
if (content_length > self._limits_conf.max_queue_... |
c869e373a52954a0a54aa18f406f072c74f356238e4475752403c57e286ab84c | def queue_metadata_putting(self, queue_metadata):
"Checking if the reserved attributes of the queue are valid.\n\n :param queue_metadata: Queue's metadata.\n :raises ValidationFailed: if any reserved attribute is invalid.\n "
if (not queue_metadata):
return
queue_default_ttl = q... | Checking if the reserved attributes of the queue are valid.
:param queue_metadata: Queue's metadata.
:raises ValidationFailed: if any reserved attribute is invalid. | zaqar/transport/validation.py | queue_metadata_putting | g894404753/zaqar | 97 | python | def queue_metadata_putting(self, queue_metadata):
"Checking if the reserved attributes of the queue are valid.\n\n :param queue_metadata: Queue's metadata.\n :raises ValidationFailed: if any reserved attribute is invalid.\n "
if (not queue_metadata):
return
queue_default_ttl = q... | def queue_metadata_putting(self, queue_metadata):
"Checking if the reserved attributes of the queue are valid.\n\n :param queue_metadata: Queue's metadata.\n :raises ValidationFailed: if any reserved attribute is invalid.\n "
if (not queue_metadata):
return
queue_default_ttl = q... |
fc4dd55409d6cc67122c7949ada52fb275b94e4173a1bf493b16d9052af674cc | def queue_purging(self, document):
'Restrictions the resource types to be purged for a queue.\n\n :param resource_types: Type list of all resource under a queue\n :raises ValidationFailed: if the resource types are invalid\n '
if ('resource_types' not in document):
msg = _(u'Post bo... | Restrictions the resource types to be purged for a queue.
:param resource_types: Type list of all resource under a queue
:raises ValidationFailed: if the resource types are invalid | zaqar/transport/validation.py | queue_purging | g894404753/zaqar | 97 | python | def queue_purging(self, document):
'Restrictions the resource types to be purged for a queue.\n\n :param resource_types: Type list of all resource under a queue\n :raises ValidationFailed: if the resource types are invalid\n '
if ('resource_types' not in document):
msg = _(u'Post bo... | def queue_purging(self, document):
'Restrictions the resource types to be purged for a queue.\n\n :param resource_types: Type list of all resource under a queue\n :raises ValidationFailed: if the resource types are invalid\n '
if ('resource_types' not in document):
msg = _(u'Post bo... |
d6356c23af1958b6f5252376956cc879a8c79207bd6232b70b8f743fe5df6963 | def message_posting(self, messages):
'Restrictions on a list of messages.\n\n :param messages: A list of messages\n :raises ValidationFailed: if any message has a out-of-range\n TTL.\n '
if (not messages):
raise ValidationFailed(_(u'No messages to enqueu.'))
for msg i... | Restrictions on a list of messages.
:param messages: A list of messages
:raises ValidationFailed: if any message has a out-of-range
TTL. | zaqar/transport/validation.py | message_posting | g894404753/zaqar | 97 | python | def message_posting(self, messages):
'Restrictions on a list of messages.\n\n :param messages: A list of messages\n :raises ValidationFailed: if any message has a out-of-range\n TTL.\n '
if (not messages):
raise ValidationFailed(_(u'No messages to enqueu.'))
for msg i... | def message_posting(self, messages):
'Restrictions on a list of messages.\n\n :param messages: A list of messages\n :raises ValidationFailed: if any message has a out-of-range\n TTL.\n '
if (not messages):
raise ValidationFailed(_(u'No messages to enqueu.'))
for msg i... |
3837ae7b83693e569b886ba53202f28eec9026f7cbfa799852de2b134d6b979e | def message_length(self, content_length, max_msg_post_size=None):
"Restrictions on message post length.\n\n :param content_length: Queue request's length.\n :raises ValidationFailed: if the metadata is oversize.\n "
if (content_length is None):
return
if max_msg_post_size:
... | Restrictions on message post length.
:param content_length: Queue request's length.
:raises ValidationFailed: if the metadata is oversize. | zaqar/transport/validation.py | message_length | g894404753/zaqar | 97 | python | def message_length(self, content_length, max_msg_post_size=None):
"Restrictions on message post length.\n\n :param content_length: Queue request's length.\n :raises ValidationFailed: if the metadata is oversize.\n "
if (content_length is None):
return
if max_msg_post_size:
... | def message_length(self, content_length, max_msg_post_size=None):
"Restrictions on message post length.\n\n :param content_length: Queue request's length.\n :raises ValidationFailed: if the metadata is oversize.\n "
if (content_length is None):
return
if max_msg_post_size:
... |
0675d940a807e008a3640f69ee22424bebb3f87563fb926aecf739ccf22731a9 | def message_content(self, message):
'Restrictions on each message.'
ttl = message['ttl']
if (not (MIN_MESSAGE_TTL <= ttl <= self._limits_conf.max_message_ttl)):
msg = _(u'The TTL for a message may not exceed {0} seconds, and must be at least {1} seconds long.')
raise ValidationFailed(msg, se... | Restrictions on each message. | zaqar/transport/validation.py | message_content | g894404753/zaqar | 97 | python | def message_content(self, message):
ttl = message['ttl']
if (not (MIN_MESSAGE_TTL <= ttl <= self._limits_conf.max_message_ttl)):
msg = _(u'The TTL for a message may not exceed {0} seconds, and must be at least {1} seconds long.')
raise ValidationFailed(msg, self._limits_conf.max_message_ttl... | def message_content(self, message):
ttl = message['ttl']
if (not (MIN_MESSAGE_TTL <= ttl <= self._limits_conf.max_message_ttl)):
msg = _(u'The TTL for a message may not exceed {0} seconds, and must be at least {1} seconds long.')
raise ValidationFailed(msg, self._limits_conf.max_message_ttl... |
c1216730f6645b59c5eef01fc9dd566f5470ad746df1e0b1664c8ba3ccb78ef1 | def message_listing(self, limit=None, **kwargs):
'Restrictions involving a list of messages.\n\n :param limit: The expected number of messages in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self.... | Restrictions involving a list of messages.
:param limit: The expected number of messages in the list
:param kwargs: Ignored arguments passed to storage API
:raises ValidationFailed: if the limit is exceeded | zaqar/transport/validation.py | message_listing | g894404753/zaqar | 97 | python | def message_listing(self, limit=None, **kwargs):
'Restrictions involving a list of messages.\n\n :param limit: The expected number of messages in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self.... | def message_listing(self, limit=None, **kwargs):
'Restrictions involving a list of messages.\n\n :param limit: The expected number of messages in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self.... |
602041d60df4dd8acda6f16baf3e3d51e31ac78a419081e49045e8e070479d46 | def message_deletion(self, ids=None, pop=None, claim_ids=None):
'Restrictions involving deletion of messages.\n\n :param ids: message ids passed in by the delete request\n :param pop: count of messages to be POPped\n :param claim_ids: claim ids passed in by the delete request\n :raises V... | Restrictions involving deletion of messages.
:param ids: message ids passed in by the delete request
:param pop: count of messages to be POPped
:param claim_ids: claim ids passed in by the delete request
:raises ValidationFailed: if,
pop AND id params are present together
neither pop or id params are present
... | zaqar/transport/validation.py | message_deletion | g894404753/zaqar | 97 | python | def message_deletion(self, ids=None, pop=None, claim_ids=None):
'Restrictions involving deletion of messages.\n\n :param ids: message ids passed in by the delete request\n :param pop: count of messages to be POPped\n :param claim_ids: claim ids passed in by the delete request\n :raises V... | def message_deletion(self, ids=None, pop=None, claim_ids=None):
'Restrictions involving deletion of messages.\n\n :param ids: message ids passed in by the delete request\n :param pop: count of messages to be POPped\n :param claim_ids: claim ids passed in by the delete request\n :raises V... |
af88c1a0d9698fe2f20708032c6a02d0ef51f606712551eb6c0cd43210623d00 | def claim_creation(self, metadata, limit=None):
'Restrictions on the claim parameters upon creation.\n\n :param metadata: The claim metadata\n :param limit: The number of messages to claim\n :raises ValidationFailed: if either TTL or grace is out of range,\n or the expected number of... | Restrictions on the claim parameters upon creation.
:param metadata: The claim metadata
:param limit: The number of messages to claim
:raises ValidationFailed: if either TTL or grace is out of range,
or the expected number of messages exceed the limit. | zaqar/transport/validation.py | claim_creation | g894404753/zaqar | 97 | python | def claim_creation(self, metadata, limit=None):
'Restrictions on the claim parameters upon creation.\n\n :param metadata: The claim metadata\n :param limit: The number of messages to claim\n :raises ValidationFailed: if either TTL or grace is out of range,\n or the expected number of... | def claim_creation(self, metadata, limit=None):
'Restrictions on the claim parameters upon creation.\n\n :param metadata: The claim metadata\n :param limit: The number of messages to claim\n :raises ValidationFailed: if either TTL or grace is out of range,\n or the expected number of... |
fba04eb09f0461eb6feea12cbce957667bee00c2d60793b28cc1406daa6c2478 | def claim_updating(self, metadata):
'Restrictions on the claim TTL.\n\n :param metadata: The claim metadata\n :raises ValidationFailed: if the TTL is out of range\n '
ttl = metadata['ttl']
if (not (MIN_CLAIM_TTL <= ttl <= self._limits_conf.max_claim_ttl)):
msg = _(u'The TTL for ... | Restrictions on the claim TTL.
:param metadata: The claim metadata
:raises ValidationFailed: if the TTL is out of range | zaqar/transport/validation.py | claim_updating | g894404753/zaqar | 97 | python | def claim_updating(self, metadata):
'Restrictions on the claim TTL.\n\n :param metadata: The claim metadata\n :raises ValidationFailed: if the TTL is out of range\n '
ttl = metadata['ttl']
if (not (MIN_CLAIM_TTL <= ttl <= self._limits_conf.max_claim_ttl)):
msg = _(u'The TTL for ... | def claim_updating(self, metadata):
'Restrictions on the claim TTL.\n\n :param metadata: The claim metadata\n :raises ValidationFailed: if the TTL is out of range\n '
ttl = metadata['ttl']
if (not (MIN_CLAIM_TTL <= ttl <= self._limits_conf.max_claim_ttl)):
msg = _(u'The TTL for ... |
bdcc86ebe6eeb362bb74dca9f0d11354689376738cc1971f155806a5357f8683 | def subscription_posting(self, subscription):
'Restrictions on a creation of subscription.\n\n :param subscription: dict of subscription\n :raises ValidationFailed: if the subscription is invalid.\n '
for p in ('subscriber',):
if (p not in subscription.keys()):
raise Val... | Restrictions on a creation of subscription.
:param subscription: dict of subscription
:raises ValidationFailed: if the subscription is invalid. | zaqar/transport/validation.py | subscription_posting | g894404753/zaqar | 97 | python | def subscription_posting(self, subscription):
'Restrictions on a creation of subscription.\n\n :param subscription: dict of subscription\n :raises ValidationFailed: if the subscription is invalid.\n '
for p in ('subscriber',):
if (p not in subscription.keys()):
raise Val... | def subscription_posting(self, subscription):
'Restrictions on a creation of subscription.\n\n :param subscription: dict of subscription\n :raises ValidationFailed: if the subscription is invalid.\n '
for p in ('subscriber',):
if (p not in subscription.keys()):
raise Val... |
6b444ad9ebcaadf44a9ad934670b0c60e1a53185d5520798527e488580c81bb7 | def subscription_patching(self, subscription):
'Restrictions on an update of subscription.\n\n :param subscription: dict of subscription\n :raises ValidationFailed: if the subscription is invalid.\n '
if (not subscription):
raise ValidationFailed(_(u'No subscription to create.'))
... | Restrictions on an update of subscription.
:param subscription: dict of subscription
:raises ValidationFailed: if the subscription is invalid. | zaqar/transport/validation.py | subscription_patching | g894404753/zaqar | 97 | python | def subscription_patching(self, subscription):
'Restrictions on an update of subscription.\n\n :param subscription: dict of subscription\n :raises ValidationFailed: if the subscription is invalid.\n '
if (not subscription):
raise ValidationFailed(_(u'No subscription to create.'))
... | def subscription_patching(self, subscription):
'Restrictions on an update of subscription.\n\n :param subscription: dict of subscription\n :raises ValidationFailed: if the subscription is invalid.\n '
if (not subscription):
raise ValidationFailed(_(u'No subscription to create.'))
... |
57e5ea30da19c23e24c451e87fccaf017b9dd1cf111baba1afee5d8a86eac09c | def subscription_listing(self, limit=None, **kwargs):
'Restrictions involving a list of subscriptions.\n\n :param limit: The expected number of subscriptions in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
... | Restrictions involving a list of subscriptions.
:param limit: The expected number of subscriptions in the list
:param kwargs: Ignored arguments passed to storage API
:raises ValidationFailed: if the limit is exceeded | zaqar/transport/validation.py | subscription_listing | g894404753/zaqar | 97 | python | def subscription_listing(self, limit=None, **kwargs):
'Restrictions involving a list of subscriptions.\n\n :param limit: The expected number of subscriptions in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
... | def subscription_listing(self, limit=None, **kwargs):
'Restrictions involving a list of subscriptions.\n\n :param limit: The expected number of subscriptions in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
... |
268fd3f442ee5bf610fe384369c184293c825f551f129b8eefe384fb612452d0 | def get_limit_conf_value(self, limit_conf_name=None):
'Return the value of limit configuration.\n\n :param limit_conf_name: configuration name\n '
return self._limits_conf[limit_conf_name] | Return the value of limit configuration.
:param limit_conf_name: configuration name | zaqar/transport/validation.py | get_limit_conf_value | g894404753/zaqar | 97 | python | def get_limit_conf_value(self, limit_conf_name=None):
'Return the value of limit configuration.\n\n :param limit_conf_name: configuration name\n '
return self._limits_conf[limit_conf_name] | def get_limit_conf_value(self, limit_conf_name=None):
'Return the value of limit configuration.\n\n :param limit_conf_name: configuration name\n '
return self._limits_conf[limit_conf_name]<|docstring|>Return the value of limit configuration.
:param limit_conf_name: configuration name<|endoftext|> |
954a3b76ab55e3e4e89f06d4a78a76874635fa5cc9cc972b873ef262837eefd0 | def flavor_listing(self, limit=None, **kwargs):
'Restrictions involving a list of pools.\n\n :param limit: The expected number of flavors in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limi... | Restrictions involving a list of pools.
:param limit: The expected number of flavors in the list
:param kwargs: Ignored arguments passed to storage API
:raises ValidationFailed: if the limit is exceeded | zaqar/transport/validation.py | flavor_listing | g894404753/zaqar | 97 | python | def flavor_listing(self, limit=None, **kwargs):
'Restrictions involving a list of pools.\n\n :param limit: The expected number of flavors in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limi... | def flavor_listing(self, limit=None, **kwargs):
'Restrictions involving a list of pools.\n\n :param limit: The expected number of flavors in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limi... |
9c6440bca0cf46d37b6d1ce9937d3144b8facedb3db06bcf75b5d8215b3f9bcc | def pool_listing(self, limit=None, **kwargs):
'Restrictions involving a list of pools.\n\n :param limit: The expected number of flavors in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limits... | Restrictions involving a list of pools.
:param limit: The expected number of flavors in the list
:param kwargs: Ignored arguments passed to storage API
:raises ValidationFailed: if the limit is exceeded | zaqar/transport/validation.py | pool_listing | g894404753/zaqar | 97 | python | def pool_listing(self, limit=None, **kwargs):
'Restrictions involving a list of pools.\n\n :param limit: The expected number of flavors in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limits... | def pool_listing(self, limit=None, **kwargs):
'Restrictions involving a list of pools.\n\n :param limit: The expected number of flavors in the list\n :param kwargs: Ignored arguments passed to storage API\n :raises ValidationFailed: if the limit is exceeded\n '
uplimit = self._limits... |
3a5942b158412aa72ed159a4e8cb79b846baad2ea7a6d0b7d4799611f2659007 | def client_id_uuid_safe(self, client_id):
'Restrictions the format of client id\n\n :param client_id: the client id of request\n :raises ValidationFailed: if the limit is exceeded\n '
if (self._limits_conf.client_id_uuid_safe == 'off'):
if ((len(client_id) < self._limits_conf.min_le... | Restrictions the format of client id
:param client_id: the client id of request
:raises ValidationFailed: if the limit is exceeded | zaqar/transport/validation.py | client_id_uuid_safe | g894404753/zaqar | 97 | python | def client_id_uuid_safe(self, client_id):
'Restrictions the format of client id\n\n :param client_id: the client id of request\n :raises ValidationFailed: if the limit is exceeded\n '
if (self._limits_conf.client_id_uuid_safe == 'off'):
if ((len(client_id) < self._limits_conf.min_le... | def client_id_uuid_safe(self, client_id):
'Restrictions the format of client id\n\n :param client_id: the client id of request\n :raises ValidationFailed: if the limit is exceeded\n '
if (self._limits_conf.client_id_uuid_safe == 'off'):
if ((len(client_id) < self._limits_conf.min_le... |
4842231413a60c8356dd80e20b60fa7f1590d40de818aecba0294fed76f13cc4 | def topic_identification(self, topic, project):
'Restrictions on a project id & topic name pair.\n\n :param queue: Name of the topic\n :param project: Project id\n :raises ValidationFailed: if the `name` is longer than 64\n characters or contains anything other than ASCII digits and\... | Restrictions on a project id & topic name pair.
:param queue: Name of the topic
:param project: Project id
:raises ValidationFailed: if the `name` is longer than 64
characters or contains anything other than ASCII digits and
letters, underscores, and dashes. Also raises if `project`
is not None but longer... | zaqar/transport/validation.py | topic_identification | g894404753/zaqar | 97 | python | def topic_identification(self, topic, project):
'Restrictions on a project id & topic name pair.\n\n :param queue: Name of the topic\n :param project: Project id\n :raises ValidationFailed: if the `name` is longer than 64\n characters or contains anything other than ASCII digits and\... | def topic_identification(self, topic, project):
'Restrictions on a project id & topic name pair.\n\n :param queue: Name of the topic\n :param project: Project id\n :raises ValidationFailed: if the `name` is longer than 64\n characters or contains anything other than ASCII digits and\... |
e3696e55dd0abbd049042af01cb3ffba2be5c0186bf8806f688cca4bf4b7102c | def test_ImageProcessor():
'Check that ImageProcessor is correctly subtracting images.'
data_key = 'pe1_image'
def verify(_name, _doc):
if (_name != 'event'):
return
data = _doc['data'][data_key]
assert isinstance(data, list)
assert np.array_equal(np.asarray(data... | Check that ImageProcessor is correctly subtracting images. | crystalmapping/tests/test_callbacks.py | test_ImageProcessor | st3107/crystalmapping | 0 | python | def test_ImageProcessor():
data_key = 'pe1_image'
def verify(_name, _doc):
if (_name != 'event'):
return
data = _doc['data'][data_key]
assert isinstance(data, list)
assert np.array_equal(np.asarray(data), np.zeros((3, 3)))
ip = cbs.ImageProcessor(data_key=da... | def test_ImageProcessor():
data_key = 'pe1_image'
def verify(_name, _doc):
if (_name != 'event'):
return
data = _doc['data'][data_key]
assert isinstance(data, list)
assert np.array_equal(np.asarray(data), np.zeros((3, 3)))
ip = cbs.ImageProcessor(data_key=da... |
cdba546e3ab248048bd439eb5e763ce671e2a0e859b997650f979ea340674d08 | def test_gen_processed_images():
'Test gen_processed_images.'
images1 = (np.ones((2, 3, 3)) for _ in range(3))
subtrahend = np.ones((3, 3))
subtrahend[(0, 0)] = 2
images2 = cbs.gen_processed_images(images1, subtrahend=subtrahend)
for image in images2:
assert np.array_equal(image, np.zero... | Test gen_processed_images. | crystalmapping/tests/test_callbacks.py | test_gen_processed_images | st3107/crystalmapping | 0 | python | def test_gen_processed_images():
images1 = (np.ones((2, 3, 3)) for _ in range(3))
subtrahend = np.ones((3, 3))
subtrahend[(0, 0)] = 2
images2 = cbs.gen_processed_images(images1, subtrahend=subtrahend)
for image in images2:
assert np.array_equal(image, np.zeros((3, 3))) | def test_gen_processed_images():
images1 = (np.ones((2, 3, 3)) for _ in range(3))
subtrahend = np.ones((3, 3))
subtrahend[(0, 0)] = 2
images2 = cbs.gen_processed_images(images1, subtrahend=subtrahend)
for image in images2:
assert np.array_equal(image, np.zeros((3, 3)))<|docstring|>Test ... |
f5ddc5e940a77a2b52f0b09c9031475ba2e623593d53532982b472067cbf5d55 | def test_PeakTracker(tmpdir):
'Check that PeakTrack and TrackLinker works without errors.'
tp.quiet()
image_file = resource_filename('crystalmapping', 'data/image.png')
image = plt.imread(image_file)
images = ([image] * 3)
db = databroker.v1.temp()
data_key = 'pe1_image'
pt = cbs.PeakTra... | Check that PeakTrack and TrackLinker works without errors. | crystalmapping/tests/test_callbacks.py | test_PeakTracker | st3107/crystalmapping | 0 | python | def test_PeakTracker(tmpdir):
tp.quiet()
image_file = resource_filename('crystalmapping', 'data/image.png')
image = plt.imread(image_file)
images = ([image] * 3)
db = databroker.v1.temp()
data_key = 'pe1_image'
pt = cbs.PeakTracker(data_key=data_key, diameter=(11, 11))
pt.subscribe(... | def test_PeakTracker(tmpdir):
tp.quiet()
image_file = resource_filename('crystalmapping', 'data/image.png')
image = plt.imread(image_file)
images = ([image] * 3)
db = databroker.v1.temp()
data_key = 'pe1_image'
pt = cbs.PeakTracker(data_key=data_key, diameter=(11, 11))
pt.subscribe(... |
92710b4aedc9f82b8b33c40347c6525d88922bceb1977da3aa079c3672e8c39d | def test_DataFrameDumper():
'Test DataFrameDumper.'
db = databroker.v1.temp()
dfd = cbs.DataFrameDumper(db)
data = [1, 2, 3]
df = pd.DataFrame({'a': [1, 2, 3]})
metadata = {'key': 'a'}
dfd.dump_df(df, metadata)
run = db[(- 1)]
assert (run.start['key'] == metadata['key'])
assert (... | Test DataFrameDumper. | crystalmapping/tests/test_callbacks.py | test_DataFrameDumper | st3107/crystalmapping | 0 | python | def test_DataFrameDumper():
db = databroker.v1.temp()
dfd = cbs.DataFrameDumper(db)
data = [1, 2, 3]
df = pd.DataFrame({'a': [1, 2, 3]})
metadata = {'key': 'a'}
dfd.dump_df(df, metadata)
run = db[(- 1)]
assert (run.start['key'] == metadata['key'])
assert (list(run.data('a')) == ... | def test_DataFrameDumper():
db = databroker.v1.temp()
dfd = cbs.DataFrameDumper(db)
data = [1, 2, 3]
df = pd.DataFrame({'a': [1, 2, 3]})
metadata = {'key': 'a'}
dfd.dump_df(df, metadata)
run = db[(- 1)]
assert (run.start['key'] == metadata['key'])
assert (list(run.data('a')) == ... |
2333ac5c45a972949da897d27d2886a576750a0a81377ef1691be47cee4fd4d6 | @jax.jit
@functools.partial(jax.vmap, in_axes=(1, 1, 1, None, None), out_axes=1)
def gae_advantages(rewards: np.ndarray, terminal_masks: np.ndarray, values: np.ndarray, discount: float, gae_param: float):
'Use Generalized Advantage Estimation (GAE) to compute advantages.\n\n As defined by eqs. (11-12) in PPO paper... | Use Generalized Advantage Estimation (GAE) to compute advantages.
As defined by eqs. (11-12) in PPO paper arXiv: 1707.06347. Implementation uses
key observation that A_{t} = delta_t + gamma*lambda*A_{t+1}.
Args:
rewards: array shaped (actor_steps, num_agents), rewards from the game
terminal_masks: array shaped (a... | examples/ppo/ppo_lib.py | gae_advantages | cccntu/flax | 4 | python | @jax.jit
@functools.partial(jax.vmap, in_axes=(1, 1, 1, None, None), out_axes=1)
def gae_advantages(rewards: np.ndarray, terminal_masks: np.ndarray, values: np.ndarray, discount: float, gae_param: float):
'Use Generalized Advantage Estimation (GAE) to compute advantages.\n\n As defined by eqs. (11-12) in PPO paper... | @jax.jit
@functools.partial(jax.vmap, in_axes=(1, 1, 1, None, None), out_axes=1)
def gae_advantages(rewards: np.ndarray, terminal_masks: np.ndarray, values: np.ndarray, discount: float, gae_param: float):
'Use Generalized Advantage Estimation (GAE) to compute advantages.\n\n As defined by eqs. (11-12) in PPO paper... |
ab8a07bf9656fba073f3e59d256726fc5c08849187e67f8555122968701a7ac2 | @functools.partial(jax.jit, static_argnums=1)
def loss_fn(params: flax.core.frozen_dict.FrozenDict, module: models.ActorCritic, minibatch: Tuple, clip_param: float, vf_coeff: float, entropy_coeff: float):
'Evaluate the loss function.\n\n Compute loss as a sum of three components: the negative of the PPO clipped\n ... | Evaluate the loss function.
Compute loss as a sum of three components: the negative of the PPO clipped
surrogate objective, the value function loss and the negative of the entropy
bonus.
Args:
params: the parameters of the actor-critic model
module: the actor-critic model
minibatch: Tuple of five elements formi... | examples/ppo/ppo_lib.py | loss_fn | cccntu/flax | 4 | python | @functools.partial(jax.jit, static_argnums=1)
def loss_fn(params: flax.core.frozen_dict.FrozenDict, module: models.ActorCritic, minibatch: Tuple, clip_param: float, vf_coeff: float, entropy_coeff: float):
'Evaluate the loss function.\n\n Compute loss as a sum of three components: the negative of the PPO clipped\n ... | @functools.partial(jax.jit, static_argnums=1)
def loss_fn(params: flax.core.frozen_dict.FrozenDict, module: models.ActorCritic, minibatch: Tuple, clip_param: float, vf_coeff: float, entropy_coeff: float):
'Evaluate the loss function.\n\n Compute loss as a sum of three components: the negative of the PPO clipped\n ... |
a64b285f52ae5c71b160a8ee0bf406bf3dc8abb208855aee0c0039d91bc45202 | @functools.partial(jax.jit, static_argnums=(0, 7))
def train_step(module: models.ActorCritic, optimizer: flax.optim.base.Optimizer, trajectories: Tuple, clip_param: float, vf_coeff: float, entropy_coeff: float, lr: float, batch_size: int):
'Compilable train step.\n\n Runs an entire epoch of training (i.e. the loop... | Compilable train step.
Runs an entire epoch of training (i.e. the loop over minibatches within
an epoch is included here for performance reasons).
Args:
module: the actor-critic model
optimizer: optimizer for the actor-critic model
trajectories: Tuple of the following five elements forming the experience:
... | examples/ppo/ppo_lib.py | train_step | cccntu/flax | 4 | python | @functools.partial(jax.jit, static_argnums=(0, 7))
def train_step(module: models.ActorCritic, optimizer: flax.optim.base.Optimizer, trajectories: Tuple, clip_param: float, vf_coeff: float, entropy_coeff: float, lr: float, batch_size: int):
'Compilable train step.\n\n Runs an entire epoch of training (i.e. the loop... | @functools.partial(jax.jit, static_argnums=(0, 7))
def train_step(module: models.ActorCritic, optimizer: flax.optim.base.Optimizer, trajectories: Tuple, clip_param: float, vf_coeff: float, entropy_coeff: float, lr: float, batch_size: int):
'Compilable train step.\n\n Runs an entire epoch of training (i.e. the loop... |
698d148d2bbb0de53bd9d65122609ae0f9d2d879a03091b6556130855c378d8c | def get_experience(params: flax.core.frozen_dict.FrozenDict, module: models.ActorCritic, simulators: List[agent.RemoteSimulator], steps_per_actor: int):
'Collect experience from agents.\n\n Runs `steps_per_actor` time steps of the game for each of the `simulators`.\n '
all_experience = []
for _ in range((... | Collect experience from agents.
Runs `steps_per_actor` time steps of the game for each of the `simulators`. | examples/ppo/ppo_lib.py | get_experience | cccntu/flax | 4 | python | def get_experience(params: flax.core.frozen_dict.FrozenDict, module: models.ActorCritic, simulators: List[agent.RemoteSimulator], steps_per_actor: int):
'Collect experience from agents.\n\n Runs `steps_per_actor` time steps of the game for each of the `simulators`.\n '
all_experience = []
for _ in range((... | def get_experience(params: flax.core.frozen_dict.FrozenDict, module: models.ActorCritic, simulators: List[agent.RemoteSimulator], steps_per_actor: int):
'Collect experience from agents.\n\n Runs `steps_per_actor` time steps of the game for each of the `simulators`.\n '
all_experience = []
for _ in range((... |
673336685f3d7f17d7f1b004094c41192e016f16b963f43fd8f281eef581d99c | def process_experience(experience: List[List[agent.ExpTuple]], actor_steps: int, num_agents: int, gamma: float, lambda_: float):
'Process experience for training, including advantage estimation.\n\n Args:\n experience: collected from agents in the form of nested lists/namedtuple\n actor_steps: number of step... | Process experience for training, including advantage estimation.
Args:
experience: collected from agents in the form of nested lists/namedtuple
actor_steps: number of steps each agent has completed
num_agents: number of agents that collected experience
gamma: dicount parameter
lambda_: GAE parameter
Returns... | examples/ppo/ppo_lib.py | process_experience | cccntu/flax | 4 | python | def process_experience(experience: List[List[agent.ExpTuple]], actor_steps: int, num_agents: int, gamma: float, lambda_: float):
'Process experience for training, including advantage estimation.\n\n Args:\n experience: collected from agents in the form of nested lists/namedtuple\n actor_steps: number of step... | def process_experience(experience: List[List[agent.ExpTuple]], actor_steps: int, num_agents: int, gamma: float, lambda_: float):
'Process experience for training, including advantage estimation.\n\n Args:\n experience: collected from agents in the form of nested lists/namedtuple\n actor_steps: number of step... |
b16f579149023f40639b6c00cba65362c9390184b139f0fdf52f7e5a34c4bd05 | def train(module: models.ActorCritic, optimizer: flax.optim.base.Optimizer, config: ml_collections.ConfigDict, model_dir: str):
'Main training loop.\n\n Args:\n module: the actor-critic model\n optimizer: optimizer for the actor-critic model\n config: object holding hyperparameters and the training inform... | Main training loop.
Args:
module: the actor-critic model
optimizer: optimizer for the actor-critic model
config: object holding hyperparameters and the training information
model_dir: path to dictionary where checkpoints and logging info are stored
Returns:
optimizer: the trained optimizer | examples/ppo/ppo_lib.py | train | cccntu/flax | 4 | python | def train(module: models.ActorCritic, optimizer: flax.optim.base.Optimizer, config: ml_collections.ConfigDict, model_dir: str):
'Main training loop.\n\n Args:\n module: the actor-critic model\n optimizer: optimizer for the actor-critic model\n config: object holding hyperparameters and the training inform... | def train(module: models.ActorCritic, optimizer: flax.optim.base.Optimizer, config: ml_collections.ConfigDict, model_dir: str):
'Main training loop.\n\n Args:\n module: the actor-critic model\n optimizer: optimizer for the actor-critic model\n config: object holding hyperparameters and the training inform... |
4acf066582fbb45f9e7a1bce90ab610b7d3c1c435583b7b72ac95663ebdc15e2 | def unit_root(x, pvalue=0.05, noprint=False):
'test if input series has unit root using augmented dickey fuller'
dftest = adfuller(x, autolag='AIC')
if (not noprint):
results = Series(dftest[0:4], index=['Test Statistic', 'p-value', 'Lags Used', 'Obs Used'])
for (k, v) in dftest[4].items():
... | test if input series has unit root using augmented dickey fuller | examples/econometric_forecast.py | unit_root | terence-lim/investment-data-science | 2 | python | def unit_root(x, pvalue=0.05, noprint=False):
dftest = adfuller(x, autolag='AIC')
if (not noprint):
results = Series(dftest[0:4], index=['Test Statistic', 'p-value', 'Lags Used', 'Obs Used'])
for (k, v) in dftest[4].items():
results[f'Critical Value ({k})'] = v
print(res... | def unit_root(x, pvalue=0.05, noprint=False):
dftest = adfuller(x, autolag='AIC')
if (not noprint):
results = Series(dftest[0:4], index=['Test Statistic', 'p-value', 'Lags Used', 'Obs Used'])
for (k, v) in dftest[4].items():
results[f'Critical Value ({k})'] = v
print(res... |
9243bf1e32b189fcd838d261b7427f518a0b01845f91363d699ea2ac377dc9f4 | def integration_order(df, noprint=True, max_order=5, pvalue=0.05):
'returns order of integration by iteratively testing for unit root'
for i in range(max_order):
if (not noprint):
print(f'Augmented Dickey-Fuller unit root test of I({i}):')
if (not unit_root(df, pvalue=pvalue, noprint... | returns order of integration by iteratively testing for unit root | examples/econometric_forecast.py | integration_order | terence-lim/investment-data-science | 2 | python | def integration_order(df, noprint=True, max_order=5, pvalue=0.05):
for i in range(max_order):
if (not noprint):
print(f'Augmented Dickey-Fuller unit root test of I({i}):')
if (not unit_root(df, pvalue=pvalue, noprint=noprint)):
return i
df = df.diff().dropna() | def integration_order(df, noprint=True, max_order=5, pvalue=0.05):
for i in range(max_order):
if (not noprint):
print(f'Augmented Dickey-Fuller unit root test of I({i}):')
if (not unit_root(df, pvalue=pvalue, noprint=noprint)):
return i
df = df.diff().dropna()<|d... |
37b59d6673efbbfd755ded666c1e09ba038ab2f321832c508134d2f666821928 | def __init__(self, params):
'\n Initialise the environmental parametrs for the NILM experiment. For the \n hyper-parameters, it takes the default values defined in the config module \n and updates only the subset of values specified in params.\n\n :param params: Dictionnary with differe... | Initialise the environmental parametrs for the NILM experiment. For the
hyper-parameters, it takes the default values defined in the config module
and updates only the subset of values specified in params.
:param params: Dictionnary with different values of hyper-parameters.
:type params: dictionnary | deep_nilmtk/disaggregate/nilm_experiment.py | __init__ | reviwe/deep-nilmtk-v1 | 0 | python | def __init__(self, params):
'\n Initialise the environmental parametrs for the NILM experiment. For the \n hyper-parameters, it takes the default values defined in the config module \n and updates only the subset of values specified in params.\n\n :param params: Dictionnary with differe... | def __init__(self, params):
'\n Initialise the environmental parametrs for the NILM experiment. For the \n hyper-parameters, it takes the default values defined in the config module \n and updates only the subset of values specified in params.\n\n :param params: Dictionnary with differe... |
c32a7df333ca00a92064e150782c27610c3591a0d3e9eb6b3df94bd9a3ecac48 | def _prepare_data(self, mains, sub_main):
"\n Performs data pre-processing and formating. By default, the default pre-processing \n method in used. Neverthless, custom pre-processing methdos are also possible\n to use and need only to be specified in the corresponding entry of the model\n ... | Performs data pre-processing and formating. By default, the default pre-processing
method in used. Neverthless, custom pre-processing methdos are also possible
to use and need only to be specified in the corresponding entry of the model
within the config module within the extra_params. For example:
NILM_MODELS = {
... | deep_nilmtk/disaggregate/nilm_experiment.py | _prepare_data | reviwe/deep-nilmtk-v1 | 0 | python | def _prepare_data(self, mains, sub_main):
"\n Performs data pre-processing and formating. By default, the default pre-processing \n method in used. Neverthless, custom pre-processing methdos are also possible\n to use and need only to be specified in the corresponding entry of the model\n ... | def _prepare_data(self, mains, sub_main):
"\n Performs data pre-processing and formating. By default, the default pre-processing \n method in used. Neverthless, custom pre-processing methdos are also possible\n to use and need only to be specified in the corresponding entry of the model\n ... |
786e3be9742daa34d4e4dd1f75fba70e7d4cbb42bf9f1d0554ef7205270cc447 | def partial_fit(self, mains, sub_main, do_preprocessing=True, **load_kwargs):
" Trains the model for appliances according to the model name specified \n in the experiment's definition. It starts with the data pre-processing and \n formatting and then train the model based on the type of the model(sing... | Trains the model for appliances according to the model name specified
in the experiment's definition. It starts with the data pre-processing and
formatting and then train the model based on the type of the model(single
or multi-task).
:param mains: Aggregate power measurements.
:type mains: Liste of pd.DataFrame
:... | deep_nilmtk/disaggregate/nilm_experiment.py | partial_fit | reviwe/deep-nilmtk-v1 | 0 | python | def partial_fit(self, mains, sub_main, do_preprocessing=True, **load_kwargs):
" Trains the model for appliances according to the model name specified \n in the experiment's definition. It starts with the data pre-processing and \n formatting and then train the model based on the type of the model(sing... | def partial_fit(self, mains, sub_main, do_preprocessing=True, **load_kwargs):
" Trains the model for appliances according to the model name specified \n in the experiment's definition. It starts with the data pre-processing and \n formatting and then train the model based on the type of the model(sing... |
db6a1cc9a8ad664754a038ddef6adb35fb26e00b7d71c28b65a9ce69db268075 | def disaggregate_chunk(self, test_main_list, do_preprocessing=True):
'\n Uses trained models to disaggregate the test_main_list. It is compatible with both single and multi-appliance models. \n\n :param test_main_list: Aggregate power measurements.\n :type test_main_list: Liste of pd.DataFrame\... | Uses trained models to disaggregate the test_main_list. It is compatible with both single and multi-appliance models.
:param test_main_list: Aggregate power measurements.
:type test_main_list: Liste of pd.DataFrame
:param do_preprocessing: Specify if pre-processing need to be done or not, defaults to True
:type do_pr... | deep_nilmtk/disaggregate/nilm_experiment.py | disaggregate_chunk | reviwe/deep-nilmtk-v1 | 0 | python | def disaggregate_chunk(self, test_main_list, do_preprocessing=True):
'\n Uses trained models to disaggregate the test_main_list. It is compatible with both single and multi-appliance models. \n\n :param test_main_list: Aggregate power measurements.\n :type test_main_list: Liste of pd.DataFrame\... | def disaggregate_chunk(self, test_main_list, do_preprocessing=True):
'\n Uses trained models to disaggregate the test_main_list. It is compatible with both single and multi-appliance models. \n\n :param test_main_list: Aggregate power measurements.\n :type test_main_list: Liste of pd.DataFrame\... |
dced02b4e7d13a3bce04a3780c9983e5a88e047a278af86437bb790caf8d48a3 | def single_appliance_disaggregate(self, test_main_list, model=None, do_preprocessing=True):
"\n Perfroms load disaggregtaion for single appliance models. If Optuna was used during the \n training phase, it disaggregtaes the test_main_list using only the best trial. \n If cross-validation is use... | Perfroms load disaggregtaion for single appliance models. If Optuna was used during the
training phase, it disaggregtaes the test_main_list using only the best trial.
If cross-validation is used during training, it returns the average of predictions
cross all folds for each applaince. In this later case, the predict... | deep_nilmtk/disaggregate/nilm_experiment.py | single_appliance_disaggregate | reviwe/deep-nilmtk-v1 | 0 | python | def single_appliance_disaggregate(self, test_main_list, model=None, do_preprocessing=True):
"\n Perfroms load disaggregtaion for single appliance models. If Optuna was used during the \n training phase, it disaggregtaes the test_main_list using only the best trial. \n If cross-validation is use... | def single_appliance_disaggregate(self, test_main_list, model=None, do_preprocessing=True):
"\n Perfroms load disaggregtaion for single appliance models. If Optuna was used during the \n training phase, it disaggregtaes the test_main_list using only the best trial. \n If cross-validation is use... |
80aaf9c41d2a71a400abb43113d83d2af3fe4915e6e28396ff79e4abebd283f8 | def objective(self, trial, train_loader=None, val_loader=None, fold_idx=None):
'The objective function to be used with optuna. This function requires the model under study to \n implement a static function called suggest_hparams() [see the model documentation for more informations]\n\n :param trial: O... | The objective function to be used with optuna. This function requires the model under study to
implement a static function called suggest_hparams() [see the model documentation for more informations]
:param trial: Optuna.trial
:param train_loader: training dataLoader for the current experiment. Defaults to None.
:typ... | deep_nilmtk/disaggregate/nilm_experiment.py | objective | reviwe/deep-nilmtk-v1 | 0 | python | def objective(self, trial, train_loader=None, val_loader=None, fold_idx=None):
'The objective function to be used with optuna. This function requires the model under study to \n implement a static function called suggest_hparams() [see the model documentation for more informations]\n\n :param trial: O... | def objective(self, trial, train_loader=None, val_loader=None, fold_idx=None):
'The objective function to be used with optuna. This function requires the model under study to \n implement a static function called suggest_hparams() [see the model documentation for more informations]\n\n :param trial: O... |
7cd969ed06d02c8e8c6e0fa8cf6e8683263ba4946eb324c3d0748fc2340676b9 | def objective_cv(self, trial):
'The objective function for Optuna when cross-validation is also used\n\n :param trial: An optuna trial\n :type trial: Optuna.Trial\n :return: average of best loss validations for considered folds\n :rtype: float\n '
fold = TimeSeriesSplit(n_spli... | The objective function for Optuna when cross-validation is also used
:param trial: An optuna trial
:type trial: Optuna.Trial
:return: average of best loss validations for considered folds
:rtype: float | deep_nilmtk/disaggregate/nilm_experiment.py | objective_cv | reviwe/deep-nilmtk-v1 | 0 | python | def objective_cv(self, trial):
'The objective function for Optuna when cross-validation is also used\n\n :param trial: An optuna trial\n :type trial: Optuna.Trial\n :return: average of best loss validations for considered folds\n :rtype: float\n '
fold = TimeSeriesSplit(n_spli... | def objective_cv(self, trial):
'The objective function for Optuna when cross-validation is also used\n\n :param trial: An optuna trial\n :type trial: Optuna.Trial\n :return: average of best loss validations for considered folds\n :rtype: float\n '
fold = TimeSeriesSplit(n_spli... |
3fc66de6c80bf603a92bbbb6b5ca54a49adc552d5f833f7400c3f304f49d23d5 | def get_net_and_loaders(self):
'Returns an instance of the specified model and the correspanding dataloader\n\n :return: (model , dataloader)\n :rtype: tuple(nn.Module, torch.utils.data.Dataset)\n '
net = NILM_MODELS[self.hparams['model_name']]['model'](self.hparams)
data = partial(NILM... | Returns an instance of the specified model and the correspanding dataloader
:return: (model , dataloader)
:rtype: tuple(nn.Module, torch.utils.data.Dataset) | deep_nilmtk/disaggregate/nilm_experiment.py | get_net_and_loaders | reviwe/deep-nilmtk-v1 | 0 | python | def get_net_and_loaders(self):
'Returns an instance of the specified model and the correspanding dataloader\n\n :return: (model , dataloader)\n :rtype: tuple(nn.Module, torch.utils.data.Dataset)\n '
net = NILM_MODELS[self.hparams['model_name']]['model'](self.hparams)
data = partial(NILM... | def get_net_and_loaders(self):
'Returns an instance of the specified model and the correspanding dataloader\n\n :return: (model , dataloader)\n :rtype: tuple(nn.Module, torch.utils.data.Dataset)\n '
net = NILM_MODELS[self.hparams['model_name']]['model'](self.hparams)
data = partial(NILM... |
6712f1c4d321ce1cb297afff5f7eb859240a29524adac8848b58ffda99811061 | def save_best_model(self, study, trial):
'Keeps track of the trial giving best results\n\n :param study: Optuna study\n :param trial: Optuna trial\n '
if (study.best_trial.number == trial.number):
study.set_user_attr(key='trial_ID', value=trial.number)
study.set_user_attr(ke... | Keeps track of the trial giving best results
:param study: Optuna study
:param trial: Optuna trial | deep_nilmtk/disaggregate/nilm_experiment.py | save_best_model | reviwe/deep-nilmtk-v1 | 0 | python | def save_best_model(self, study, trial):
'Keeps track of the trial giving best results\n\n :param study: Optuna study\n :param trial: Optuna trial\n '
if (study.best_trial.number == trial.number):
study.set_user_attr(key='trial_ID', value=trial.number)
study.set_user_attr(ke... | def save_best_model(self, study, trial):
'Keeps track of the trial giving best results\n\n :param study: Optuna study\n :param trial: Optuna trial\n '
if (study.best_trial.number == trial.number):
study.set_user_attr(key='trial_ID', value=trial.number)
study.set_user_attr(ke... |
e1d8872ad361929ab047025470236ff401d506c668c6982ba33b940e3ee0ffd8 | def single_appliance_fit(self):
'\n Train the specified models for each appliance separately taking into consideration\n the use of cross-validation and hyper-parameters optimisation. The checkpoints for \n each model are saved in the correspondng path.\n '
self.exp_name = f"{self.hp... | Train the specified models for each appliance separately taking into consideration
the use of cross-validation and hyper-parameters optimisation. The checkpoints for
each model are saved in the correspondng path. | deep_nilmtk/disaggregate/nilm_experiment.py | single_appliance_fit | reviwe/deep-nilmtk-v1 | 0 | python | def single_appliance_fit(self):
'\n Train the specified models for each appliance separately taking into consideration\n the use of cross-validation and hyper-parameters optimisation. The checkpoints for \n each model are saved in the correspondng path.\n '
self.exp_name = f"{self.hp... | def single_appliance_fit(self):
'\n Train the specified models for each appliance separately taking into consideration\n the use of cross-validation and hyper-parameters optimisation. The checkpoints for \n each model are saved in the correspondng path.\n '
self.exp_name = f"{self.hp... |
fb609dd973cc13146630306c7a264b6131bd0935caea9db9735b3af77a3fc8cd | def train_model(self, appliance_name, train_loader, val_loader, exp_name, mean=None, std=None, trial_idx=None, fold_idx=None, model=None):
'Trains a single PyTorch model.\n\n :param appliance_name: Name of teh appliance to be modeled\n :type appliance_name: str\n :param train_loader: training d... | Trains a single PyTorch model.
:param appliance_name: Name of teh appliance to be modeled
:type appliance_name: str
:param train_loader: training dataLoader for the current appliance
:type train_loader: DataLoader
:param val_loader: validation dataLoader for the current appliance
:type val_loader: DataLoader
:param ex... | deep_nilmtk/disaggregate/nilm_experiment.py | train_model | reviwe/deep-nilmtk-v1 | 0 | python | def train_model(self, appliance_name, train_loader, val_loader, exp_name, mean=None, std=None, trial_idx=None, fold_idx=None, model=None):
'Trains a single PyTorch model.\n\n :param appliance_name: Name of teh appliance to be modeled\n :type appliance_name: str\n :param train_loader: training d... | def train_model(self, appliance_name, train_loader, val_loader, exp_name, mean=None, std=None, trial_idx=None, fold_idx=None, model=None):
'Trains a single PyTorch model.\n\n :param appliance_name: Name of teh appliance to be modeled\n :type appliance_name: str\n :param train_loader: training d... |
60e7f3a6ff77286be77987327ec2d86ed0e2c20dc70deb08771519a8a4287e9e | def multi_appliance_disaggregate(self, test_main_list, model=None, do_preprocessing=True):
"\n Perfroms load disaggregtaion for single appliance models. If Optuna was used during the \n training phase, it disaggregtaes the test_main_list using only the best trial. \n If cross-validation is used... | Perfroms load disaggregtaion for single appliance models. If Optuna was used during the
training phase, it disaggregtaes the test_main_list using only the best trial.
If cross-validation is used during training, it returns the average of predictions
cross all folds for each applaince. In this later case, the predict... | deep_nilmtk/disaggregate/nilm_experiment.py | multi_appliance_disaggregate | reviwe/deep-nilmtk-v1 | 0 | python | def multi_appliance_disaggregate(self, test_main_list, model=None, do_preprocessing=True):
"\n Perfroms load disaggregtaion for single appliance models. If Optuna was used during the \n training phase, it disaggregtaes the test_main_list using only the best trial. \n If cross-validation is used... | def multi_appliance_disaggregate(self, test_main_list, model=None, do_preprocessing=True):
"\n Perfroms load disaggregtaion for single appliance models. If Optuna was used during the \n training phase, it disaggregtaes the test_main_list using only the best trial. \n If cross-validation is used... |
b954b4599e5e4f227f0e9f0d920f7744e1038682b9362117339305d436fafeb8 | def multi_appliance_fit(self):
'\n Train the specified models for each appliance separately taking into consideration\n the use of cross-validation and hyper-parameters optimisation. The checkpoints for \n each model are saved in the correspondng path.\n '
self.exp_name = f"{self.hpa... | Train the specified models for each appliance separately taking into consideration
the use of cross-validation and hyper-parameters optimisation. The checkpoints for
each model are saved in the correspondng path. | deep_nilmtk/disaggregate/nilm_experiment.py | multi_appliance_fit | reviwe/deep-nilmtk-v1 | 0 | python | def multi_appliance_fit(self):
'\n Train the specified models for each appliance separately taking into consideration\n the use of cross-validation and hyper-parameters optimisation. The checkpoints for \n each model are saved in the correspondng path.\n '
self.exp_name = f"{self.hpa... | def multi_appliance_fit(self):
'\n Train the specified models for each appliance separately taking into consideration\n the use of cross-validation and hyper-parameters optimisation. The checkpoints for \n each model are saved in the correspondng path.\n '
self.exp_name = f"{self.hpa... |
6f713870ca44fdd7c64b8609185febcb535533540be9bbcd9e72f51aa65436e5 | def parse_int(string):
'\n Finds the first integer in a string without casting it.\n :param string:\n :return:\n '
matches = re.findall('(\\d+)', string)
if matches:
return matches[0]
else:
return None | Finds the first integer in a string without casting it.
:param string:
:return: | scraper/scraper/loaders.py | parse_int | viktorfa/F033583-project | 2 | python | def parse_int(string):
'\n Finds the first integer in a string without casting it.\n :param string:\n :return:\n '
matches = re.findall('(\\d+)', string)
if matches:
return matches[0]
else:
return None | def parse_int(string):
'\n Finds the first integer in a string without casting it.\n :param string:\n :return:\n '
matches = re.findall('(\\d+)', string)
if matches:
return matches[0]
else:
return None<|docstring|>Finds the first integer in a string without casting it.
:param... |
a32fb8a52de54b39ed2597ed14f8b01b7faa022cb22787cc39655f442af3d985 | def parse_float(string):
'\n Finds the first float in a string without casting it.\n :param string:\n :return:\n '
matches = re.findall('(\\d+\\.\\d+)', string)
if matches:
return matches[0]
else:
return None | Finds the first float in a string without casting it.
:param string:
:return: | scraper/scraper/loaders.py | parse_float | viktorfa/F033583-project | 2 | python | def parse_float(string):
'\n Finds the first float in a string without casting it.\n :param string:\n :return:\n '
matches = re.findall('(\\d+\\.\\d+)', string)
if matches:
return matches[0]
else:
return None | def parse_float(string):
'\n Finds the first float in a string without casting it.\n :param string:\n :return:\n '
matches = re.findall('(\\d+\\.\\d+)', string)
if matches:
return matches[0]
else:
return None<|docstring|>Finds the first float in a string without casting it.
:... |
125f69b68d239b9a2af7179fcead7f26b7802f23b7ffc8c8451309db9f5c223c | @property
def url_format(self):
'Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017'
return '{}-{}-{}'.format(self.month, self.day, self.year) | Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017 | tools/util_date.py | url_format | osvenskan/data_rescue_D62CD1E5 | 0 | python | @property
def url_format(self):
return '{}-{}-{}'.format(self.month, self.day, self.year) | @property
def url_format(self):
return '{}-{}-{}'.format(self.month, self.day, self.year)<|docstring|>Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017<|endoftext|> |
125f69b68d239b9a2af7179fcead7f26b7802f23b7ffc8c8451309db9f5c223c | @property
def url_format(self):
'Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017'
return '{}-{}-{}'.format(self.month, self.day, self.year) | Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017 | tools/util_date.py | url_format | osvenskan/data_rescue_D62CD1E5 | 0 | python | @property
def url_format(self):
return '{}-{}-{}'.format(self.month, self.day, self.year) | @property
def url_format(self):
return '{}-{}-{}'.format(self.month, self.day, self.year)<|docstring|>Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017<|endoftext|> |
9b9c69f3faa45ab63c624a7974fe1ae222622f9967ec39ca296a2f24c2f0bfc6 | @property
def url_format(self):
'Return e.g. Tue Feb 14 2017'
return self.strftime('%a %b %d %Y') | Return e.g. Tue Feb 14 2017 | tools/util_date.py | url_format | osvenskan/data_rescue_D62CD1E5 | 0 | python | @property
def url_format(self):
return self.strftime('%a %b %d %Y') | @property
def url_format(self):
return self.strftime('%a %b %d %Y')<|docstring|>Return e.g. Tue Feb 14 2017<|endoftext|> |
bb8dd71d7b0d5ffa5600042a14e2889f088c3612eb76b730363caf8685550129 | @property
def url_format_for_geographic_type(self):
'Return e.g. Tue Feb 14 2017'
return self.strftime('%a %b %d %Y') | Return e.g. Tue Feb 14 2017 | tools/util_date.py | url_format_for_geographic_type | osvenskan/data_rescue_D62CD1E5 | 0 | python | @property
def url_format_for_geographic_type(self):
return self.strftime('%a %b %d %Y') | @property
def url_format_for_geographic_type(self):
return self.strftime('%a %b %d %Y')<|docstring|>Return e.g. Tue Feb 14 2017<|endoftext|> |
033f366a11599207fead6ff1ddfd9e36907b8620662114dc80d1f58703719538 | @property
def url_format_for_attribute(self):
'Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017'
return '{}-{}-{}'.format(self.month, self.day, self.year) | Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017 | tools/util_date.py | url_format_for_attribute | osvenskan/data_rescue_D62CD1E5 | 0 | python | @property
def url_format_for_attribute(self):
return '{}-{}-{}'.format(self.month, self.day, self.year) | @property
def url_format_for_attribute(self):
return '{}-{}-{}'.format(self.month, self.day, self.year)<|docstring|>Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017<|endoftext|> |
bb8dd71d7b0d5ffa5600042a14e2889f088c3612eb76b730363caf8685550129 | @property
def url_format_for_geographic_type(self):
'Return e.g. Tue Feb 14 2017'
return self.strftime('%a %b %d %Y') | Return e.g. Tue Feb 14 2017 | tools/util_date.py | url_format_for_geographic_type | osvenskan/data_rescue_D62CD1E5 | 0 | python | @property
def url_format_for_geographic_type(self):
return self.strftime('%a %b %d %Y') | @property
def url_format_for_geographic_type(self):
return self.strftime('%a %b %d %Y')<|docstring|>Return e.g. Tue Feb 14 2017<|endoftext|> |
033f366a11599207fead6ff1ddfd9e36907b8620662114dc80d1f58703719538 | @property
def url_format_for_attribute(self):
'Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017'
return '{}-{}-{}'.format(self.month, self.day, self.year) | Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017 | tools/util_date.py | url_format_for_attribute | osvenskan/data_rescue_D62CD1E5 | 0 | python | @property
def url_format_for_attribute(self):
return '{}-{}-{}'.format(self.month, self.day, self.year) | @property
def url_format_for_attribute(self):
return '{}-{}-{}'.format(self.month, self.day, self.year)<|docstring|>Return m-d-yyyy, e.g. 2-14-2017 for Feb 14th 2017<|endoftext|> |
a129211f82a3ee9841c1499eb3c91652bcd064d6878852523fa368f1dcafb448 | def get_language(query: str) -> str:
'Tries to work out the highlight.js language of a given file name or\n shebang. Returns an empty string if none match.\n '
query = query.lower()
for language in LANGUAGES:
if query.endswith(language):
return language
return '' | Tries to work out the highlight.js language of a given file name or
shebang. Returns an empty string if none match. | discordjspy/addons/jishaku/hljs.py | get_language | Gelbpunkt/discord.jspy | 5 | python | def get_language(query: str) -> str:
'Tries to work out the highlight.js language of a given file name or\n shebang. Returns an empty string if none match.\n '
query = query.lower()
for language in LANGUAGES:
if query.endswith(language):
return language
return | def get_language(query: str) -> str:
'Tries to work out the highlight.js language of a given file name or\n shebang. Returns an empty string if none match.\n '
query = query.lower()
for language in LANGUAGES:
if query.endswith(language):
return language
return <|docstring|>Trie... |
eda9689e73dfc9ba66d6b44f57c675e7616cbc892162ed72291467b6b9406a2b | def notebook_node_from_string_list(string_list):
'\n Reads a notebook from a string list and returns the NotebookNode\n object.\n\n :param string_list: The notebook file contents as list of strings\n (linewise).\n :return: The notebook as NotebookNode.\n '
return... | Reads a notebook from a string list and returns the NotebookNode
object.
:param string_list: The notebook file contents as list of strings
(linewise).
:return: The notebook as NotebookNode. | venv/lib/python3.5/site-packages/bears/python/PEP8NotebookBear.py | notebook_node_from_string_list | prashant0598/CoffeeApp | 0 | python | def notebook_node_from_string_list(string_list):
'\n Reads a notebook from a string list and returns the NotebookNode\n object.\n\n :param string_list: The notebook file contents as list of strings\n (linewise).\n :return: The notebook as NotebookNode.\n '
return... | def notebook_node_from_string_list(string_list):
'\n Reads a notebook from a string list and returns the NotebookNode\n object.\n\n :param string_list: The notebook file contents as list of strings\n (linewise).\n :return: The notebook as NotebookNode.\n '
return... |
77b7e08b4c4de40f6b138038232ee877ab2a8f3b1f86f9a37f3da930ee198a79 | def notebook_node_to_string_list(notebook_node):
'\n Writes a NotebookNode to a list of strings.\n\n :param notebook_node: The notebook as NotebookNode to write.\n :return: The notebook as list of strings (linewise).\n '
return nbformat.writes(notebook_node, nbformat.NO_CONVERT).splitli... | Writes a NotebookNode to a list of strings.
:param notebook_node: The notebook as NotebookNode to write.
:return: The notebook as list of strings (linewise). | venv/lib/python3.5/site-packages/bears/python/PEP8NotebookBear.py | notebook_node_to_string_list | prashant0598/CoffeeApp | 0 | python | def notebook_node_to_string_list(notebook_node):
'\n Writes a NotebookNode to a list of strings.\n\n :param notebook_node: The notebook as NotebookNode to write.\n :return: The notebook as list of strings (linewise).\n '
return nbformat.writes(notebook_node, nbformat.NO_CONVERT).splitli... | def notebook_node_to_string_list(notebook_node):
'\n Writes a NotebookNode to a list of strings.\n\n :param notebook_node: The notebook as NotebookNode to write.\n :return: The notebook as list of strings (linewise).\n '
return nbformat.writes(notebook_node, nbformat.NO_CONVERT).splitli... |
57e0ea8dd5ae06f82fd743be968ab1697128d09c07dc5c2fc52fa4213e0477b4 | def autopep8_fix_code_cell(source, options=None, apply_config=None):
"\n Applies autopep8.fix_code and takes care of newline characters.\n\n autopep8.fix_code automatically adds a final newline at the end,\n e.g. ``autopep8.fix_code('a=1')`` yields 'a = 1\\n'.\n Note that this is not related to the 'W29... | Applies autopep8.fix_code and takes care of newline characters.
autopep8.fix_code automatically adds a final newline at the end,
e.g. ``autopep8.fix_code('a=1')`` yields 'a = 1\n'.
Note that this is not related to the 'W292' flag, i.e.
``autopep8.fix_code('a=1', options=dict(ignore=('W292',)))`` gives
the same result.... | venv/lib/python3.5/site-packages/bears/python/PEP8NotebookBear.py | autopep8_fix_code_cell | prashant0598/CoffeeApp | 0 | python | def autopep8_fix_code_cell(source, options=None, apply_config=None):
"\n Applies autopep8.fix_code and takes care of newline characters.\n\n autopep8.fix_code automatically adds a final newline at the end,\n e.g. ``autopep8.fix_code('a=1')`` yields 'a = 1\\n'.\n Note that this is not related to the 'W29... | def autopep8_fix_code_cell(source, options=None, apply_config=None):
"\n Applies autopep8.fix_code and takes care of newline characters.\n\n autopep8.fix_code automatically adds a final newline at the end,\n e.g. ``autopep8.fix_code('a=1')`` yields 'a = 1\\n'.\n Note that this is not related to the 'W29... |
2d8dc63a0480f1633aaac830535d86dfd7584a6e08a6222fbe46f13c1f0ca6c3 | def run(self, filename, file, max_line_length: int=79, indent_size: int=SpacingHelper.DEFAULT_TAB_WIDTH, pep_ignore: typed_list(str)=(), pep_select: typed_list(str)=(), local_pep8_config: bool=False):
'\n Detects and fixes PEP8 incompliant code in Jupyter Notebooks. This bear\n will not change functio... | Detects and fixes PEP8 incompliant code in Jupyter Notebooks. This bear
will not change functionality of the code in any way.
:param max_line_length: Maximum number of characters for a line.
:param indent_size: Number of spaces per indent level.
:param pep_ignore: A list of errors/warnings to ignore.
:p... | venv/lib/python3.5/site-packages/bears/python/PEP8NotebookBear.py | run | prashant0598/CoffeeApp | 0 | python | def run(self, filename, file, max_line_length: int=79, indent_size: int=SpacingHelper.DEFAULT_TAB_WIDTH, pep_ignore: typed_list(str)=(), pep_select: typed_list(str)=(), local_pep8_config: bool=False):
'\n Detects and fixes PEP8 incompliant code in Jupyter Notebooks. This bear\n will not change functio... | def run(self, filename, file, max_line_length: int=79, indent_size: int=SpacingHelper.DEFAULT_TAB_WIDTH, pep_ignore: typed_list(str)=(), pep_select: typed_list(str)=(), local_pep8_config: bool=False):
'\n Detects and fixes PEP8 incompliant code in Jupyter Notebooks. This bear\n will not change functio... |
affe7a6e9615ddd89985087426ce951021b6a1c089646f4b050d5e368998b218 | def run_file(file_path: Path, is_console_app: bool, args: str):
' Decide, if a file should be opened or executed and call the appropriate method '
if (not file_path.is_file()):
return
if is_file_executable(file_path):
execute_app(file_path, is_console_app, args)
else:
open_file(f... | Decide, if a file should be opened or executed and call the appropriate method | src/conan_app_launcher/components/file_runner.py | run_file | goszpeti/conan_app_launcher | 5 | python | def run_file(file_path: Path, is_console_app: bool, args: str):
' '
if (not file_path.is_file()):
return
if is_file_executable(file_path):
execute_app(file_path, is_console_app, args)
else:
open_file(file_path) | def run_file(file_path: Path, is_console_app: bool, args: str):
' '
if (not file_path.is_file()):
return
if is_file_executable(file_path):
execute_app(file_path, is_console_app, args)
else:
open_file(file_path)<|docstring|>Decide, if a file should be opened or executed and call ... |
b56c91fdfd6d5ae93dea84eb754007216edf6ab27bd17a4c2b6fc792b5ef825b | def execute_app(executable: Path, is_console_app: bool, args: str) -> int:
'\n Executes an application with args and optionally spawns a new shell\n as specified in the app entry.\n Returns the pid of the new process.\n '
if executable.absolute().is_file():
cmd = [str(executable)]
if... | Executes an application with args and optionally spawns a new shell
as specified in the app entry.
Returns the pid of the new process. | src/conan_app_launcher/components/file_runner.py | execute_app | goszpeti/conan_app_launcher | 5 | python | def execute_app(executable: Path, is_console_app: bool, args: str) -> int:
'\n Executes an application with args and optionally spawns a new shell\n as specified in the app entry.\n Returns the pid of the new process.\n '
if executable.absolute().is_file():
cmd = [str(executable)]
if... | def execute_app(executable: Path, is_console_app: bool, args: str) -> int:
'\n Executes an application with args and optionally spawns a new shell\n as specified in the app entry.\n Returns the pid of the new process.\n '
if executable.absolute().is_file():
cmd = [str(executable)]
if... |
0ade625e82d498e531884f6db2598e4bd8a7fd99479bdb1f334d8ad2729ad0cd | def open_file(file: Path):
' Open files with their assocoiated programs '
if file.absolute().is_file():
if (platform.system() == 'Windows'):
os.startfile(str(file))
elif (platform.system() == 'Linux'):
subprocess.call(('xdg-open', str(file))) | Open files with their assocoiated programs | src/conan_app_launcher/components/file_runner.py | open_file | goszpeti/conan_app_launcher | 5 | python | def open_file(file: Path):
' '
if file.absolute().is_file():
if (platform.system() == 'Windows'):
os.startfile(str(file))
elif (platform.system() == 'Linux'):
subprocess.call(('xdg-open', str(file))) | def open_file(file: Path):
' '
if file.absolute().is_file():
if (platform.system() == 'Windows'):
os.startfile(str(file))
elif (platform.system() == 'Linux'):
subprocess.call(('xdg-open', str(file)))<|docstring|>Open files with their assocoiated programs<|endoftext|> |
62b52dcd07afd3f86b2707683ddbbaa54bbcfee89f3ee468316292a14086d520 | def __users_me(self, **kwargs):
'users_me # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n\n >>> thread = api.users_me(async_req=True)\n >>> result = thread.get()\n\n\n ... | users_me # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.users_me(async_req=True)
>>> result = thread.get()
Keyword Args:
_return_http_data_only (bool): response data without head status
code and hea... | src/gretel_client/rest/api/users_api.py | __users_me | gretelai/gretel-python-client | 23 | python | def __users_me(self, **kwargs):
'users_me # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n\n >>> thread = api.users_me(async_req=True)\n >>> result = thread.get()\n\n\n ... | def __users_me(self, **kwargs):
'users_me # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n\n >>> thread = api.users_me(async_req=True)\n >>> result = thread.get()\n\n\n ... |
46a06ed5aaf6d824302dcaea2be3529740c550983f65c1bbe17d92b2ae17a8d5 | def _start(func: Callable, scheduler: Optional[Scheduler]=None) -> Observable:
"Invokes the specified function asynchronously on the specified\n scheduler, surfacing the result through an observable sequence.\n\n Example:\n >>> res = rx3.start(lambda: pprint('hello'))\n >>> res = rx3.start(lambd... | Invokes the specified function asynchronously on the specified
scheduler, surfacing the result through an observable sequence.
Example:
>>> res = rx3.start(lambda: pprint('hello'))
>>> res = rx3.start(lambda: pprint('hello'), rx3.Scheduler.timeout)
Args:
func: Function to run asynchronously.
scheduler... | rx3/core/observable/start.py | _start | samiur/RxPY | 0 | python | def _start(func: Callable, scheduler: Optional[Scheduler]=None) -> Observable:
"Invokes the specified function asynchronously on the specified\n scheduler, surfacing the result through an observable sequence.\n\n Example:\n >>> res = rx3.start(lambda: pprint('hello'))\n >>> res = rx3.start(lambd... | def _start(func: Callable, scheduler: Optional[Scheduler]=None) -> Observable:
"Invokes the specified function asynchronously on the specified\n scheduler, surfacing the result through an observable sequence.\n\n Example:\n >>> res = rx3.start(lambda: pprint('hello'))\n >>> res = rx3.start(lambd... |
ed15beb46b7920ed4dbd3f1fe6a06324ec1044dc0af8b38411ce876a5b99a1f2 | def get_active_announcements():
'Get the active announcements.'
now = arrow.utcnow().to(current_app.config['TIME_ZONE']).naive
return Announcement.query.current.filter((Announcement.active == True), (Announcement.published < now)).order_by(db.desc(Announcement.published)).all() | Get the active announcements. | pygotham/news/__init__.py | get_active_announcements | PyGotham/pygotham | 19 | python | def get_active_announcements():
now = arrow.utcnow().to(current_app.config['TIME_ZONE']).naive
return Announcement.query.current.filter((Announcement.active == True), (Announcement.published < now)).order_by(db.desc(Announcement.published)).all() | def get_active_announcements():
now = arrow.utcnow().to(current_app.config['TIME_ZONE']).naive
return Announcement.query.current.filter((Announcement.active == True), (Announcement.published < now)).order_by(db.desc(Announcement.published)).all()<|docstring|>Get the active announcements.<|endoftext|> |
ed0c8069cb1d8d32651516fba5b0c6ab2ed07d40ef684b0832f39ac8431e43ca | def get_active_call_to_action():
'Return the active call to action.'
now = arrow.utcnow().to(current_app.config['TIME_ZONE']).naive
return CallToAction.query.current.filter((CallToAction.active == True), (CallToAction.begins < now), db.or_((CallToAction.ends > now), (CallToAction.ends == None))).order_by(Ca... | Return the active call to action. | pygotham/news/__init__.py | get_active_call_to_action | PyGotham/pygotham | 19 | python | def get_active_call_to_action():
now = arrow.utcnow().to(current_app.config['TIME_ZONE']).naive
return CallToAction.query.current.filter((CallToAction.active == True), (CallToAction.begins < now), db.or_((CallToAction.ends > now), (CallToAction.ends == None))).order_by(CallToAction.begins, db.desc(CallToAc... | def get_active_call_to_action():
now = arrow.utcnow().to(current_app.config['TIME_ZONE']).naive
return CallToAction.query.current.filter((CallToAction.active == True), (CallToAction.begins < now), db.or_((CallToAction.ends > now), (CallToAction.ends == None))).order_by(CallToAction.begins, db.desc(CallToAc... |
befa8a1763a1e3a99308ba5b2b8d06198ee11c1f8b844a49f2341fe34b08f4a3 | def wjx_sump(url, filename):
"filename = './t.xlsx' 本地正确答案所在名称\n "
imp_data = xlsx_get.get_asw(filename, 1)
net_hold = webdriver.Chrome('chromedriver.exe')
net_hold.get(url)
time.sleep(2)
for i in range(1, (len(imp_data) + 1)):
q_id = ('div' + str(i))
question_hold = net_hold.... | filename = './t.xlsx' 本地正确答案所在名称 | selenuim/wjx_obj.py | wjx_sump | yinboliu-git/- | 0 | python | def wjx_sump(url, filename):
"\n "
imp_data = xlsx_get.get_asw(filename, 1)
net_hold = webdriver.Chrome('chromedriver.exe')
net_hold.get(url)
time.sleep(2)
for i in range(1, (len(imp_data) + 1)):
q_id = ('div' + str(i))
question_hold = net_hold.find_element_by_id(q_id)
... | def wjx_sump(url, filename):
"\n "
imp_data = xlsx_get.get_asw(filename, 1)
net_hold = webdriver.Chrome('chromedriver.exe')
net_hold.get(url)
time.sleep(2)
for i in range(1, (len(imp_data) + 1)):
q_id = ('div' + str(i))
question_hold = net_hold.find_element_by_id(q_id)
... |
1e98bcc545e30d906c332a132a1a5a21fce7d0fef2130f0112d39e95c21b0345 | def update_graph_memory():
"Use Q_G(φ(s), a) ← r + γ max_{a'}( Q_G (φ(s'), a')) )\n r: reward\n γ: discount \n φ: state vector. Each state is some s in S. \n " | Use Q_G(φ(s), a) ← r + γ max_{a'}( Q_G (φ(s'), a')) )
r: reward
γ: discount
φ: state vector. Each state is some s in S. | rl_memory/erik/old/value_prop_associative.py | update_graph_memory | eskalnes/RL_memory | 0 | python | def update_graph_memory():
"Use Q_G(φ(s), a) ← r + γ max_{a'}( Q_G (φ(s'), a')) )\n r: reward\n γ: discount \n φ: state vector. Each state is some s in S. \n " | def update_graph_memory():
"Use Q_G(φ(s), a) ← r + γ max_{a'}( Q_G (φ(s'), a')) )\n r: reward\n γ: discount \n φ: state vector. Each state is some s in S. \n "<|docstring|>Use Q_G(φ(s), a) ← r + γ max_{a'}( Q_G (φ(s'), a')) )
r: reward
γ: discount
φ: state vector. Each state is some s in S.<|endoftex... |
0b8cbc74fe6e202c15f48ac414b6086ab175ef0adbb65e4535d21dcddc49c4d1 | def prepare_parser():
" Parse the command line arguments.\n\n Arguments:\n --input: Name of the input data folder, defaults to 'data'.\n --output: Name of the output file, defaults to 'output.txt'.\n Returns:\n The parser with all the arguments.\n "
parser = argparse.ArgumentParser... | Parse the command line arguments.
Arguments:
--input: Name of the input data folder, defaults to 'data'.
--output: Name of the output file, defaults to 'output.txt'.
Returns:
The parser with all the arguments. | json-to-csv-converter/converter.py | prepare_parser | vkaracic/review-parser | 1 | python | def prepare_parser():
" Parse the command line arguments.\n\n Arguments:\n --input: Name of the input data folder, defaults to 'data'.\n --output: Name of the output file, defaults to 'output.txt'.\n Returns:\n The parser with all the arguments.\n "
parser = argparse.ArgumentParser... | def prepare_parser():
" Parse the command line arguments.\n\n Arguments:\n --input: Name of the input data folder, defaults to 'data'.\n --output: Name of the output file, defaults to 'output.txt'.\n Returns:\n The parser with all the arguments.\n "
parser = argparse.ArgumentParser... |
064f92113f089a0e85dea0b8e80e4b3fa9d2687a68286cb82c29be814953ed8a | def main():
' Reads JSON files from input data folder and saves as CSV with labeled sentiments.\n Labels are 1 for positive, 0 for negative.\n '
POSITIVE = 1
NEGATIVE = 0
parser = prepare_parser()
args = parser.parse_args()
csv_file = csv.writer(open(args.output, 'w'))
csv_file.writero... | Reads JSON files from input data folder and saves as CSV with labeled sentiments.
Labels are 1 for positive, 0 for negative. | json-to-csv-converter/converter.py | main | vkaracic/review-parser | 1 | python | def main():
' Reads JSON files from input data folder and saves as CSV with labeled sentiments.\n Labels are 1 for positive, 0 for negative.\n '
POSITIVE = 1
NEGATIVE = 0
parser = prepare_parser()
args = parser.parse_args()
csv_file = csv.writer(open(args.output, 'w'))
csv_file.writero... | def main():
' Reads JSON files from input data folder and saves as CSV with labeled sentiments.\n Labels are 1 for positive, 0 for negative.\n '
POSITIVE = 1
NEGATIVE = 0
parser = prepare_parser()
args = parser.parse_args()
csv_file = csv.writer(open(args.output, 'w'))
csv_file.writero... |
07dc1d0a22698748efa073f0d0f2313e4c051049b51353d825893fdeb6a89172 | def test_run_charclassml(self):
'test run_charclassml'
config = attr.assoc(run_charclassml.CONFIG_DEFAULT)
config.nn_opt['max_epochs'] = 1
config.train.idxs = [1]
config.train.do_balance = True
config.train.balance_size = 64
config.dev.idxs = [2]
config.test.idxs = [3]
self._test_tra... | test run_charclassml | integration/tests_train.py | test_run_charclassml | bdzimmer/handwriting | 2 | python | def test_run_charclassml(self):
config = attr.assoc(run_charclassml.CONFIG_DEFAULT)
config.nn_opt['max_epochs'] = 1
config.train.idxs = [1]
config.train.do_balance = True
config.train.balance_size = 64
config.dev.idxs = [2]
config.test.idxs = [3]
self._test_training_module(run_charc... | def test_run_charclassml(self):
config = attr.assoc(run_charclassml.CONFIG_DEFAULT)
config.nn_opt['max_epochs'] = 1
config.train.idxs = [1]
config.train.do_balance = True
config.train.balance_size = 64
config.dev.idxs = [2]
config.test.idxs = [3]
self._test_training_module(run_charc... |
f66e23a6f60a064734d348b954437eb6ed91bd48aa0f8051e863a3a434fa1f5d | def test_run_charposml(self):
'test run_charposml'
run_charposml.VERBOSE = True
config = attr.assoc(run_charposml.CONFIG_DEFAULT)
config.train.idxs = [1]
config.nn_opt['max_epochs'] = 1
config.train.do_balance = True
config.train.balance_size = 64
config.dev.idxs = [2]
config.test.id... | test run_charposml | integration/tests_train.py | test_run_charposml | bdzimmer/handwriting | 2 | python | def test_run_charposml(self):
run_charposml.VERBOSE = True
config = attr.assoc(run_charposml.CONFIG_DEFAULT)
config.train.idxs = [1]
config.nn_opt['max_epochs'] = 1
config.train.do_balance = True
config.train.balance_size = 64
config.dev.idxs = [2]
config.test.idxs = [3]
self._t... | def test_run_charposml(self):
run_charposml.VERBOSE = True
config = attr.assoc(run_charposml.CONFIG_DEFAULT)
config.train.idxs = [1]
config.nn_opt['max_epochs'] = 1
config.train.do_balance = True
config.train.balance_size = 64
config.dev.idxs = [2]
config.test.idxs = [3]
self._t... |
3148bb084c3474ec1faa5bba6358cde6d49bbb1326819c94e34e07a04f521c41 | def _test_training_module(self, module, sub_dirname, config):
'helper method: run one of the training modules with config,\n testing that it produces output files'
work_dirname = os.path.join('integration', sub_dirname)
if os.path.exists(work_dirname):
shutil.rmtree(work_dirname)
os.maked... | helper method: run one of the training modules with config,
testing that it produces output files | integration/tests_train.py | _test_training_module | bdzimmer/handwriting | 2 | python | def _test_training_module(self, module, sub_dirname, config):
'helper method: run one of the training modules with config,\n testing that it produces output files'
work_dirname = os.path.join('integration', sub_dirname)
if os.path.exists(work_dirname):
shutil.rmtree(work_dirname)
os.maked... | def _test_training_module(self, module, sub_dirname, config):
'helper method: run one of the training modules with config,\n testing that it produces output files'
work_dirname = os.path.join('integration', sub_dirname)
if os.path.exists(work_dirname):
shutil.rmtree(work_dirname)
os.maked... |
9defd67dc3607bdbdbad802492f17145c1407993e2ca38ee339b1f60bea4ac1d | def run_model_training():
'Run model training using tensorflow\n\n # TODO Refactor the function\n Args:\n\n Output:\n None'
with open('params.yaml', 'r') as fd:
params = yaml.safe_load(fd)
SEED = params['seed']
GCP_BUCKET = params['gcp_bucket']
TEST_SIZE = params['test_size']... | Run model training using tensorflow
# TODO Refactor the function
Args:
Output:
None | src/Model_Training/Model_Training.py | run_model_training | Roger-Parkinson-EHP/ML_Workflow_Demo | 0 | python | def run_model_training():
'Run model training using tensorflow\n\n # TODO Refactor the function\n Args:\n\n Output:\n None'
with open('params.yaml', 'r') as fd:
params = yaml.safe_load(fd)
SEED = params['seed']
GCP_BUCKET = params['gcp_bucket']
TEST_SIZE = params['test_size']... | def run_model_training():
'Run model training using tensorflow\n\n # TODO Refactor the function\n Args:\n\n Output:\n None'
with open('params.yaml', 'r') as fd:
params = yaml.safe_load(fd)
SEED = params['seed']
GCP_BUCKET = params['gcp_bucket']
TEST_SIZE = params['test_size']... |
29ba05b6db315ce65f0cef813cba1957f54797b37e452547af11167095e117a0 | @pytest.fixture()
def bomb():
'A bomb context appropriate for proper testing of all wire sequences\n cases.\n '
bomb = Bomb()
return bomb | A bomb context appropriate for proper testing of all wire sequences
cases. | tests/test_wire_sequences.py | bomb | MartinHarding/ktaned | 1 | python | @pytest.fixture()
def bomb():
'A bomb context appropriate for proper testing of all wire sequences\n cases.\n '
bomb = Bomb()
return bomb | @pytest.fixture()
def bomb():
'A bomb context appropriate for proper testing of all wire sequences\n cases.\n '
bomb = Bomb()
return bomb<|docstring|>A bomb context appropriate for proper testing of all wire sequences
cases.<|endoftext|> |
bbb9a208502d9abdfc936cfc91a6f5ab9d43790fec9be1f21cc86d0df2c61e83 | @pytest.fixture()
def cuts():
'Hand crafted validated result sets for cuts on each wire sequence. The\n named key represents the color of the wire, the index of the list\n represents how many times that wire color has appeared, and the list of\n values represent you should cut the wire if it is connected t... | Hand crafted validated result sets for cuts on each wire sequence. The
named key represents the color of the wire, the index of the list
represents how many times that wire color has appeared, and the list of
values represent you should cut the wire if it is connected to that letter.
e.g. "third time I've seen a red w... | tests/test_wire_sequences.py | cuts | MartinHarding/ktaned | 1 | python | @pytest.fixture()
def cuts():
'Hand crafted validated result sets for cuts on each wire sequence. The\n named key represents the color of the wire, the index of the list\n represents how many times that wire color has appeared, and the list of\n values represent you should cut the wire if it is connected t... | @pytest.fixture()
def cuts():
'Hand crafted validated result sets for cuts on each wire sequence. The\n named key represents the color of the wire, the index of the list\n represents how many times that wire color has appeared, and the list of\n values represent you should cut the wire if it is connected t... |
ab82abc87eb7d5a5557bd3a39bfac95fe4e0e38b397dc422d353cd6c138ea791 | def test_add_wire_invalid_color(bomb):
'Test adding a wire to a sequence with an invalid color.'
wire_sequences = WireSequences(bomb)
expected_exception = 'Color (chartreuse) must be one of {}'.format(wire_sequences.valid_colors)
with pytest.raises(Exception, message=expected_exception):
wire_se... | Test adding a wire to a sequence with an invalid color. | tests/test_wire_sequences.py | test_add_wire_invalid_color | MartinHarding/ktaned | 1 | python | def test_add_wire_invalid_color(bomb):
wire_sequences = WireSequences(bomb)
expected_exception = 'Color (chartreuse) must be one of {}'.format(wire_sequences.valid_colors)
with pytest.raises(Exception, message=expected_exception):
wire_sequences.add_wire('chartreuse', 'c') | def test_add_wire_invalid_color(bomb):
wire_sequences = WireSequences(bomb)
expected_exception = 'Color (chartreuse) must be one of {}'.format(wire_sequences.valid_colors)
with pytest.raises(Exception, message=expected_exception):
wire_sequences.add_wire('chartreuse', 'c')<|docstring|>Test addi... |
db3e86a4a59bb3b230bce0cb4825b69f5d9ef3bd3f1e31c1b04acd7312a09386 | def test_add_wire_invalid_letter(bomb):
'Test adding a wire to a sequence connected to an invalid letter.'
wire_sequences = WireSequences(bomb)
expected_exception = 'Letter (d) must be one of {}'.format(wire_sequences.valid_letters)
with pytest.raises(Exception, message=expected_exception):
wire... | Test adding a wire to a sequence connected to an invalid letter. | tests/test_wire_sequences.py | test_add_wire_invalid_letter | MartinHarding/ktaned | 1 | python | def test_add_wire_invalid_letter(bomb):
wire_sequences = WireSequences(bomb)
expected_exception = 'Letter (d) must be one of {}'.format(wire_sequences.valid_letters)
with pytest.raises(Exception, message=expected_exception):
wire_sequences.add_wire('red', 'd') | def test_add_wire_invalid_letter(bomb):
wire_sequences = WireSequences(bomb)
expected_exception = 'Letter (d) must be one of {}'.format(wire_sequences.valid_letters)
with pytest.raises(Exception, message=expected_exception):
wire_sequences.add_wire('red', 'd')<|docstring|>Test adding a wire to ... |
83c2fcce74263bb01577f68f1e4c189c38ca8882af6ae773ae8659d2d6b06b1d | def test_add_wire_by_color_letter(bomb, cuts):
'Test adding wire by color and letter (iterates through every color,\n letter, and appearance combination).\n '
for color in ['red', 'blue', 'black']:
for letter in ['a', 'b', 'c']:
wire_sequences = WireSequences(bomb)
for cut ... | Test adding wire by color and letter (iterates through every color,
letter, and appearance combination). | tests/test_wire_sequences.py | test_add_wire_by_color_letter | MartinHarding/ktaned | 1 | python | def test_add_wire_by_color_letter(bomb, cuts):
'Test adding wire by color and letter (iterates through every color,\n letter, and appearance combination).\n '
for color in ['red', 'blue', 'black']:
for letter in ['a', 'b', 'c']:
wire_sequences = WireSequences(bomb)
for cut ... | def test_add_wire_by_color_letter(bomb, cuts):
'Test adding wire by color and letter (iterates through every color,\n letter, and appearance combination).\n '
for color in ['red', 'blue', 'black']:
for letter in ['a', 'b', 'c']:
wire_sequences = WireSequences(bomb)
for cut ... |
93aa0358eb04d9df0ca7f8069c8239debfcf716ee675de635aadb3b7f3f7cbeb | def test_add_wire_mixed(bomb):
'Test some random wire sequences.'
wire_sequences = WireSequences(bomb)
wires = [('red', 'c', True), ('blue', 'a', False), ('black', 'b', True), ('blue', 'a', True), ('red', 'c', False), ('black', 'b', False), ('red', 'a', True), ('blue', 'c', False), ('black', 'b', True)]
... | Test some random wire sequences. | tests/test_wire_sequences.py | test_add_wire_mixed | MartinHarding/ktaned | 1 | python | def test_add_wire_mixed(bomb):
wire_sequences = WireSequences(bomb)
wires = [('red', 'c', True), ('blue', 'a', False), ('black', 'b', True), ('blue', 'a', True), ('red', 'c', False), ('black', 'b', False), ('red', 'a', True), ('blue', 'c', False), ('black', 'b', True)]
for wire in wires:
(color... | def test_add_wire_mixed(bomb):
wire_sequences = WireSequences(bomb)
wires = [('red', 'c', True), ('blue', 'a', False), ('black', 'b', True), ('blue', 'a', True), ('red', 'c', False), ('black', 'b', False), ('red', 'a', True), ('blue', 'c', False), ('black', 'b', True)]
for wire in wires:
(color... |
c5da5dc5ab7083bf49e69e9f8c61cd3f7f28f32727415fb13d886a137e534014 | def math2html(formula):
'Convert some TeX math to HTML.'
factory = FormulaFactory()
whole = factory.parseformula(formula)
FormulaProcessor().process(whole)
whole.process()
return ''.join(whole.gethtml()) | Convert some TeX math to HTML. | Lib/site-packages/docutils/utils/math/math2html.py | math2html | edupyter/EDUPYTER | 2 | python | def math2html(formula):
factory = FormulaFactory()
whole = factory.parseformula(formula)
FormulaProcessor().process(whole)
whole.process()
return .join(whole.gethtml()) | def math2html(formula):
factory = FormulaFactory()
whole = factory.parseformula(formula)
FormulaProcessor().process(whole)
whole.process()
return .join(whole.gethtml())<|docstring|>Convert some TeX math to HTML.<|endoftext|> |
f24277821d9a641dca613cb77393656b4e278d85aa264faa7b7c5b89721af99f | def main():
'Main function, called if invoked from the command line'
args = sys.argv
Options().parseoptions(args)
if (len(args) != 1):
Trace.error('Usage: math2html.py escaped_string')
exit()
result = math2html(args[0])
Trace.message(result) | Main function, called if invoked from the command line | Lib/site-packages/docutils/utils/math/math2html.py | main | edupyter/EDUPYTER | 2 | python | def main():
args = sys.argv
Options().parseoptions(args)
if (len(args) != 1):
Trace.error('Usage: math2html.py escaped_string')
exit()
result = math2html(args[0])
Trace.message(result) | def main():
args = sys.argv
Options().parseoptions(args)
if (len(args) != 1):
Trace.error('Usage: math2html.py escaped_string')
exit()
result = math2html(args[0])
Trace.message(result)<|docstring|>Main function, called if invoked from the command line<|endoftext|> |
ef97645dcd8b9754745b191c29b29d446897f222c55125ce90ae0328d990d0ed | def debug(cls, message):
'Show a debug message'
if ((not Trace.debugmode) or Trace.quietmode):
return
Trace.show(message, sys.stdout) | Show a debug message | Lib/site-packages/docutils/utils/math/math2html.py | debug | edupyter/EDUPYTER | 2 | python | def debug(cls, message):
if ((not Trace.debugmode) or Trace.quietmode):
return
Trace.show(message, sys.stdout) | def debug(cls, message):
if ((not Trace.debugmode) or Trace.quietmode):
return
Trace.show(message, sys.stdout)<|docstring|>Show a debug message<|endoftext|> |
0e5b9c016a9d4f7d24161573c57eb2608094dceea90401b145ce96a7fc1eaf47 | def message(cls, message):
'Show a trace message'
if Trace.quietmode:
return
if (Trace.prefix and Trace.showlinesmode):
message = (Trace.prefix + message)
Trace.show(message, sys.stdout) | Show a trace message | Lib/site-packages/docutils/utils/math/math2html.py | message | edupyter/EDUPYTER | 2 | python | def message(cls, message):
if Trace.quietmode:
return
if (Trace.prefix and Trace.showlinesmode):
message = (Trace.prefix + message)
Trace.show(message, sys.stdout) | def message(cls, message):
if Trace.quietmode:
return
if (Trace.prefix and Trace.showlinesmode):
message = (Trace.prefix + message)
Trace.show(message, sys.stdout)<|docstring|>Show a trace message<|endoftext|> |
bef16f7e7e2a238f039c0b9a1872d712ce6154c8f4e005f6ed6701a357cf8eb6 | def error(cls, message):
'Show an error message'
message = ('* ' + message)
if (Trace.prefix and Trace.showlinesmode):
message = (Trace.prefix + message)
Trace.show(message, sys.stderr) | Show an error message | Lib/site-packages/docutils/utils/math/math2html.py | error | edupyter/EDUPYTER | 2 | python | def error(cls, message):
message = ('* ' + message)
if (Trace.prefix and Trace.showlinesmode):
message = (Trace.prefix + message)
Trace.show(message, sys.stderr) | def error(cls, message):
message = ('* ' + message)
if (Trace.prefix and Trace.showlinesmode):
message = (Trace.prefix + message)
Trace.show(message, sys.stderr)<|docstring|>Show an error message<|endoftext|> |
dbf8bf09f41eff2710ce880753a36053194174db62974597ab84034850c991f9 | def fatal(cls, message):
'Show an error message and terminate'
Trace.error(('FATAL: ' + message))
exit((- 1)) | Show an error message and terminate | Lib/site-packages/docutils/utils/math/math2html.py | fatal | edupyter/EDUPYTER | 2 | python | def fatal(cls, message):
Trace.error(('FATAL: ' + message))
exit((- 1)) | def fatal(cls, message):
Trace.error(('FATAL: ' + message))
exit((- 1))<|docstring|>Show an error message and terminate<|endoftext|> |
c431322ea34926e8df5ebf04932cc8c4266bf6259dd9329a42264217c1087b5a | def show(cls, message, channel):
'Show a message out of a channel'
if (sys.version_info < (3, 0)):
message = message.encode('utf-8')
channel.write((message + '\n')) | Show a message out of a channel | Lib/site-packages/docutils/utils/math/math2html.py | show | edupyter/EDUPYTER | 2 | python | def show(cls, message, channel):
if (sys.version_info < (3, 0)):
message = message.encode('utf-8')
channel.write((message + '\n')) | def show(cls, message, channel):
if (sys.version_info < (3, 0)):
message = message.encode('utf-8')
channel.write((message + '\n'))<|docstring|>Show a message out of a channel<|endoftext|> |
dcea4c5623947b569e40a349e26151c43d72a7aa0347c2edf19299f215dc75c3 | def parseoptions(self, args):
'Parse command line options'
if (len(args) == 0):
return None
while ((len(args) > 0) and args[0].startswith('--')):
(key, value) = self.readoption(args)
if (not key):
return (('Option ' + value) + ' not recognized')
if (not value):
... | Parse command line options | Lib/site-packages/docutils/utils/math/math2html.py | parseoptions | edupyter/EDUPYTER | 2 | python | def parseoptions(self, args):
if (len(args) == 0):
return None
while ((len(args) > 0) and args[0].startswith('--')):
(key, value) = self.readoption(args)
if (not key):
return (('Option ' + value) + ' not recognized')
if (not value):
return (('Option '... | def parseoptions(self, args):
if (len(args) == 0):
return None
while ((len(args) > 0) and args[0].startswith('--')):
(key, value) = self.readoption(args)
if (not key):
return (('Option ' + value) + ' not recognized')
if (not value):
return (('Option '... |
45d75e57d485dd7447afc78e8b20ea35a382ceffa6d4efa8fcde46b0e6ccd513 | def readoption(self, args):
'Read the key and value for an option'
arg = args[0][2:]
del args[0]
if ('=' in arg):
key = self.readequalskey(arg, args)
else:
key = arg.replace('-', '')
if (not hasattr(self.options, key)):
return (None, key)
current = getattr(self.option... | Read the key and value for an option | Lib/site-packages/docutils/utils/math/math2html.py | readoption | edupyter/EDUPYTER | 2 | python | def readoption(self, args):
arg = args[0][2:]
del args[0]
if ('=' in arg):
key = self.readequalskey(arg, args)
else:
key = arg.replace('-', )
if (not hasattr(self.options, key)):
return (None, key)
current = getattr(self.options, key)
if isinstance(current, bool)... | def readoption(self, args):
arg = args[0][2:]
del args[0]
if ('=' in arg):
key = self.readequalskey(arg, args)
else:
key = arg.replace('-', )
if (not hasattr(self.options, key)):
return (None, key)
current = getattr(self.options, key)
if isinstance(current, bool)... |
0611334680e2831ca78bac6cf5ecede2ed60718411e5faf01ebdb08e208237f9 | def readquoted(self, args, initial):
'Read a value between quotes'
Trace.error('Oops')
value = initial[1:]
while ((len(args) > 0) and (not args[0].endswith('"')) and (not args[0].startswith('--'))):
Trace.error(('Appending ' + args[0]))
value += (' ' + args[0])
del args[0]
if... | Read a value between quotes | Lib/site-packages/docutils/utils/math/math2html.py | readquoted | edupyter/EDUPYTER | 2 | python | def readquoted(self, args, initial):
Trace.error('Oops')
value = initial[1:]
while ((len(args) > 0) and (not args[0].endswith('"')) and (not args[0].startswith('--'))):
Trace.error(('Appending ' + args[0]))
value += (' ' + args[0])
del args[0]
if ((len(args) == 0) or args[0]... | def readquoted(self, args, initial):
Trace.error('Oops')
value = initial[1:]
while ((len(args) > 0) and (not args[0].endswith('"')) and (not args[0].startswith('--'))):
Trace.error(('Appending ' + args[0]))
value += (' ' + args[0])
del args[0]
if ((len(args) == 0) or args[0]... |
704dc2e0b83ad9676bee39717bce95598aa6e4febfac007fedbca710633d9213 | def readequalskey(self, arg, args):
'Read a key using equals'
split = arg.split('=', 1)
key = split[0]
value = split[1]
args.insert(0, value)
return key | Read a key using equals | Lib/site-packages/docutils/utils/math/math2html.py | readequalskey | edupyter/EDUPYTER | 2 | python | def readequalskey(self, arg, args):
split = arg.split('=', 1)
key = split[0]
value = split[1]
args.insert(0, value)
return key | def readequalskey(self, arg, args):
split = arg.split('=', 1)
key = split[0]
value = split[1]
args.insert(0, value)
return key<|docstring|>Read a key using equals<|endoftext|> |
555dd0f334ffa8dfa424532c308beb63f5de450331120db7e869872ec41c3ceb | def parseoptions(self, args):
'Parse command line options'
Options.location = args[0]
del args[0]
parser = CommandLineParser(Options)
result = parser.parseoptions(args)
if result:
Trace.error(result)
self.usage()
self.processoptions() | Parse command line options | Lib/site-packages/docutils/utils/math/math2html.py | parseoptions | edupyter/EDUPYTER | 2 | python | def parseoptions(self, args):
Options.location = args[0]
del args[0]
parser = CommandLineParser(Options)
result = parser.parseoptions(args)
if result:
Trace.error(result)
self.usage()
self.processoptions() | def parseoptions(self, args):
Options.location = args[0]
del args[0]
parser = CommandLineParser(Options)
result = parser.parseoptions(args)
if result:
Trace.error(result)
self.usage()
self.processoptions()<|docstring|>Parse command line options<|endoftext|> |
8dbf1e5fd2b592ff7f8c3007c226577afadc42856ce7e08c13ee402e7152b0a1 | def processoptions(self):
'Process all options parsed.'
if Options.help:
self.usage()
if Options.version:
self.showversion()
for param in dir(Trace):
if param.endswith('mode'):
setattr(Trace, param, getattr(self, param[:(- 4)])) | Process all options parsed. | Lib/site-packages/docutils/utils/math/math2html.py | processoptions | edupyter/EDUPYTER | 2 | python | def processoptions(self):
if Options.help:
self.usage()
if Options.version:
self.showversion()
for param in dir(Trace):
if param.endswith('mode'):
setattr(Trace, param, getattr(self, param[:(- 4)])) | def processoptions(self):
if Options.help:
self.usage()
if Options.version:
self.showversion()
for param in dir(Trace):
if param.endswith('mode'):
setattr(Trace, param, getattr(self, param[:(- 4)]))<|docstring|>Process all options parsed.<|endoftext|> |
05cd9ed5aa02f2aaad953f2f642b2dd43995bca3450f9459d24b3df0f384474f | def usage(self):
'Show correct usage'
Trace.error((('Usage: ' + os.path.basename(Options.location)) + ' [options] "input string"'))
Trace.error('Convert input string with LaTeX math to MathML')
self.showoptions() | Show correct usage | Lib/site-packages/docutils/utils/math/math2html.py | usage | edupyter/EDUPYTER | 2 | python | def usage(self):
Trace.error((('Usage: ' + os.path.basename(Options.location)) + ' [options] "input string"'))
Trace.error('Convert input string with LaTeX math to MathML')
self.showoptions() | def usage(self):
Trace.error((('Usage: ' + os.path.basename(Options.location)) + ' [options] "input string"'))
Trace.error('Convert input string with LaTeX math to MathML')
self.showoptions()<|docstring|>Show correct usage<|endoftext|> |
634f867c80fdbdd3a242bbc5a23e3700f19ef06866f0a7f260ba14e6096055c2 | def showoptions(self):
'Show all possible options'
Trace.error(' --help: show this online help')
Trace.error(' --quiet: disables all runtime messages')
Trace.error(' --debug: enable debugging messages (for developers)')
Trace.error(' --versio... | Show all possible options | Lib/site-packages/docutils/utils/math/math2html.py | showoptions | edupyter/EDUPYTER | 2 | python | def showoptions(self):
Trace.error(' --help: show this online help')
Trace.error(' --quiet: disables all runtime messages')
Trace.error(' --debug: enable debugging messages (for developers)')
Trace.error(' --version: show versio... | def showoptions(self):
Trace.error(' --help: show this online help')
Trace.error(' --quiet: disables all runtime messages')
Trace.error(' --debug: enable debugging messages (for developers)')
Trace.error(' --version: show versio... |
534b16bddca9d5a4370725e1df28baaf36a3e4a69fd8a6403a914eb26ced9b08 | def showversion(self):
'Return the current eLyXer version string'
Trace.error(('math2html ' + __version__))
sys.exit() | Return the current eLyXer version string | Lib/site-packages/docutils/utils/math/math2html.py | showversion | edupyter/EDUPYTER | 2 | python | def showversion(self):
Trace.error(('math2html ' + __version__))
sys.exit() | def showversion(self):
Trace.error(('math2html ' + __version__))
sys.exit()<|docstring|>Return the current eLyXer version string<|endoftext|> |
b8961ad1e8d09d389289fbadebff6279b43fe90e621097a8107e241aaa64ce7d | def clone(cls, original):
'Return an exact copy of an object.'
'The original object must have an empty constructor.'
return cls.create(original.__class__) | Return an exact copy of an object. | Lib/site-packages/docutils/utils/math/math2html.py | clone | edupyter/EDUPYTER | 2 | python | def clone(cls, original):
'The original object must have an empty constructor.'
return cls.create(original.__class__) | def clone(cls, original):
'The original object must have an empty constructor.'
return cls.create(original.__class__)<|docstring|>Return an exact copy of an object.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.