repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
lorien/grab | grab/document.py | Document.text_assert_any | def text_assert_any(self, anchors, byte=False):
"""
If no `anchors` were found then raise `DataNotFound` exception.
"""
found = False
for anchor in anchors:
if self.text_search(anchor, byte=byte):
found = True
break
if not foun... | python | def text_assert_any(self, anchors, byte=False):
"""
If no `anchors` were found then raise `DataNotFound` exception.
"""
found = False
for anchor in anchors:
if self.text_search(anchor, byte=byte):
found = True
break
if not foun... | [
"def",
"text_assert_any",
"(",
"self",
",",
"anchors",
",",
"byte",
"=",
"False",
")",
":",
"found",
"=",
"False",
"for",
"anchor",
"in",
"anchors",
":",
"if",
"self",
".",
"text_search",
"(",
"anchor",
",",
"byte",
"=",
"byte",
")",
":",
"found",
"=... | If no `anchors` were found then raise `DataNotFound` exception. | [
"If",
"no",
"anchors",
"were",
"found",
"then",
"raise",
"DataNotFound",
"exception",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L440-L452 | train |
lorien/grab | grab/document.py | Document.rex_text | def rex_text(self, regexp, flags=0, byte=False, default=NULL):
"""
Search regular expression in response body and return content of first
matching group.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`.
... | python | def rex_text(self, regexp, flags=0, byte=False, default=NULL):
"""
Search regular expression in response body and return content of first
matching group.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`.
... | [
"def",
"rex_text",
"(",
"self",
",",
"regexp",
",",
"flags",
"=",
"0",
",",
"byte",
"=",
"False",
",",
"default",
"=",
"NULL",
")",
":",
"# pylint: disable=no-member",
"try",
":",
"match",
"=",
"self",
".",
"rex_search",
"(",
"regexp",
",",
"flags",
"=... | Search regular expression in response body and return content of first
matching group.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`. | [
"Search",
"regular",
"expression",
"in",
"response",
"body",
"and",
"return",
"content",
"of",
"first",
"matching",
"group",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L456-L474 | train |
lorien/grab | grab/document.py | Document.rex_search | def rex_search(self, regexp, flags=0, byte=False, default=NULL):
"""
Search the regular expression in response body.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`.
Note: if you use default non-byte mode t... | python | def rex_search(self, regexp, flags=0, byte=False, default=NULL):
"""
Search the regular expression in response body.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`.
Note: if you use default non-byte mode t... | [
"def",
"rex_search",
"(",
"self",
",",
"regexp",
",",
"flags",
"=",
"0",
",",
"byte",
"=",
"False",
",",
"default",
"=",
"NULL",
")",
":",
"regexp",
"=",
"normalize_regexp",
"(",
"regexp",
",",
"flags",
")",
"match",
"=",
"None",
"if",
"byte",
":",
... | Search the regular expression in response body.
:param byte: if False then search is performed in
`response.unicode_body()` else the rex is searched in `response.body`.
Note: if you use default non-byte mode than do not forget to build your
regular expression with re.U flag.
R... | [
"Search",
"the",
"regular",
"expression",
"in",
"response",
"body",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L476-L509 | train |
lorien/grab | grab/document.py | Document.rex_assert | def rex_assert(self, rex, byte=False):
"""
If `rex` expression is not found then raise `DataNotFound` exception.
"""
self.rex_search(rex, byte=byte) | python | def rex_assert(self, rex, byte=False):
"""
If `rex` expression is not found then raise `DataNotFound` exception.
"""
self.rex_search(rex, byte=byte) | [
"def",
"rex_assert",
"(",
"self",
",",
"rex",
",",
"byte",
"=",
"False",
")",
":",
"self",
".",
"rex_search",
"(",
"rex",
",",
"byte",
"=",
"byte",
")"
] | If `rex` expression is not found then raise `DataNotFound` exception. | [
"If",
"rex",
"expression",
"is",
"not",
"found",
"then",
"raise",
"DataNotFound",
"exception",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L511-L516 | train |
lorien/grab | grab/document.py | Document.pyquery | def pyquery(self):
"""
Returns pyquery handler.
"""
if not self._pyquery:
from pyquery import PyQuery
self._pyquery = PyQuery(self.tree)
return self._pyquery | python | def pyquery(self):
"""
Returns pyquery handler.
"""
if not self._pyquery:
from pyquery import PyQuery
self._pyquery = PyQuery(self.tree)
return self._pyquery | [
"def",
"pyquery",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pyquery",
":",
"from",
"pyquery",
"import",
"PyQuery",
"self",
".",
"_pyquery",
"=",
"PyQuery",
"(",
"self",
".",
"tree",
")",
"return",
"self",
".",
"_pyquery"
] | Returns pyquery handler. | [
"Returns",
"pyquery",
"handler",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L521-L530 | train |
lorien/grab | grab/document.py | Document.unicode_body | def unicode_body(self, ignore_errors=True, fix_special_entities=True):
"""
Return response body as unicode string.
"""
if not self._unicode_body:
self._unicode_body = self.convert_body_to_unicode(
body=self.body,
bom=self.bom,
... | python | def unicode_body(self, ignore_errors=True, fix_special_entities=True):
"""
Return response body as unicode string.
"""
if not self._unicode_body:
self._unicode_body = self.convert_body_to_unicode(
body=self.body,
bom=self.bom,
... | [
"def",
"unicode_body",
"(",
"self",
",",
"ignore_errors",
"=",
"True",
",",
"fix_special_entities",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_unicode_body",
":",
"self",
".",
"_unicode_body",
"=",
"self",
".",
"convert_body_to_unicode",
"(",
"body",
... | Return response body as unicode string. | [
"Return",
"response",
"body",
"as",
"unicode",
"string",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L562-L575 | train |
lorien/grab | grab/document.py | Document.choose_form | def choose_form(self, number=None, xpath=None, name=None, **kwargs):
"""
Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`... | python | def choose_form(self, number=None, xpath=None, name=None, **kwargs):
"""
Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`... | [
"def",
"choose_form",
"(",
"self",
",",
"number",
"=",
"None",
",",
"xpath",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"id_",
"=",
"kwargs",
".",
"pop",
"(",
"'id'",
",",
"None",
")",
"if",
"id_",
"is",
"not",
"N... | Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`DataNotFound` if form not found
:raises: :class:`GrabMisuseError`
if ... | [
"Set",
"the",
"default",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L688-L743 | train |
lorien/grab | grab/document.py | Document.form | def form(self):
"""
This attribute points to default form.
If form was not selected manually then select the form
which has the biggest number of input elements.
The form value is just an `lxml.html` form element.
Example::
g.go('some URL')
# C... | python | def form(self):
"""
This attribute points to default form.
If form was not selected manually then select the form
which has the biggest number of input elements.
The form value is just an `lxml.html` form element.
Example::
g.go('some URL')
# C... | [
"def",
"form",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"forms",
"=",
"[",
"(",
"idx",
",",
"len",
"(",
"list",
"(",
"x",
".",
"fields",
")",
")",
")",
"for",
"idx",
",",
"x",
"in",
"enumerate",
"(",
"self",
... | This attribute points to default form.
If form was not selected manually then select the form
which has the biggest number of input elements.
The form value is just an `lxml.html` form element.
Example::
g.go('some URL')
# Choose form automatically
... | [
"This",
"attribute",
"points",
"to",
"default",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L746-L774 | train |
lorien/grab | grab/document.py | Document.set_input | def set_input(self, name, value):
"""
Set the value of form element by its `name` attribute.
:param name: name of element
:param value: value which should be set to element
To check/uncheck the checkbox pass boolean value.
Example::
g.set_input('sex', 'mal... | python | def set_input(self, name, value):
"""
Set the value of form element by its `name` attribute.
:param name: name of element
:param value: value which should be set to element
To check/uncheck the checkbox pass boolean value.
Example::
g.set_input('sex', 'mal... | [
"def",
"set_input",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"self",
".",
"choose_form_by_element",
"(",
"'.//*[@name=\"%s\"]'",
"%",
"name",
")",
"elem",
"=",
"self",
".",
"form",
".",
"inputs... | Set the value of form element by its `name` attribute.
:param name: name of element
:param value: value which should be set to element
To check/uncheck the checkbox pass boolean value.
Example::
g.set_input('sex', 'male')
# Check the checkbox
g.se... | [
"Set",
"the",
"value",
"of",
"form",
"element",
"by",
"its",
"name",
"attribute",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L776-L811 | train |
lorien/grab | grab/document.py | Document.set_input_by_id | def set_input_by_id(self, _id, value):
"""
Set the value of form element by its `id` attribute.
:param _id: id of element
:param value: value which should be set to element
"""
xpath = './/*[@id="%s"]' % _id
if self._lxml_form is None:
self.choose_fo... | python | def set_input_by_id(self, _id, value):
"""
Set the value of form element by its `id` attribute.
:param _id: id of element
:param value: value which should be set to element
"""
xpath = './/*[@id="%s"]' % _id
if self._lxml_form is None:
self.choose_fo... | [
"def",
"set_input_by_id",
"(",
"self",
",",
"_id",
",",
"value",
")",
":",
"xpath",
"=",
"'.//*[@id=\"%s\"]'",
"%",
"_id",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"self",
".",
"choose_form_by_element",
"(",
"xpath",
")",
"sel",
"=",
"XpathSelec... | Set the value of form element by its `id` attribute.
:param _id: id of element
:param value: value which should be set to element | [
"Set",
"the",
"value",
"of",
"form",
"element",
"by",
"its",
"id",
"attribute",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L813-L827 | train |
lorien/grab | grab/document.py | Document.set_input_by_number | def set_input_by_number(self, number, value):
"""
Set the value of form element by its number in the form
:param number: number of element
:param value: value which should be set to element
"""
sel = XpathSelector(self.form)
elem = sel.select('.//input[@type="te... | python | def set_input_by_number(self, number, value):
"""
Set the value of form element by its number in the form
:param number: number of element
:param value: value which should be set to element
"""
sel = XpathSelector(self.form)
elem = sel.select('.//input[@type="te... | [
"def",
"set_input_by_number",
"(",
"self",
",",
"number",
",",
"value",
")",
":",
"sel",
"=",
"XpathSelector",
"(",
"self",
".",
"form",
")",
"elem",
"=",
"sel",
".",
"select",
"(",
"'.//input[@type=\"text\"]'",
")",
"[",
"number",
"]",
".",
"node",
"(",... | Set the value of form element by its number in the form
:param number: number of element
:param value: value which should be set to element | [
"Set",
"the",
"value",
"of",
"form",
"element",
"by",
"its",
"number",
"in",
"the",
"form"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L829-L839 | train |
lorien/grab | grab/document.py | Document.set_input_by_xpath | def set_input_by_xpath(self, xpath, value):
"""
Set the value of form element by xpath
:param xpath: xpath path
:param value: value which should be set to element
"""
elem = self.select(xpath).node()
if self._lxml_form is None:
# Explicitly set the ... | python | def set_input_by_xpath(self, xpath, value):
"""
Set the value of form element by xpath
:param xpath: xpath path
:param value: value which should be set to element
"""
elem = self.select(xpath).node()
if self._lxml_form is None:
# Explicitly set the ... | [
"def",
"set_input_by_xpath",
"(",
"self",
",",
"xpath",
",",
"value",
")",
":",
"elem",
"=",
"self",
".",
"select",
"(",
"xpath",
")",
".",
"node",
"(",
")",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"# Explicitly set the default form",
"# which ... | Set the value of form element by xpath
:param xpath: xpath path
:param value: value which should be set to element | [
"Set",
"the",
"value",
"of",
"form",
"element",
"by",
"xpath"
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L841-L862 | train |
lorien/grab | grab/document.py | Document.get_form_request | def get_form_request(
self, submit_name=None,
url=None, extra_post=None, remove_from_post=None):
"""
Submit default form.
:param submit_name: name of button which should be "clicked" to
submit form
:param url: explicitly specify form action url
... | python | def get_form_request(
self, submit_name=None,
url=None, extra_post=None, remove_from_post=None):
"""
Submit default form.
:param submit_name: name of button which should be "clicked" to
submit form
:param url: explicitly specify form action url
... | [
"def",
"get_form_request",
"(",
"self",
",",
"submit_name",
"=",
"None",
",",
"url",
"=",
"None",
",",
"extra_post",
"=",
"None",
",",
"remove_from_post",
"=",
"None",
")",
":",
"# pylint: disable=no-member",
"post",
"=",
"self",
".",
"form_fields",
"(",
")"... | Submit default form.
:param submit_name: name of button which should be "clicked" to
submit form
:param url: explicitly specify form action url
:param extra_post: (dict or list of pairs) additional form data which
will override data automatically extracted from the form.... | [
"Submit",
"default",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L869-L978 | train |
lorien/grab | grab/document.py | Document.form_fields | def form_fields(self):
"""
Return fields of default form.
Fill some fields with reasonable values.
"""
fields = dict(self.form.fields) # pylint: disable=no-member
fields_to_remove = set()
for key, val in list(fields.items()):
if isinstance(val, Che... | python | def form_fields(self):
"""
Return fields of default form.
Fill some fields with reasonable values.
"""
fields = dict(self.form.fields) # pylint: disable=no-member
fields_to_remove = set()
for key, val in list(fields.items()):
if isinstance(val, Che... | [
"def",
"form_fields",
"(",
"self",
")",
":",
"fields",
"=",
"dict",
"(",
"self",
".",
"form",
".",
"fields",
")",
"# pylint: disable=no-member",
"fields_to_remove",
"=",
"set",
"(",
")",
"for",
"key",
",",
"val",
"in",
"list",
"(",
"fields",
".",
"items"... | Return fields of default form.
Fill some fields with reasonable values. | [
"Return",
"fields",
"of",
"default",
"form",
"."
] | 8b301db2a08c830245b61c589e58af6234f4db79 | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L993-L1048 | train |
maxpumperla/elephas | elephas/utils/functional_utils.py | add_params | def add_params(param_list_left, param_list_right):
"""Add two lists of parameters one by one
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
res = []
for x, y in zip(param_list_left, param_list_right):
res.... | python | def add_params(param_list_left, param_list_right):
"""Add two lists of parameters one by one
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
res = []
for x, y in zip(param_list_left, param_list_right):
res.... | [
"def",
"add_params",
"(",
"param_list_left",
",",
"param_list_right",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"param_list_left",
",",
"param_list_right",
")",
":",
"res",
".",
"append",
"(",
"x",
"+",
"y",
")",
"return",... | Add two lists of parameters one by one
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays | [
"Add",
"two",
"lists",
"of",
"parameters",
"one",
"by",
"one"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L7-L17 | train |
maxpumperla/elephas | elephas/utils/functional_utils.py | subtract_params | def subtract_params(param_list_left, param_list_right):
"""Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
res = []
for x, y in zip(param_list_left, param_list_right):
res.a... | python | def subtract_params(param_list_left, param_list_right):
"""Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
res = []
for x, y in zip(param_list_left, param_list_right):
res.a... | [
"def",
"subtract_params",
"(",
"param_list_left",
",",
"param_list_right",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"param_list_left",
",",
"param_list_right",
")",
":",
"res",
".",
"append",
"(",
"x",
"-",
"y",
")",
"ret... | Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays | [
"Subtract",
"two",
"lists",
"of",
"parameters"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L20-L30 | train |
maxpumperla/elephas | elephas/utils/functional_utils.py | get_neutral | def get_neutral(array_list):
"""Get list of zero-valued numpy arrays for
specified list of numpy arrays
:param array_list: list of numpy arrays
:return: list of zeros of same shape as input
"""
res = []
for x in array_list:
res.append(np.zeros_like(x))
return res | python | def get_neutral(array_list):
"""Get list of zero-valued numpy arrays for
specified list of numpy arrays
:param array_list: list of numpy arrays
:return: list of zeros of same shape as input
"""
res = []
for x in array_list:
res.append(np.zeros_like(x))
return res | [
"def",
"get_neutral",
"(",
"array_list",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"array_list",
":",
"res",
".",
"append",
"(",
"np",
".",
"zeros_like",
"(",
"x",
")",
")",
"return",
"res"
] | Get list of zero-valued numpy arrays for
specified list of numpy arrays
:param array_list: list of numpy arrays
:return: list of zeros of same shape as input | [
"Get",
"list",
"of",
"zero",
"-",
"valued",
"numpy",
"arrays",
"for",
"specified",
"list",
"of",
"numpy",
"arrays"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L33-L43 | train |
maxpumperla/elephas | elephas/utils/functional_utils.py | divide_by | def divide_by(array_list, num_workers):
"""Divide a list of parameters by an integer num_workers.
:param array_list:
:param num_workers:
:return:
"""
for i, x in enumerate(array_list):
array_list[i] /= num_workers
return array_list | python | def divide_by(array_list, num_workers):
"""Divide a list of parameters by an integer num_workers.
:param array_list:
:param num_workers:
:return:
"""
for i, x in enumerate(array_list):
array_list[i] /= num_workers
return array_list | [
"def",
"divide_by",
"(",
"array_list",
",",
"num_workers",
")",
":",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"array_list",
")",
":",
"array_list",
"[",
"i",
"]",
"/=",
"num_workers",
"return",
"array_list"
] | Divide a list of parameters by an integer num_workers.
:param array_list:
:param num_workers:
:return: | [
"Divide",
"a",
"list",
"of",
"parameters",
"by",
"an",
"integer",
"num_workers",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L46-L55 | train |
maxpumperla/elephas | elephas/parameter/server.py | HttpServer.start_flask_service | def start_flask_service(self):
"""Define Flask parameter server service.
This HTTP server can do two things: get the current model
parameters and update model parameters. After registering
the `parameters` and `update` routes, the service will
get started.
"""
a... | python | def start_flask_service(self):
"""Define Flask parameter server service.
This HTTP server can do two things: get the current model
parameters and update model parameters. After registering
the `parameters` and `update` routes, the service will
get started.
"""
a... | [
"def",
"start_flask_service",
"(",
"self",
")",
":",
"app",
"=",
"Flask",
"(",
"__name__",
")",
"self",
".",
"app",
"=",
"app",
"@",
"app",
".",
"route",
"(",
"'/'",
")",
"def",
"home",
"(",
")",
":",
"return",
"'Elephas'",
"@",
"app",
".",
"route"... | Define Flask parameter server service.
This HTTP server can do two things: get the current model
parameters and update model parameters. After registering
the `parameters` and `update` routes, the service will
get started. | [
"Define",
"Flask",
"parameter",
"server",
"service",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/parameter/server.py#L92-L138 | train |
maxpumperla/elephas | elephas/mllib/adapter.py | to_matrix | def to_matrix(np_array):
"""Convert numpy array to MLlib Matrix
"""
if len(np_array.shape) == 2:
return Matrices.dense(np_array.shape[0],
np_array.shape[1],
np_array.ravel())
else:
raise Exception("An MLLib Matrix can only be cr... | python | def to_matrix(np_array):
"""Convert numpy array to MLlib Matrix
"""
if len(np_array.shape) == 2:
return Matrices.dense(np_array.shape[0],
np_array.shape[1],
np_array.ravel())
else:
raise Exception("An MLLib Matrix can only be cr... | [
"def",
"to_matrix",
"(",
"np_array",
")",
":",
"if",
"len",
"(",
"np_array",
".",
"shape",
")",
"==",
"2",
":",
"return",
"Matrices",
".",
"dense",
"(",
"np_array",
".",
"shape",
"[",
"0",
"]",
",",
"np_array",
".",
"shape",
"[",
"1",
"]",
",",
"... | Convert numpy array to MLlib Matrix | [
"Convert",
"numpy",
"array",
"to",
"MLlib",
"Matrix"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/mllib/adapter.py#L11-L20 | train |
maxpumperla/elephas | elephas/mllib/adapter.py | to_vector | def to_vector(np_array):
"""Convert numpy array to MLlib Vector
"""
if len(np_array.shape) == 1:
return Vectors.dense(np_array)
else:
raise Exception("An MLLib Vector can only be created from a one-dimensional " +
"numpy array, got {}".format(len(np_array.shape))) | python | def to_vector(np_array):
"""Convert numpy array to MLlib Vector
"""
if len(np_array.shape) == 1:
return Vectors.dense(np_array)
else:
raise Exception("An MLLib Vector can only be created from a one-dimensional " +
"numpy array, got {}".format(len(np_array.shape))) | [
"def",
"to_vector",
"(",
"np_array",
")",
":",
"if",
"len",
"(",
"np_array",
".",
"shape",
")",
"==",
"1",
":",
"return",
"Vectors",
".",
"dense",
"(",
"np_array",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"An MLLib Vector can only be created from a one-d... | Convert numpy array to MLlib Vector | [
"Convert",
"numpy",
"array",
"to",
"MLlib",
"Vector"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/mllib/adapter.py#L29-L36 | train |
maxpumperla/elephas | elephas/java/adapter.py | retrieve_keras_weights | def retrieve_keras_weights(java_model):
"""For a previously imported Keras model, after training it with DL4J Spark,
we want to set the resulting weights back to the original Keras model.
:param java_model: DL4J model (MultiLayerNetwork or ComputationGraph
:return: list of numpy arrays in correct order... | python | def retrieve_keras_weights(java_model):
"""For a previously imported Keras model, after training it with DL4J Spark,
we want to set the resulting weights back to the original Keras model.
:param java_model: DL4J model (MultiLayerNetwork or ComputationGraph
:return: list of numpy arrays in correct order... | [
"def",
"retrieve_keras_weights",
"(",
"java_model",
")",
":",
"weights",
"=",
"[",
"]",
"layers",
"=",
"java_model",
".",
"getLayers",
"(",
")",
"for",
"layer",
"in",
"layers",
":",
"params",
"=",
"layer",
".",
"paramTable",
"(",
")",
"keys",
"=",
"param... | For a previously imported Keras model, after training it with DL4J Spark,
we want to set the resulting weights back to the original Keras model.
:param java_model: DL4J model (MultiLayerNetwork or ComputationGraph
:return: list of numpy arrays in correct order for model.set_weights(...) of a corresponding ... | [
"For",
"a",
"previously",
"imported",
"Keras",
"model",
"after",
"training",
"it",
"with",
"DL4J",
"Spark",
"we",
"want",
"to",
"set",
"the",
"resulting",
"weights",
"back",
"to",
"the",
"original",
"Keras",
"model",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/adapter.py#L35-L52 | train |
maxpumperla/elephas | elephas/ml_model.py | ElephasEstimator._fit | def _fit(self, df):
"""Private fit method of the Estimator, which trains the model.
"""
simple_rdd = df_to_simple_rdd(df, categorical=self.get_categorical_labels(), nb_classes=self.get_nb_classes(),
features_col=self.getFeaturesCol(), label_col=self.getLabel... | python | def _fit(self, df):
"""Private fit method of the Estimator, which trains the model.
"""
simple_rdd = df_to_simple_rdd(df, categorical=self.get_categorical_labels(), nb_classes=self.get_nb_classes(),
features_col=self.getFeaturesCol(), label_col=self.getLabel... | [
"def",
"_fit",
"(",
"self",
",",
"df",
")",
":",
"simple_rdd",
"=",
"df_to_simple_rdd",
"(",
"df",
",",
"categorical",
"=",
"self",
".",
"get_categorical_labels",
"(",
")",
",",
"nb_classes",
"=",
"self",
".",
"get_nb_classes",
"(",
")",
",",
"features_col... | Private fit method of the Estimator, which trains the model. | [
"Private",
"fit",
"method",
"of",
"the",
"Estimator",
"which",
"trains",
"the",
"model",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml_model.py#L72-L99 | train |
maxpumperla/elephas | elephas/ml_model.py | ElephasTransformer._transform | def _transform(self, df):
"""Private transform method of a Transformer. This serves as batch-prediction method for our purposes.
"""
output_col = self.getOutputCol()
label_col = self.getLabelCol()
new_schema = copy.deepcopy(df.schema)
new_schema.add(StructField(output_col... | python | def _transform(self, df):
"""Private transform method of a Transformer. This serves as batch-prediction method for our purposes.
"""
output_col = self.getOutputCol()
label_col = self.getLabelCol()
new_schema = copy.deepcopy(df.schema)
new_schema.add(StructField(output_col... | [
"def",
"_transform",
"(",
"self",
",",
"df",
")",
":",
"output_col",
"=",
"self",
".",
"getOutputCol",
"(",
")",
"label_col",
"=",
"self",
".",
"getLabelCol",
"(",
")",
"new_schema",
"=",
"copy",
".",
"deepcopy",
"(",
"df",
".",
"schema",
")",
"new_sch... | Private transform method of a Transformer. This serves as batch-prediction method for our purposes. | [
"Private",
"transform",
"method",
"of",
"a",
"Transformer",
".",
"This",
"serves",
"as",
"batch",
"-",
"prediction",
"method",
"for",
"our",
"purposes",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml_model.py#L146-L171 | train |
maxpumperla/elephas | elephas/java/ndarray.py | _from_numpy | def _from_numpy(np_array):
"""
Convert numpy array to nd4j array
"""
# Convert the numpy array to nd4j context dtype
required_dtype = get_np_dtype(get_context_dtype())
if np_array.dtype != required_dtype:
raise Exception("{} is required, got {}".format(
repr(required_dtype),... | python | def _from_numpy(np_array):
"""
Convert numpy array to nd4j array
"""
# Convert the numpy array to nd4j context dtype
required_dtype = get_np_dtype(get_context_dtype())
if np_array.dtype != required_dtype:
raise Exception("{} is required, got {}".format(
repr(required_dtype),... | [
"def",
"_from_numpy",
"(",
"np_array",
")",
":",
"# Convert the numpy array to nd4j context dtype",
"required_dtype",
"=",
"get_np_dtype",
"(",
"get_context_dtype",
"(",
")",
")",
"if",
"np_array",
".",
"dtype",
"!=",
"required_dtype",
":",
"raise",
"Exception",
"(",
... | Convert numpy array to nd4j array | [
"Convert",
"numpy",
"array",
"to",
"nd4j",
"array"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/ndarray.py#L78-L133 | train |
maxpumperla/elephas | elephas/java/ndarray.py | _to_numpy | def _to_numpy(nd4j_array):
"""
Convert nd4j array to numpy array
"""
buff = nd4j_array.data()
address = buff.pointer().address()
dtype = get_context_dtype()
mapping = {
'double': ctypes.c_double,
'float': ctypes.c_float
}
Pointer = ctypes.POINTER(mapping[dtype])
p... | python | def _to_numpy(nd4j_array):
"""
Convert nd4j array to numpy array
"""
buff = nd4j_array.data()
address = buff.pointer().address()
dtype = get_context_dtype()
mapping = {
'double': ctypes.c_double,
'float': ctypes.c_float
}
Pointer = ctypes.POINTER(mapping[dtype])
p... | [
"def",
"_to_numpy",
"(",
"nd4j_array",
")",
":",
"buff",
"=",
"nd4j_array",
".",
"data",
"(",
")",
"address",
"=",
"buff",
".",
"pointer",
"(",
")",
".",
"address",
"(",
")",
"dtype",
"=",
"get_context_dtype",
"(",
")",
"mapping",
"=",
"{",
"'double'",... | Convert nd4j array to numpy array | [
"Convert",
"nd4j",
"array",
"to",
"numpy",
"array"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/ndarray.py#L136-L150 | train |
maxpumperla/elephas | elephas/utils/rwlock.py | RWLock.acquire_read | def acquire_read(self):
"""
Acquire a read lock. Several threads can hold this typeof lock.
It is exclusive with write locks.
"""
self.monitor.acquire()
while self.rwlock < 0 or self.writers_waiting:
self.readers_ok.wait()
self.rwlock += 1
self... | python | def acquire_read(self):
"""
Acquire a read lock. Several threads can hold this typeof lock.
It is exclusive with write locks.
"""
self.monitor.acquire()
while self.rwlock < 0 or self.writers_waiting:
self.readers_ok.wait()
self.rwlock += 1
self... | [
"def",
"acquire_read",
"(",
"self",
")",
":",
"self",
".",
"monitor",
".",
"acquire",
"(",
")",
"while",
"self",
".",
"rwlock",
"<",
"0",
"or",
"self",
".",
"writers_waiting",
":",
"self",
".",
"readers_ok",
".",
"wait",
"(",
")",
"self",
".",
"rwloc... | Acquire a read lock. Several threads can hold this typeof lock.
It is exclusive with write locks. | [
"Acquire",
"a",
"read",
"lock",
".",
"Several",
"threads",
"can",
"hold",
"this",
"typeof",
"lock",
".",
"It",
"is",
"exclusive",
"with",
"write",
"locks",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L25-L34 | train |
maxpumperla/elephas | elephas/utils/rwlock.py | RWLock.acquire_write | def acquire_write(self):
"""
Acquire a write lock. Only one thread can hold this lock, and
only when no read locks are also held.
"""
self.monitor.acquire()
while self.rwlock != 0:
self.writers_waiting += 1
self.writers_ok.wait()
self.w... | python | def acquire_write(self):
"""
Acquire a write lock. Only one thread can hold this lock, and
only when no read locks are also held.
"""
self.monitor.acquire()
while self.rwlock != 0:
self.writers_waiting += 1
self.writers_ok.wait()
self.w... | [
"def",
"acquire_write",
"(",
"self",
")",
":",
"self",
".",
"monitor",
".",
"acquire",
"(",
")",
"while",
"self",
".",
"rwlock",
"!=",
"0",
":",
"self",
".",
"writers_waiting",
"+=",
"1",
"self",
".",
"writers_ok",
".",
"wait",
"(",
")",
"self",
".",... | Acquire a write lock. Only one thread can hold this lock, and
only when no read locks are also held. | [
"Acquire",
"a",
"write",
"lock",
".",
"Only",
"one",
"thread",
"can",
"hold",
"this",
"lock",
"and",
"only",
"when",
"no",
"read",
"locks",
"are",
"also",
"held",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L36-L47 | train |
maxpumperla/elephas | elephas/utils/rwlock.py | RWLock.release | def release(self):
"""
Release a lock, whether read or write.
"""
self.monitor.acquire()
if self.rwlock < 0:
self.rwlock = 0
else:
self.rwlock -= 1
wake_writers = self.writers_waiting and self.rwlock == 0
wake_readers = self.writers... | python | def release(self):
"""
Release a lock, whether read or write.
"""
self.monitor.acquire()
if self.rwlock < 0:
self.rwlock = 0
else:
self.rwlock -= 1
wake_writers = self.writers_waiting and self.rwlock == 0
wake_readers = self.writers... | [
"def",
"release",
"(",
"self",
")",
":",
"self",
".",
"monitor",
".",
"acquire",
"(",
")",
"if",
"self",
".",
"rwlock",
"<",
"0",
":",
"self",
".",
"rwlock",
"=",
"0",
"else",
":",
"self",
".",
"rwlock",
"-=",
"1",
"wake_writers",
"=",
"self",
".... | Release a lock, whether read or write. | [
"Release",
"a",
"lock",
"whether",
"read",
"or",
"write",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L49-L68 | train |
maxpumperla/elephas | elephas/ml/adapter.py | to_data_frame | def to_data_frame(sc, features, labels, categorical=False):
"""Convert numpy arrays of features and labels into Spark DataFrame
"""
lp_rdd = to_labeled_point(sc, features, labels, categorical)
sql_context = SQLContext(sc)
df = sql_context.createDataFrame(lp_rdd)
return df | python | def to_data_frame(sc, features, labels, categorical=False):
"""Convert numpy arrays of features and labels into Spark DataFrame
"""
lp_rdd = to_labeled_point(sc, features, labels, categorical)
sql_context = SQLContext(sc)
df = sql_context.createDataFrame(lp_rdd)
return df | [
"def",
"to_data_frame",
"(",
"sc",
",",
"features",
",",
"labels",
",",
"categorical",
"=",
"False",
")",
":",
"lp_rdd",
"=",
"to_labeled_point",
"(",
"sc",
",",
"features",
",",
"labels",
",",
"categorical",
")",
"sql_context",
"=",
"SQLContext",
"(",
"sc... | Convert numpy arrays of features and labels into Spark DataFrame | [
"Convert",
"numpy",
"arrays",
"of",
"features",
"and",
"labels",
"into",
"Spark",
"DataFrame"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L9-L15 | train |
maxpumperla/elephas | elephas/ml/adapter.py | from_data_frame | def from_data_frame(df, categorical=False, nb_classes=None):
"""Convert DataFrame back to pair of numpy arrays
"""
lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features))
features, labels = from_labeled_point(lp_rdd, categorical, nb_classes)
return features, labels | python | def from_data_frame(df, categorical=False, nb_classes=None):
"""Convert DataFrame back to pair of numpy arrays
"""
lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features))
features, labels = from_labeled_point(lp_rdd, categorical, nb_classes)
return features, labels | [
"def",
"from_data_frame",
"(",
"df",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
")",
":",
"lp_rdd",
"=",
"df",
".",
"rdd",
".",
"map",
"(",
"lambda",
"row",
":",
"LabeledPoint",
"(",
"row",
".",
"label",
",",
"row",
".",
"featu... | Convert DataFrame back to pair of numpy arrays | [
"Convert",
"DataFrame",
"back",
"to",
"pair",
"of",
"numpy",
"arrays"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L18-L23 | train |
maxpumperla/elephas | elephas/ml/adapter.py | df_to_simple_rdd | def df_to_simple_rdd(df, categorical=False, nb_classes=None, features_col='features', label_col='label'):
"""Convert DataFrame into RDD of pairs
"""
sql_context = df.sql_ctx
sql_context.registerDataFrameAsTable(df, "temp_table")
selected_df = sql_context.sql(
"SELECT {0} AS features, {1} as ... | python | def df_to_simple_rdd(df, categorical=False, nb_classes=None, features_col='features', label_col='label'):
"""Convert DataFrame into RDD of pairs
"""
sql_context = df.sql_ctx
sql_context.registerDataFrameAsTable(df, "temp_table")
selected_df = sql_context.sql(
"SELECT {0} AS features, {1} as ... | [
"def",
"df_to_simple_rdd",
"(",
"df",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
",",
"features_col",
"=",
"'features'",
",",
"label_col",
"=",
"'label'",
")",
":",
"sql_context",
"=",
"df",
".",
"sql_ctx",
"sql_context",
".",
"registe... | Convert DataFrame into RDD of pairs | [
"Convert",
"DataFrame",
"into",
"RDD",
"of",
"pairs"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L26-L40 | train |
maxpumperla/elephas | elephas/spark_model.py | SparkModel.fit | def fit(self, rdd, epochs=10, batch_size=32,
verbose=0, validation_split=0.1):
"""
Train an elephas model on an RDD. The Keras model configuration as specified
in the elephas model is sent to Spark workers, abd each worker will be trained
on their data partition.
:pa... | python | def fit(self, rdd, epochs=10, batch_size=32,
verbose=0, validation_split=0.1):
"""
Train an elephas model on an RDD. The Keras model configuration as specified
in the elephas model is sent to Spark workers, abd each worker will be trained
on their data partition.
:pa... | [
"def",
"fit",
"(",
"self",
",",
"rdd",
",",
"epochs",
"=",
"10",
",",
"batch_size",
"=",
"32",
",",
"verbose",
"=",
"0",
",",
"validation_split",
"=",
"0.1",
")",
":",
"print",
"(",
"'>>> Fit model'",
")",
"if",
"self",
".",
"num_workers",
":",
"rdd"... | Train an elephas model on an RDD. The Keras model configuration as specified
in the elephas model is sent to Spark workers, abd each worker will be trained
on their data partition.
:param rdd: RDD with features and labels
:param epochs: number of epochs used for training
:param ... | [
"Train",
"an",
"elephas",
"model",
"on",
"an",
"RDD",
".",
"The",
"Keras",
"model",
"configuration",
"as",
"specified",
"in",
"the",
"elephas",
"model",
"is",
"sent",
"to",
"Spark",
"workers",
"abd",
"each",
"worker",
"will",
"be",
"trained",
"on",
"their"... | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L133-L154 | train |
maxpumperla/elephas | elephas/spark_model.py | SparkModel._fit | def _fit(self, rdd, epochs, batch_size, verbose, validation_split):
"""Protected train method to make wrapping of modes easier
"""
self._master_network.compile(optimizer=self.master_optimizer,
loss=self.master_loss,
metric... | python | def _fit(self, rdd, epochs, batch_size, verbose, validation_split):
"""Protected train method to make wrapping of modes easier
"""
self._master_network.compile(optimizer=self.master_optimizer,
loss=self.master_loss,
metric... | [
"def",
"_fit",
"(",
"self",
",",
"rdd",
",",
"epochs",
",",
"batch_size",
",",
"verbose",
",",
"validation_split",
")",
":",
"self",
".",
"_master_network",
".",
"compile",
"(",
"optimizer",
"=",
"self",
".",
"master_optimizer",
",",
"loss",
"=",
"self",
... | Protected train method to make wrapping of modes easier | [
"Protected",
"train",
"method",
"to",
"make",
"wrapping",
"of",
"modes",
"easier"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L156-L197 | train |
maxpumperla/elephas | elephas/spark_model.py | SparkMLlibModel.fit | def fit(self, labeled_points, epochs=10, batch_size=32, verbose=0, validation_split=0.1,
categorical=False, nb_classes=None):
"""Train an elephas model on an RDD of LabeledPoints
"""
rdd = lp_to_simple_rdd(labeled_points, categorical, nb_classes)
rdd = rdd.repartition(self.nu... | python | def fit(self, labeled_points, epochs=10, batch_size=32, verbose=0, validation_split=0.1,
categorical=False, nb_classes=None):
"""Train an elephas model on an RDD of LabeledPoints
"""
rdd = lp_to_simple_rdd(labeled_points, categorical, nb_classes)
rdd = rdd.repartition(self.nu... | [
"def",
"fit",
"(",
"self",
",",
"labeled_points",
",",
"epochs",
"=",
"10",
",",
"batch_size",
"=",
"32",
",",
"verbose",
"=",
"0",
",",
"validation_split",
"=",
"0.1",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
")",
":",
"rdd",
... | Train an elephas model on an RDD of LabeledPoints | [
"Train",
"an",
"elephas",
"model",
"on",
"an",
"RDD",
"of",
"LabeledPoints"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L235-L242 | train |
maxpumperla/elephas | elephas/spark_model.py | SparkMLlibModel.predict | def predict(self, mllib_data):
"""Predict probabilities for an RDD of features
"""
if isinstance(mllib_data, pyspark.mllib.linalg.Matrix):
return to_matrix(self._master_network.predict(from_matrix(mllib_data)))
elif isinstance(mllib_data, pyspark.mllib.linalg.Vector):
... | python | def predict(self, mllib_data):
"""Predict probabilities for an RDD of features
"""
if isinstance(mllib_data, pyspark.mllib.linalg.Matrix):
return to_matrix(self._master_network.predict(from_matrix(mllib_data)))
elif isinstance(mllib_data, pyspark.mllib.linalg.Vector):
... | [
"def",
"predict",
"(",
"self",
",",
"mllib_data",
")",
":",
"if",
"isinstance",
"(",
"mllib_data",
",",
"pyspark",
".",
"mllib",
".",
"linalg",
".",
"Matrix",
")",
":",
"return",
"to_matrix",
"(",
"self",
".",
"_master_network",
".",
"predict",
"(",
"fro... | Predict probabilities for an RDD of features | [
"Predict",
"probabilities",
"for",
"an",
"RDD",
"of",
"features"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L244-L253 | train |
maxpumperla/elephas | elephas/worker.py | SparkWorker.train | def train(self, data_iterator):
"""Train a keras model on a worker
"""
optimizer = get_optimizer(self.master_optimizer)
self.model = model_from_yaml(self.yaml, self.custom_objects)
self.model.compile(optimizer=optimizer,
loss=self.master_loss, metrics=s... | python | def train(self, data_iterator):
"""Train a keras model on a worker
"""
optimizer = get_optimizer(self.master_optimizer)
self.model = model_from_yaml(self.yaml, self.custom_objects)
self.model.compile(optimizer=optimizer,
loss=self.master_loss, metrics=s... | [
"def",
"train",
"(",
"self",
",",
"data_iterator",
")",
":",
"optimizer",
"=",
"get_optimizer",
"(",
"self",
".",
"master_optimizer",
")",
"self",
".",
"model",
"=",
"model_from_yaml",
"(",
"self",
".",
"yaml",
",",
"self",
".",
"custom_objects",
")",
"sel... | Train a keras model on a worker | [
"Train",
"a",
"keras",
"model",
"on",
"a",
"worker"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/worker.py#L26-L49 | train |
maxpumperla/elephas | elephas/worker.py | AsynchronousSparkWorker.train | def train(self, data_iterator):
"""Train a keras model on a worker and send asynchronous updates
to parameter server
"""
feature_iterator, label_iterator = tee(data_iterator, 2)
x_train = np.asarray([x for x, y in feature_iterator])
y_train = np.asarray([y for x, y in lab... | python | def train(self, data_iterator):
"""Train a keras model on a worker and send asynchronous updates
to parameter server
"""
feature_iterator, label_iterator = tee(data_iterator, 2)
x_train = np.asarray([x for x, y in feature_iterator])
y_train = np.asarray([y for x, y in lab... | [
"def",
"train",
"(",
"self",
",",
"data_iterator",
")",
":",
"feature_iterator",
",",
"label_iterator",
"=",
"tee",
"(",
"data_iterator",
",",
"2",
")",
"x_train",
"=",
"np",
".",
"asarray",
"(",
"[",
"x",
"for",
"x",
",",
"y",
"in",
"feature_iterator",
... | Train a keras model on a worker and send asynchronous updates
to parameter server | [
"Train",
"a",
"keras",
"model",
"on",
"a",
"worker",
"and",
"send",
"asynchronous",
"updates",
"to",
"parameter",
"server"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/worker.py#L77-L133 | train |
maxpumperla/elephas | elephas/utils/sockets.py | determine_master | def determine_master(port=4000):
"""Determine address of master so that workers
can connect to it. If the environment variable
SPARK_LOCAL_IP is set, that address will be used.
:param port: port on which the application runs
:return: Master address
Example usage:
SPARK_LOCAL_IP=127.0.0... | python | def determine_master(port=4000):
"""Determine address of master so that workers
can connect to it. If the environment variable
SPARK_LOCAL_IP is set, that address will be used.
:param port: port on which the application runs
:return: Master address
Example usage:
SPARK_LOCAL_IP=127.0.0... | [
"def",
"determine_master",
"(",
"port",
"=",
"4000",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'SPARK_LOCAL_IP'",
")",
":",
"return",
"os",
".",
"environ",
"[",
"'SPARK_LOCAL_IP'",
"]",
"+",
"\":\"",
"+",
"str",
"(",
"port",
")",
"else",
... | Determine address of master so that workers
can connect to it. If the environment variable
SPARK_LOCAL_IP is set, that address will be used.
:param port: port on which the application runs
:return: Master address
Example usage:
SPARK_LOCAL_IP=127.0.0.1 spark-submit --master \
l... | [
"Determine",
"address",
"of",
"master",
"so",
"that",
"workers",
"can",
"connect",
"to",
"it",
".",
"If",
"the",
"environment",
"variable",
"SPARK_LOCAL_IP",
"is",
"set",
"that",
"address",
"will",
"be",
"used",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L6-L21 | train |
maxpumperla/elephas | elephas/utils/sockets.py | _receive_all | def _receive_all(socket, num_bytes):
"""Reads `num_bytes` bytes from the specified socket.
:param socket: open socket instance
:param num_bytes: number of bytes to read
:return: received data
"""
buffer = ''
buffer_size = 0
bytes_left = num_bytes
while buffer_size < num_bytes:
... | python | def _receive_all(socket, num_bytes):
"""Reads `num_bytes` bytes from the specified socket.
:param socket: open socket instance
:param num_bytes: number of bytes to read
:return: received data
"""
buffer = ''
buffer_size = 0
bytes_left = num_bytes
while buffer_size < num_bytes:
... | [
"def",
"_receive_all",
"(",
"socket",
",",
"num_bytes",
")",
":",
"buffer",
"=",
"''",
"buffer_size",
"=",
"0",
"bytes_left",
"=",
"num_bytes",
"while",
"buffer_size",
"<",
"num_bytes",
":",
"data",
"=",
"socket",
".",
"recv",
"(",
"bytes_left",
")",
"delt... | Reads `num_bytes` bytes from the specified socket.
:param socket: open socket instance
:param num_bytes: number of bytes to read
:return: received data | [
"Reads",
"num_bytes",
"bytes",
"from",
"the",
"specified",
"socket",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L24-L42 | train |
maxpumperla/elephas | elephas/utils/sockets.py | receive | def receive(socket, num_bytes=20):
"""Receive data frame from open socket.
:param socket: open socket instance
:param num_bytes: number of bytes to read
:return: received data
"""
length = int(_receive_all(socket, num_bytes).decode())
serialized_data = _receive_all(socket, length)
retu... | python | def receive(socket, num_bytes=20):
"""Receive data frame from open socket.
:param socket: open socket instance
:param num_bytes: number of bytes to read
:return: received data
"""
length = int(_receive_all(socket, num_bytes).decode())
serialized_data = _receive_all(socket, length)
retu... | [
"def",
"receive",
"(",
"socket",
",",
"num_bytes",
"=",
"20",
")",
":",
"length",
"=",
"int",
"(",
"_receive_all",
"(",
"socket",
",",
"num_bytes",
")",
".",
"decode",
"(",
")",
")",
"serialized_data",
"=",
"_receive_all",
"(",
"socket",
",",
"length",
... | Receive data frame from open socket.
:param socket: open socket instance
:param num_bytes: number of bytes to read
:return: received data | [
"Receive",
"data",
"frame",
"from",
"open",
"socket",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L45-L55 | train |
maxpumperla/elephas | elephas/utils/sockets.py | send | def send(socket, data, num_bytes=20):
"""Send data to specified socket.
:param socket: open socket instance
:param data: data to send
:param num_bytes: number of bytes to read
:return: received data
"""
pickled_data = pickle.dumps(data, -1)
length = str(len(pickled_data)).zfill(num_by... | python | def send(socket, data, num_bytes=20):
"""Send data to specified socket.
:param socket: open socket instance
:param data: data to send
:param num_bytes: number of bytes to read
:return: received data
"""
pickled_data = pickle.dumps(data, -1)
length = str(len(pickled_data)).zfill(num_by... | [
"def",
"send",
"(",
"socket",
",",
"data",
",",
"num_bytes",
"=",
"20",
")",
":",
"pickled_data",
"=",
"pickle",
".",
"dumps",
"(",
"data",
",",
"-",
"1",
")",
"length",
"=",
"str",
"(",
"len",
"(",
"pickled_data",
")",
")",
".",
"zfill",
"(",
"n... | Send data to specified socket.
:param socket: open socket instance
:param data: data to send
:param num_bytes: number of bytes to read
:return: received data | [
"Send",
"data",
"to",
"specified",
"socket",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L58-L71 | train |
maxpumperla/elephas | elephas/utils/rdd_utils.py | to_java_rdd | def to_java_rdd(jsc, features, labels, batch_size):
"""Convert numpy features and labels into a JavaRDD of
DL4J DataSet type.
:param jsc: JavaSparkContext from pyjnius
:param features: numpy array with features
:param labels: numpy array with labels:
:return: JavaRDD<DataSet>
"""
data_s... | python | def to_java_rdd(jsc, features, labels, batch_size):
"""Convert numpy features and labels into a JavaRDD of
DL4J DataSet type.
:param jsc: JavaSparkContext from pyjnius
:param features: numpy array with features
:param labels: numpy array with labels:
:return: JavaRDD<DataSet>
"""
data_s... | [
"def",
"to_java_rdd",
"(",
"jsc",
",",
"features",
",",
"labels",
",",
"batch_size",
")",
":",
"data_sets",
"=",
"java_classes",
".",
"ArrayList",
"(",
")",
"num_batches",
"=",
"int",
"(",
"len",
"(",
"features",
")",
"/",
"batch_size",
")",
"for",
"i",
... | Convert numpy features and labels into a JavaRDD of
DL4J DataSet type.
:param jsc: JavaSparkContext from pyjnius
:param features: numpy array with features
:param labels: numpy array with labels:
:return: JavaRDD<DataSet> | [
"Convert",
"numpy",
"features",
"and",
"labels",
"into",
"a",
"JavaRDD",
"of",
"DL4J",
"DataSet",
"type",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L16-L35 | train |
maxpumperla/elephas | elephas/utils/rdd_utils.py | to_simple_rdd | def to_simple_rdd(sc, features, labels):
"""Convert numpy arrays of features and labels into
an RDD of pairs.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:return: Spark RDD with feature-label pairs
"""
pairs = [(x, y) for x,... | python | def to_simple_rdd(sc, features, labels):
"""Convert numpy arrays of features and labels into
an RDD of pairs.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:return: Spark RDD with feature-label pairs
"""
pairs = [(x, y) for x,... | [
"def",
"to_simple_rdd",
"(",
"sc",
",",
"features",
",",
"labels",
")",
":",
"pairs",
"=",
"[",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"features",
",",
"labels",
")",
"]",
"return",
"sc",
".",
"parallelize",
"(",
"pairs"... | Convert numpy arrays of features and labels into
an RDD of pairs.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:return: Spark RDD with feature-label pairs | [
"Convert",
"numpy",
"arrays",
"of",
"features",
"and",
"labels",
"into",
"an",
"RDD",
"of",
"pairs",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L38-L48 | train |
maxpumperla/elephas | elephas/utils/rdd_utils.py | to_labeled_point | def to_labeled_point(sc, features, labels, categorical=False):
"""Convert numpy arrays of features and labels into
a LabeledPoint RDD for MLlib and ML integration.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:param categorical: bool... | python | def to_labeled_point(sc, features, labels, categorical=False):
"""Convert numpy arrays of features and labels into
a LabeledPoint RDD for MLlib and ML integration.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:param categorical: bool... | [
"def",
"to_labeled_point",
"(",
"sc",
",",
"features",
",",
"labels",
",",
"categorical",
"=",
"False",
")",
":",
"labeled_points",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"features",
",",
"labels",
")",
":",
"if",
"categorical",
":",
... | Convert numpy arrays of features and labels into
a LabeledPoint RDD for MLlib and ML integration.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:param categorical: boolean, whether labels are already one-hot encoded or not
:return: La... | [
"Convert",
"numpy",
"arrays",
"of",
"features",
"and",
"labels",
"into",
"a",
"LabeledPoint",
"RDD",
"for",
"MLlib",
"and",
"ML",
"integration",
"."
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L51-L68 | train |
maxpumperla/elephas | elephas/utils/rdd_utils.py | from_labeled_point | def from_labeled_point(rdd, categorical=False, nb_classes=None):
"""Convert a LabeledPoint RDD back to a pair of numpy arrays
:param rdd: LabeledPoint RDD
:param categorical: boolean, if labels should be one-hot encode when returned
:param nb_classes: optional int, indicating the number of class labels... | python | def from_labeled_point(rdd, categorical=False, nb_classes=None):
"""Convert a LabeledPoint RDD back to a pair of numpy arrays
:param rdd: LabeledPoint RDD
:param categorical: boolean, if labels should be one-hot encode when returned
:param nb_classes: optional int, indicating the number of class labels... | [
"def",
"from_labeled_point",
"(",
"rdd",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
")",
":",
"features",
"=",
"np",
".",
"asarray",
"(",
"rdd",
".",
"map",
"(",
"lambda",
"lp",
":",
"from_vector",
"(",
"lp",
".",
"features",
")"... | Convert a LabeledPoint RDD back to a pair of numpy arrays
:param rdd: LabeledPoint RDD
:param categorical: boolean, if labels should be one-hot encode when returned
:param nb_classes: optional int, indicating the number of class labels
:return: pair of numpy arrays, features and labels | [
"Convert",
"a",
"LabeledPoint",
"RDD",
"back",
"to",
"a",
"pair",
"of",
"numpy",
"arrays"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L71-L89 | train |
maxpumperla/elephas | elephas/utils/rdd_utils.py | encode_label | def encode_label(label, nb_classes):
"""One-hot encoding of a single label
:param label: class label (int or double without floating point digits)
:param nb_classes: int, number of total classes
:return: one-hot encoded vector
"""
encoded = np.zeros(nb_classes)
encoded[int(label)] = 1.
... | python | def encode_label(label, nb_classes):
"""One-hot encoding of a single label
:param label: class label (int or double without floating point digits)
:param nb_classes: int, number of total classes
:return: one-hot encoded vector
"""
encoded = np.zeros(nb_classes)
encoded[int(label)] = 1.
... | [
"def",
"encode_label",
"(",
"label",
",",
"nb_classes",
")",
":",
"encoded",
"=",
"np",
".",
"zeros",
"(",
"nb_classes",
")",
"encoded",
"[",
"int",
"(",
"label",
")",
"]",
"=",
"1.",
"return",
"encoded"
] | One-hot encoding of a single label
:param label: class label (int or double without floating point digits)
:param nb_classes: int, number of total classes
:return: one-hot encoded vector | [
"One",
"-",
"hot",
"encoding",
"of",
"a",
"single",
"label"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L92-L101 | train |
maxpumperla/elephas | elephas/utils/rdd_utils.py | lp_to_simple_rdd | def lp_to_simple_rdd(lp_rdd, categorical=False, nb_classes=None):
"""Convert a LabeledPoint RDD into an RDD of feature-label pairs
:param lp_rdd: LabeledPoint RDD of features and labels
:param categorical: boolean, if labels should be one-hot encode when returned
:param nb_classes: int, number of total... | python | def lp_to_simple_rdd(lp_rdd, categorical=False, nb_classes=None):
"""Convert a LabeledPoint RDD into an RDD of feature-label pairs
:param lp_rdd: LabeledPoint RDD of features and labels
:param categorical: boolean, if labels should be one-hot encode when returned
:param nb_classes: int, number of total... | [
"def",
"lp_to_simple_rdd",
"(",
"lp_rdd",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
")",
":",
"if",
"categorical",
":",
"if",
"not",
"nb_classes",
":",
"labels",
"=",
"np",
".",
"asarray",
"(",
"lp_rdd",
".",
"map",
"(",
"lambda",... | Convert a LabeledPoint RDD into an RDD of feature-label pairs
:param lp_rdd: LabeledPoint RDD of features and labels
:param categorical: boolean, if labels should be one-hot encode when returned
:param nb_classes: int, number of total classes
:return: Spark RDD with feature-label pairs | [
"Convert",
"a",
"LabeledPoint",
"RDD",
"into",
"an",
"RDD",
"of",
"feature",
"-",
"label",
"pairs"
] | 84605acdc9564673c487637dcb27f5def128bcc7 | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L104-L121 | train |
lebinh/ngxtop | ngxtop/ngxtop.py | follow | def follow(the_file):
"""
Follow a given file and yield new lines when they are available, like `tail -f`.
"""
with open(the_file) as f:
f.seek(0, 2) # seek to eof
while True:
line = f.readline()
if not line:
time.sleep(0.1) # sleep briefly befor... | python | def follow(the_file):
"""
Follow a given file and yield new lines when they are available, like `tail -f`.
"""
with open(the_file) as f:
f.seek(0, 2) # seek to eof
while True:
line = f.readline()
if not line:
time.sleep(0.1) # sleep briefly befor... | [
"def",
"follow",
"(",
"the_file",
")",
":",
"with",
"open",
"(",
"the_file",
")",
"as",
"f",
":",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"# seek to eof",
"while",
"True",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"not",
"line",
... | Follow a given file and yield new lines when they are available, like `tail -f`. | [
"Follow",
"a",
"given",
"file",
"and",
"yield",
"new",
"lines",
"when",
"they",
"are",
"available",
"like",
"tail",
"-",
"f",
"."
] | 170caa1cd899de051ab961a3e46f7ecfbfed7764 | https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L116-L127 | train |
lebinh/ngxtop | ngxtop/ngxtop.py | map_field | def map_field(field, func, dict_sequence):
"""
Apply given function to value of given key in every dictionary in sequence and
set the result as new value for that key.
"""
for item in dict_sequence:
try:
item[field] = func(item.get(field, None))
yield item
exc... | python | def map_field(field, func, dict_sequence):
"""
Apply given function to value of given key in every dictionary in sequence and
set the result as new value for that key.
"""
for item in dict_sequence:
try:
item[field] = func(item.get(field, None))
yield item
exc... | [
"def",
"map_field",
"(",
"field",
",",
"func",
",",
"dict_sequence",
")",
":",
"for",
"item",
"in",
"dict_sequence",
":",
"try",
":",
"item",
"[",
"field",
"]",
"=",
"func",
"(",
"item",
".",
"get",
"(",
"field",
",",
"None",
")",
")",
"yield",
"it... | Apply given function to value of given key in every dictionary in sequence and
set the result as new value for that key. | [
"Apply",
"given",
"function",
"to",
"value",
"of",
"given",
"key",
"in",
"every",
"dictionary",
"in",
"sequence",
"and",
"set",
"the",
"result",
"as",
"new",
"value",
"for",
"that",
"key",
"."
] | 170caa1cd899de051ab961a3e46f7ecfbfed7764 | https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L130-L140 | train |
lebinh/ngxtop | ngxtop/ngxtop.py | add_field | def add_field(field, func, dict_sequence):
"""
Apply given function to the record and store result in given field of current record.
Do nothing if record already contains given field.
"""
for item in dict_sequence:
if field not in item:
item[field] = func(item)
yield item | python | def add_field(field, func, dict_sequence):
"""
Apply given function to the record and store result in given field of current record.
Do nothing if record already contains given field.
"""
for item in dict_sequence:
if field not in item:
item[field] = func(item)
yield item | [
"def",
"add_field",
"(",
"field",
",",
"func",
",",
"dict_sequence",
")",
":",
"for",
"item",
"in",
"dict_sequence",
":",
"if",
"field",
"not",
"in",
"item",
":",
"item",
"[",
"field",
"]",
"=",
"func",
"(",
"item",
")",
"yield",
"item"
] | Apply given function to the record and store result in given field of current record.
Do nothing if record already contains given field. | [
"Apply",
"given",
"function",
"to",
"the",
"record",
"and",
"store",
"result",
"in",
"given",
"field",
"of",
"current",
"record",
".",
"Do",
"nothing",
"if",
"record",
"already",
"contains",
"given",
"field",
"."
] | 170caa1cd899de051ab961a3e46f7ecfbfed7764 | https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L143-L151 | train |
dedupeio/dedupe | dedupe/canonical.py | getCanonicalRep | def getCanonicalRep(record_cluster):
"""
Given a list of records within a duplicate cluster, constructs a
canonical representation of the cluster by finding canonical
values for each field
"""
canonical_rep = {}
keys = record_cluster[0].keys()
for key in keys:
key_values = []
... | python | def getCanonicalRep(record_cluster):
"""
Given a list of records within a duplicate cluster, constructs a
canonical representation of the cluster by finding canonical
values for each field
"""
canonical_rep = {}
keys = record_cluster[0].keys()
for key in keys:
key_values = []
... | [
"def",
"getCanonicalRep",
"(",
"record_cluster",
")",
":",
"canonical_rep",
"=",
"{",
"}",
"keys",
"=",
"record_cluster",
"[",
"0",
"]",
".",
"keys",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"key_values",
"=",
"[",
"]",
"for",
"record",
"in",
"record... | Given a list of records within a duplicate cluster, constructs a
canonical representation of the cluster by finding canonical
values for each field | [
"Given",
"a",
"list",
"of",
"records",
"within",
"a",
"duplicate",
"cluster",
"constructs",
"a",
"canonical",
"representation",
"of",
"the",
"cluster",
"by",
"finding",
"canonical",
"values",
"for",
"each",
"field"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/canonical.py#L48-L71 | train |
dedupeio/dedupe | dedupe/predicates.py | nearIntegersPredicate | def nearIntegersPredicate(field):
"""return any integers N, N+1, and N-1"""
ints = integers(field)
near_ints = set()
for char in ints:
num = int(char)
near_ints.add(str(num - 1))
near_ints.add(str(num))
near_ints.add(str(num + 1))
return near_ints | python | def nearIntegersPredicate(field):
"""return any integers N, N+1, and N-1"""
ints = integers(field)
near_ints = set()
for char in ints:
num = int(char)
near_ints.add(str(num - 1))
near_ints.add(str(num))
near_ints.add(str(num + 1))
return near_ints | [
"def",
"nearIntegersPredicate",
"(",
"field",
")",
":",
"ints",
"=",
"integers",
"(",
"field",
")",
"near_ints",
"=",
"set",
"(",
")",
"for",
"char",
"in",
"ints",
":",
"num",
"=",
"int",
"(",
"char",
")",
"near_ints",
".",
"add",
"(",
"str",
"(",
... | return any integers N, N+1, and N-1 | [
"return",
"any",
"integers",
"N",
"N",
"+",
"1",
"and",
"N",
"-",
"1"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/predicates.py#L320-L330 | train |
dedupeio/dedupe | dedupe/core.py | randomPairsMatch | def randomPairsMatch(n_records_A, n_records_B, sample_size):
"""
Return random combinations of indices for record list A and B
"""
n = int(n_records_A * n_records_B)
if sample_size >= n:
random_pairs = numpy.arange(n)
else:
random_pairs = numpy.array(random.sample(range(n), samp... | python | def randomPairsMatch(n_records_A, n_records_B, sample_size):
"""
Return random combinations of indices for record list A and B
"""
n = int(n_records_A * n_records_B)
if sample_size >= n:
random_pairs = numpy.arange(n)
else:
random_pairs = numpy.array(random.sample(range(n), samp... | [
"def",
"randomPairsMatch",
"(",
"n_records_A",
",",
"n_records_B",
",",
"sample_size",
")",
":",
"n",
"=",
"int",
"(",
"n_records_A",
"*",
"n_records_B",
")",
"if",
"sample_size",
">=",
"n",
":",
"random_pairs",
"=",
"numpy",
".",
"arange",
"(",
"n",
")",
... | Return random combinations of indices for record list A and B | [
"Return",
"random",
"combinations",
"of",
"indices",
"for",
"record",
"list",
"A",
"and",
"B"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/core.py#L65-L79 | train |
dedupeio/dedupe | dedupe/api.py | Matching.thresholdBlocks | def thresholdBlocks(self, blocks, recall_weight=1.5): # pragma: nocover
"""
Returns the threshold that maximizes the expected F score, a
weighted average of precision and recall for a sample of
blocked data.
Arguments:
blocks -- Sequence of tuples of records, where eac... | python | def thresholdBlocks(self, blocks, recall_weight=1.5): # pragma: nocover
"""
Returns the threshold that maximizes the expected F score, a
weighted average of precision and recall for a sample of
blocked data.
Arguments:
blocks -- Sequence of tuples of records, where eac... | [
"def",
"thresholdBlocks",
"(",
"self",
",",
"blocks",
",",
"recall_weight",
"=",
"1.5",
")",
":",
"# pragma: nocover",
"candidate_records",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"self",
".",
"_blockedPairs",
"(",
"blocks",
")",
")",
"proba... | Returns the threshold that maximizes the expected F score, a
weighted average of precision and recall for a sample of
blocked data.
Arguments:
blocks -- Sequence of tuples of records, where each tuple is a
set of records covered by a blocking predicate
recall... | [
"Returns",
"the",
"threshold",
"that",
"maximizes",
"the",
"expected",
"F",
"score",
"a",
"weighted",
"average",
"of",
"precision",
"and",
"recall",
"for",
"a",
"sample",
"of",
"blocked",
"data",
"."
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L52-L94 | train |
dedupeio/dedupe | dedupe/api.py | DedupeMatching.match | def match(self, data, threshold=0.5, generator=False): # pragma: no cover
"""Identifies records that all refer to the same entity, returns
tuples
containing a set of record ids and a confidence score as a
float between 0 and 1. The record_ids within each set should
refer to the... | python | def match(self, data, threshold=0.5, generator=False): # pragma: no cover
"""Identifies records that all refer to the same entity, returns
tuples
containing a set of record ids and a confidence score as a
float between 0 and 1. The record_ids within each set should
refer to the... | [
"def",
"match",
"(",
"self",
",",
"data",
",",
"threshold",
"=",
"0.5",
",",
"generator",
"=",
"False",
")",
":",
"# pragma: no cover",
"blocked_pairs",
"=",
"self",
".",
"_blockData",
"(",
"data",
")",
"clusters",
"=",
"self",
".",
"matchBlocks",
"(",
"... | Identifies records that all refer to the same entity, returns
tuples
containing a set of record ids and a confidence score as a
float between 0 and 1. The record_ids within each set should
refer to the same entity and the confidence score is a measure
of our confidence that all ... | [
"Identifies",
"records",
"that",
"all",
"refer",
"to",
"the",
"same",
"entity",
"returns",
"tuples"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L190-L223 | train |
dedupeio/dedupe | dedupe/api.py | ActiveMatching.readTraining | def readTraining(self, training_file):
'''
Read training from previously built training data file object
Arguments:
training_file -- file object containing the training data
'''
logger.info('reading training from file')
training_pairs = json.load(training_file,... | python | def readTraining(self, training_file):
'''
Read training from previously built training data file object
Arguments:
training_file -- file object containing the training data
'''
logger.info('reading training from file')
training_pairs = json.load(training_file,... | [
"def",
"readTraining",
"(",
"self",
",",
"training_file",
")",
":",
"logger",
".",
"info",
"(",
"'reading training from file'",
")",
"training_pairs",
"=",
"json",
".",
"load",
"(",
"training_file",
",",
"cls",
"=",
"serializer",
".",
"dedupe_decoder",
")",
"s... | Read training from previously built training data file object
Arguments:
training_file -- file object containing the training data | [
"Read",
"training",
"from",
"previously",
"built",
"training",
"data",
"file",
"object"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L635-L647 | train |
dedupeio/dedupe | dedupe/api.py | ActiveMatching.writeTraining | def writeTraining(self, file_obj): # pragma: no cover
"""
Write to a json file that contains labeled examples
Keyword arguments:
file_obj -- file object to write training data to
"""
json.dump(self.training_pairs,
file_obj,
default=s... | python | def writeTraining(self, file_obj): # pragma: no cover
"""
Write to a json file that contains labeled examples
Keyword arguments:
file_obj -- file object to write training data to
"""
json.dump(self.training_pairs,
file_obj,
default=s... | [
"def",
"writeTraining",
"(",
"self",
",",
"file_obj",
")",
":",
"# pragma: no cover",
"json",
".",
"dump",
"(",
"self",
".",
"training_pairs",
",",
"file_obj",
",",
"default",
"=",
"serializer",
".",
"_to_json",
",",
"tuple_as_array",
"=",
"False",
",",
"ens... | Write to a json file that contains labeled examples
Keyword arguments:
file_obj -- file object to write training data to | [
"Write",
"to",
"a",
"json",
"file",
"that",
"contains",
"labeled",
"examples"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L680-L692 | train |
dedupeio/dedupe | dedupe/api.py | RecordLink.sample | def sample(self, data_1, data_2, sample_size=15000,
blocked_proportion=.5, original_length_1=None,
original_length_2=None):
'''
Draws a random sample of combinations of records from
the first and second datasets, and initializes active
learning with this sam... | python | def sample(self, data_1, data_2, sample_size=15000,
blocked_proportion=.5, original_length_1=None,
original_length_2=None):
'''
Draws a random sample of combinations of records from
the first and second datasets, and initializes active
learning with this sam... | [
"def",
"sample",
"(",
"self",
",",
"data_1",
",",
"data_2",
",",
"sample_size",
"=",
"15000",
",",
"blocked_proportion",
"=",
".5",
",",
"original_length_1",
"=",
"None",
",",
"original_length_2",
"=",
"None",
")",
":",
"self",
".",
"_checkData",
"(",
"dat... | Draws a random sample of combinations of records from
the first and second datasets, and initializes active
learning with this sample
Arguments:
data_1 -- Dictionary of records from first dataset, where the
keys are record_ids and the values are dictionaries... | [
"Draws",
"a",
"random",
"sample",
"of",
"combinations",
"of",
"records",
"from",
"the",
"first",
"and",
"second",
"datasets",
"and",
"initializes",
"active",
"learning",
"with",
"this",
"sample"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L816-L841 | train |
dedupeio/dedupe | dedupe/clustering.py | condensedDistance | def condensedDistance(dupes):
'''
Convert the pairwise list of distances in dupes to "condensed
distance matrix" required by the hierarchical clustering
algorithms. Also return a dictionary that maps the distance matrix
to the record_ids.
The formula for an index of the condensed matrix is
... | python | def condensedDistance(dupes):
'''
Convert the pairwise list of distances in dupes to "condensed
distance matrix" required by the hierarchical clustering
algorithms. Also return a dictionary that maps the distance matrix
to the record_ids.
The formula for an index of the condensed matrix is
... | [
"def",
"condensedDistance",
"(",
"dupes",
")",
":",
"candidate_set",
"=",
"numpy",
".",
"unique",
"(",
"dupes",
"[",
"'pairs'",
"]",
")",
"i_to_id",
"=",
"dict",
"(",
"enumerate",
"(",
"candidate_set",
")",
")",
"ids",
"=",
"candidate_set",
".",
"searchsor... | Convert the pairwise list of distances in dupes to "condensed
distance matrix" required by the hierarchical clustering
algorithms. Also return a dictionary that maps the distance matrix
to the record_ids.
The formula for an index of the condensed matrix is
index = {N choose 2}-{N-row choose 2} + (... | [
"Convert",
"the",
"pairwise",
"list",
"of",
"distances",
"in",
"dupes",
"to",
"condensed",
"distance",
"matrix",
"required",
"by",
"the",
"hierarchical",
"clustering",
"algorithms",
".",
"Also",
"return",
"a",
"dictionary",
"that",
"maps",
"the",
"distance",
"ma... | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/clustering.py#L95-L131 | train |
dedupeio/dedupe | dedupe/clustering.py | cluster | def cluster(dupes, threshold=.5, max_components=30000):
'''
Takes in a list of duplicate pairs and clusters them in to a
list records that all refer to the same entity based on a given
threshold
Keyword arguments:
threshold -- number betweent 0 and 1 (default is .5). lowering the
... | python | def cluster(dupes, threshold=.5, max_components=30000):
'''
Takes in a list of duplicate pairs and clusters them in to a
list records that all refer to the same entity based on a given
threshold
Keyword arguments:
threshold -- number betweent 0 and 1 (default is .5). lowering the
... | [
"def",
"cluster",
"(",
"dupes",
",",
"threshold",
"=",
".5",
",",
"max_components",
"=",
"30000",
")",
":",
"distance_threshold",
"=",
"1",
"-",
"threshold",
"dupe_sub_graphs",
"=",
"connected_components",
"(",
"dupes",
",",
"max_components",
")",
"for",
"sub_... | Takes in a list of duplicate pairs and clusters them in to a
list records that all refer to the same entity based on a given
threshold
Keyword arguments:
threshold -- number betweent 0 and 1 (default is .5). lowering the
number will increase precision, raising it will increase
... | [
"Takes",
"in",
"a",
"list",
"of",
"duplicate",
"pairs",
"and",
"clusters",
"them",
"in",
"to",
"a",
"list",
"records",
"that",
"all",
"refer",
"to",
"the",
"same",
"entity",
"based",
"on",
"a",
"given",
"threshold"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/clustering.py#L134-L174 | train |
dedupeio/dedupe | dedupe/clustering.py | confidences | def confidences(cluster, condensed_distances, d):
'''
We calculate a per record score that is similar to a standard
deviation. The main reason is that these record scores can be
used to calculate the standard deviation of an entire cluster,
which is a reasonable metric for clusters.
'''
sc... | python | def confidences(cluster, condensed_distances, d):
'''
We calculate a per record score that is similar to a standard
deviation. The main reason is that these record scores can be
used to calculate the standard deviation of an entire cluster,
which is a reasonable metric for clusters.
'''
sc... | [
"def",
"confidences",
"(",
"cluster",
",",
"condensed_distances",
",",
"d",
")",
":",
"scores",
"=",
"dict",
".",
"fromkeys",
"(",
"cluster",
",",
"0.0",
")",
"squared_distances",
"=",
"condensed_distances",
"**",
"2",
"for",
"i",
",",
"j",
"in",
"itertool... | We calculate a per record score that is similar to a standard
deviation. The main reason is that these record scores can be
used to calculate the standard deviation of an entire cluster,
which is a reasonable metric for clusters. | [
"We",
"calculate",
"a",
"per",
"record",
"score",
"that",
"is",
"similar",
"to",
"a",
"standard",
"deviation",
".",
"The",
"main",
"reason",
"is",
"that",
"these",
"record",
"scores",
"can",
"be",
"used",
"to",
"calculate",
"the",
"standard",
"deviation",
... | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/clustering.py#L177-L196 | train |
dedupeio/dedupe | dedupe/convenience.py | consoleLabel | def consoleLabel(deduper): # pragma: no cover
'''
Command line interface for presenting and labeling training pairs
by the user
Argument :
A deduper object
'''
finished = False
use_previous = False
fields = unique(field.field
for field
in de... | python | def consoleLabel(deduper): # pragma: no cover
'''
Command line interface for presenting and labeling training pairs
by the user
Argument :
A deduper object
'''
finished = False
use_previous = False
fields = unique(field.field
for field
in de... | [
"def",
"consoleLabel",
"(",
"deduper",
")",
":",
"# pragma: no cover",
"finished",
"=",
"False",
"use_previous",
"=",
"False",
"fields",
"=",
"unique",
"(",
"field",
".",
"field",
"for",
"field",
"in",
"deduper",
".",
"data_model",
".",
"primary_fields",
")",
... | Command line interface for presenting and labeling training pairs
by the user
Argument :
A deduper object | [
"Command",
"line",
"interface",
"for",
"presenting",
"and",
"labeling",
"training",
"pairs",
"by",
"the",
"user"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/convenience.py#L19-L105 | train |
dedupeio/dedupe | dedupe/convenience.py | trainingDataLink | def trainingDataLink(data_1, data_2, common_key, training_size=50000): # pragma: nocover
'''
Construct training data for consumption by the ActiveLearning
markPairs method from already linked datasets.
Arguments :
data_1 -- Dictionary of records from first dataset, where the keys
... | python | def trainingDataLink(data_1, data_2, common_key, training_size=50000): # pragma: nocover
'''
Construct training data for consumption by the ActiveLearning
markPairs method from already linked datasets.
Arguments :
data_1 -- Dictionary of records from first dataset, where the keys
... | [
"def",
"trainingDataLink",
"(",
"data_1",
",",
"data_2",
",",
"common_key",
",",
"training_size",
"=",
"50000",
")",
":",
"# pragma: nocover",
"identified_records",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"[",
"[",
"]",
",",
"[",
"]",
"]"... | Construct training data for consumption by the ActiveLearning
markPairs method from already linked datasets.
Arguments :
data_1 -- Dictionary of records from first dataset, where the keys
are record_ids and the values are dictionaries with the
keys being fie... | [
"Construct",
"training",
"data",
"for",
"consumption",
"by",
"the",
"ActiveLearning",
"markPairs",
"method",
"from",
"already",
"linked",
"datasets",
"."
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/convenience.py#L108-L167 | train |
dedupeio/dedupe | dedupe/convenience.py | trainingDataDedupe | def trainingDataDedupe(data, common_key, training_size=50000): # pragma: nocover
'''
Construct training data for consumption by the ActiveLearning
markPairs method from an already deduplicated dataset.
Arguments :
data -- Dictionary of records, where the keys are record_ids and
... | python | def trainingDataDedupe(data, common_key, training_size=50000): # pragma: nocover
'''
Construct training data for consumption by the ActiveLearning
markPairs method from an already deduplicated dataset.
Arguments :
data -- Dictionary of records, where the keys are record_ids and
... | [
"def",
"trainingDataDedupe",
"(",
"data",
",",
"common_key",
",",
"training_size",
"=",
"50000",
")",
":",
"# pragma: nocover",
"identified_records",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"matched_pairs",
"=",
"set",
"(",
")",
"distinct_pairs",... | Construct training data for consumption by the ActiveLearning
markPairs method from an already deduplicated dataset.
Arguments :
data -- Dictionary of records, where the keys are record_ids and
the values are dictionaries with the keys being
field names
... | [
"Construct",
"training",
"data",
"for",
"consumption",
"by",
"the",
"ActiveLearning",
"markPairs",
"method",
"from",
"an",
"already",
"deduplicated",
"dataset",
"."
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/convenience.py#L170-L228 | train |
dedupeio/dedupe | dedupe/labeler.py | unique | def unique(seq):
"""Return the unique elements of a collection even if those elements are
unhashable and unsortable, like dicts and sets"""
cleaned = []
for each in seq:
if each not in cleaned:
cleaned.append(each)
return cleaned | python | def unique(seq):
"""Return the unique elements of a collection even if those elements are
unhashable and unsortable, like dicts and sets"""
cleaned = []
for each in seq:
if each not in cleaned:
cleaned.append(each)
return cleaned | [
"def",
"unique",
"(",
"seq",
")",
":",
"cleaned",
"=",
"[",
"]",
"for",
"each",
"in",
"seq",
":",
"if",
"each",
"not",
"in",
"cleaned",
":",
"cleaned",
".",
"append",
"(",
"each",
")",
"return",
"cleaned"
] | Return the unique elements of a collection even if those elements are
unhashable and unsortable, like dicts and sets | [
"Return",
"the",
"unique",
"elements",
"of",
"a",
"collection",
"even",
"if",
"those",
"elements",
"are",
"unhashable",
"and",
"unsortable",
"like",
"dicts",
"and",
"sets"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/labeler.py#L383-L390 | train |
dedupeio/dedupe | dedupe/training.py | BlockLearner.learn | def learn(self, matches, recall):
'''
Takes in a set of training pairs and predicates and tries to find
a good set of blocking rules.
'''
compound_length = 2
dupe_cover = Cover(self.blocker.predicates, matches)
dupe_cover.dominators(cost=self.total_cover)
... | python | def learn(self, matches, recall):
'''
Takes in a set of training pairs and predicates and tries to find
a good set of blocking rules.
'''
compound_length = 2
dupe_cover = Cover(self.blocker.predicates, matches)
dupe_cover.dominators(cost=self.total_cover)
... | [
"def",
"learn",
"(",
"self",
",",
"matches",
",",
"recall",
")",
":",
"compound_length",
"=",
"2",
"dupe_cover",
"=",
"Cover",
"(",
"self",
".",
"blocker",
".",
"predicates",
",",
"matches",
")",
"dupe_cover",
".",
"dominators",
"(",
"cost",
"=",
"self",... | Takes in a set of training pairs and predicates and tries to find
a good set of blocking rules. | [
"Takes",
"in",
"a",
"set",
"of",
"training",
"pairs",
"and",
"predicates",
"and",
"tries",
"to",
"find",
"a",
"good",
"set",
"of",
"blocking",
"rules",
"."
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/training.py#L24-L62 | train |
dedupeio/dedupe | dedupe/blocking.py | Blocker.unindex | def unindex(self, data, field):
'''Remove index of a given set of data'''
indices = extractIndices(self.index_fields[field])
for doc in data:
if doc:
for _, index, preprocess in indices:
index.unindex(preprocess(doc))
for index_type, inde... | python | def unindex(self, data, field):
'''Remove index of a given set of data'''
indices = extractIndices(self.index_fields[field])
for doc in data:
if doc:
for _, index, preprocess in indices:
index.unindex(preprocess(doc))
for index_type, inde... | [
"def",
"unindex",
"(",
"self",
",",
"data",
",",
"field",
")",
":",
"indices",
"=",
"extractIndices",
"(",
"self",
".",
"index_fields",
"[",
"field",
"]",
")",
"for",
"doc",
"in",
"data",
":",
"if",
"doc",
":",
"for",
"_",
",",
"index",
",",
"prepr... | Remove index of a given set of data | [
"Remove",
"index",
"of",
"a",
"given",
"set",
"of",
"data"
] | 9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b | https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/blocking.py#L80-L95 | train |
marcgibbons/django-rest-swagger | example_app/snippets/models.py | Snippet.save | def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title}... | python | def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title}... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lexer",
"=",
"get_lexer_by_name",
"(",
"self",
".",
"language",
")",
"linenos",
"=",
"self",
".",
"linenos",
"and",
"'table'",
"or",
"False",
"options",
"=",
"self",
".... | Use the `pygments` library to create a highlighted HTML
representation of the code snippet. | [
"Use",
"the",
"pygments",
"library",
"to",
"create",
"a",
"highlighted",
"HTML",
"representation",
"of",
"the",
"code",
"snippet",
"."
] | 102d22eaefb7898342ba2fb5af5618b9e3a32f1d | https://github.com/marcgibbons/django-rest-swagger/blob/102d22eaefb7898342ba2fb5af5618b9e3a32f1d/example_app/snippets/models.py#L38-L54 | train |
adafruit/Adafruit_Blinka | src/adafruit_blinka/microcontroller/generic_linux/i2c.py | I2C.scan | def scan(self):
"""Try to read a byte from each address, if you get an OSError it means the device isnt there"""
found = []
for addr in range(0,0x80):
try:
self._i2c_bus.read_byte(addr)
except OSError:
continue
found.append(addr... | python | def scan(self):
"""Try to read a byte from each address, if you get an OSError it means the device isnt there"""
found = []
for addr in range(0,0x80):
try:
self._i2c_bus.read_byte(addr)
except OSError:
continue
found.append(addr... | [
"def",
"scan",
"(",
"self",
")",
":",
"found",
"=",
"[",
"]",
"for",
"addr",
"in",
"range",
"(",
"0",
",",
"0x80",
")",
":",
"try",
":",
"self",
".",
"_i2c_bus",
".",
"read_byte",
"(",
"addr",
")",
"except",
"OSError",
":",
"continue",
"found",
"... | Try to read a byte from each address, if you get an OSError it means the device isnt there | [
"Try",
"to",
"read",
"a",
"byte",
"from",
"each",
"address",
"if",
"you",
"get",
"an",
"OSError",
"it",
"means",
"the",
"device",
"isnt",
"there"
] | b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff | https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/generic_linux/i2c.py#L24-L33 | train |
adafruit/Adafruit_Blinka | src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py | final | def final():
"""In case the program is cancelled or quit, we need to clean up the PulseIn
helper process and also the message queue, this is called at exit to do so"""
if DEBUG:
print("Cleaning up message queues", queues)
print("Cleaning up processes", procs)
for q in queues:
q.r... | python | def final():
"""In case the program is cancelled or quit, we need to clean up the PulseIn
helper process and also the message queue, this is called at exit to do so"""
if DEBUG:
print("Cleaning up message queues", queues)
print("Cleaning up processes", procs)
for q in queues:
q.r... | [
"def",
"final",
"(",
")",
":",
"if",
"DEBUG",
":",
"print",
"(",
"\"Cleaning up message queues\"",
",",
"queues",
")",
"print",
"(",
"\"Cleaning up processes\"",
",",
"procs",
")",
"for",
"q",
"in",
"queues",
":",
"q",
".",
"remove",
"(",
")",
"for",
"pr... | In case the program is cancelled or quit, we need to clean up the PulseIn
helper process and also the message queue, this is called at exit to do so | [
"In",
"case",
"the",
"program",
"is",
"cancelled",
"or",
"quit",
"we",
"need",
"to",
"clean",
"up",
"the",
"PulseIn",
"helper",
"process",
"and",
"also",
"the",
"message",
"queue",
"this",
"is",
"called",
"at",
"exit",
"to",
"do",
"so"
] | b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff | https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L16-L25 | train |
adafruit/Adafruit_Blinka | src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py | PulseIn._wait_receive_msg | def _wait_receive_msg(self, timeout=0.25, type=2):
"""Internal helper that will wait for new messages of a given type,
and throw an exception on timeout"""
stamp = time.monotonic()
while (time.monotonic() - stamp) < timeout:
try:
message = self._mq.receive(blo... | python | def _wait_receive_msg(self, timeout=0.25, type=2):
"""Internal helper that will wait for new messages of a given type,
and throw an exception on timeout"""
stamp = time.monotonic()
while (time.monotonic() - stamp) < timeout:
try:
message = self._mq.receive(blo... | [
"def",
"_wait_receive_msg",
"(",
"self",
",",
"timeout",
"=",
"0.25",
",",
"type",
"=",
"2",
")",
":",
"stamp",
"=",
"time",
".",
"monotonic",
"(",
")",
"while",
"(",
"time",
".",
"monotonic",
"(",
")",
"-",
"stamp",
")",
"<",
"timeout",
":",
"try"... | Internal helper that will wait for new messages of a given type,
and throw an exception on timeout | [
"Internal",
"helper",
"that",
"will",
"wait",
"for",
"new",
"messages",
"of",
"a",
"given",
"type",
"and",
"throw",
"an",
"exception",
"on",
"timeout"
] | b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff | https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L69-L80 | train |
adafruit/Adafruit_Blinka | src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py | PulseIn.deinit | def deinit(self):
"""Deinitialises the PulseIn and releases any hardware and software
resources for reuse."""
# Clean up after ourselves
self._process.terminate()
procs.remove(self._process)
self._mq.remove()
queues.remove(self._mq) | python | def deinit(self):
"""Deinitialises the PulseIn and releases any hardware and software
resources for reuse."""
# Clean up after ourselves
self._process.terminate()
procs.remove(self._process)
self._mq.remove()
queues.remove(self._mq) | [
"def",
"deinit",
"(",
"self",
")",
":",
"# Clean up after ourselves",
"self",
".",
"_process",
".",
"terminate",
"(",
")",
"procs",
".",
"remove",
"(",
"self",
".",
"_process",
")",
"self",
".",
"_mq",
".",
"remove",
"(",
")",
"queues",
".",
"remove",
... | Deinitialises the PulseIn and releases any hardware and software
resources for reuse. | [
"Deinitialises",
"the",
"PulseIn",
"and",
"releases",
"any",
"hardware",
"and",
"software",
"resources",
"for",
"reuse",
"."
] | b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff | https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L82-L89 | train |
adafruit/Adafruit_Blinka | src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py | PulseIn.resume | def resume(self, trigger_duration=0):
"""Resumes pulse capture after an optional trigger pulse."""
if trigger_duration != 0:
self._mq.send("t%d" % trigger_duration, True, type=1)
else:
self._mq.send("r", True, type=1)
self._paused = False | python | def resume(self, trigger_duration=0):
"""Resumes pulse capture after an optional trigger pulse."""
if trigger_duration != 0:
self._mq.send("t%d" % trigger_duration, True, type=1)
else:
self._mq.send("r", True, type=1)
self._paused = False | [
"def",
"resume",
"(",
"self",
",",
"trigger_duration",
"=",
"0",
")",
":",
"if",
"trigger_duration",
"!=",
"0",
":",
"self",
".",
"_mq",
".",
"send",
"(",
"\"t%d\"",
"%",
"trigger_duration",
",",
"True",
",",
"type",
"=",
"1",
")",
"else",
":",
"self... | Resumes pulse capture after an optional trigger pulse. | [
"Resumes",
"pulse",
"capture",
"after",
"an",
"optional",
"trigger",
"pulse",
"."
] | b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff | https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L99-L105 | train |
adafruit/Adafruit_Blinka | src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py | PulseIn.pause | def pause(self):
"""Pause pulse capture"""
self._mq.send("p", True, type=1)
self._paused = True | python | def pause(self):
"""Pause pulse capture"""
self._mq.send("p", True, type=1)
self._paused = True | [
"def",
"pause",
"(",
"self",
")",
":",
"self",
".",
"_mq",
".",
"send",
"(",
"\"p\"",
",",
"True",
",",
"type",
"=",
"1",
")",
"self",
".",
"_paused",
"=",
"True"
] | Pause pulse capture | [
"Pause",
"pulse",
"capture"
] | b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff | https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L107-L110 | train |
adafruit/Adafruit_Blinka | src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py | PulseIn.popleft | def popleft(self):
"""Removes and returns the oldest read pulse."""
self._mq.send("^", True, type=1)
message = self._wait_receive_msg()
reply = int(message[0].decode('utf-8'))
#print(reply)
if reply == -1:
raise IndexError("pop from empty list")
return... | python | def popleft(self):
"""Removes and returns the oldest read pulse."""
self._mq.send("^", True, type=1)
message = self._wait_receive_msg()
reply = int(message[0].decode('utf-8'))
#print(reply)
if reply == -1:
raise IndexError("pop from empty list")
return... | [
"def",
"popleft",
"(",
"self",
")",
":",
"self",
".",
"_mq",
".",
"send",
"(",
"\"^\"",
",",
"True",
",",
"type",
"=",
"1",
")",
"message",
"=",
"self",
".",
"_wait_receive_msg",
"(",
")",
"reply",
"=",
"int",
"(",
"message",
"[",
"0",
"]",
".",
... | Removes and returns the oldest read pulse. | [
"Removes",
"and",
"returns",
"the",
"oldest",
"read",
"pulse",
"."
] | b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff | https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L128-L136 | train |
jupyter-widgets/ipyleaflet | ipyleaflet/leaflet.py | LayerGroup._validate_layers | def _validate_layers(self, proposal):
'''Validate layers list.
Makes sure only one instance of any given layer can exist in the
layers list.
'''
self._layer_ids = [l.model_id for l in proposal.value]
if len(set(self._layer_ids)) != len(self._layer_ids):
raise... | python | def _validate_layers(self, proposal):
'''Validate layers list.
Makes sure only one instance of any given layer can exist in the
layers list.
'''
self._layer_ids = [l.model_id for l in proposal.value]
if len(set(self._layer_ids)) != len(self._layer_ids):
raise... | [
"def",
"_validate_layers",
"(",
"self",
",",
"proposal",
")",
":",
"self",
".",
"_layer_ids",
"=",
"[",
"l",
".",
"model_id",
"for",
"l",
"in",
"proposal",
".",
"value",
"]",
"if",
"len",
"(",
"set",
"(",
"self",
".",
"_layer_ids",
")",
")",
"!=",
... | Validate layers list.
Makes sure only one instance of any given layer can exist in the
layers list. | [
"Validate",
"layers",
"list",
"."
] | 74488d4699a5663fc28aabf94ebf08d956a30598 | https://github.com/jupyter-widgets/ipyleaflet/blob/74488d4699a5663fc28aabf94ebf08d956a30598/ipyleaflet/leaflet.py#L431-L440 | train |
jupyter-widgets/ipyleaflet | ipyleaflet/leaflet.py | GeoJSON.on_hover | def on_hover(self, callback, remove=False):
'''
The hover callback takes an unpacked set of keyword arguments.
'''
self._hover_callbacks.register_callback(callback, remove=remove) | python | def on_hover(self, callback, remove=False):
'''
The hover callback takes an unpacked set of keyword arguments.
'''
self._hover_callbacks.register_callback(callback, remove=remove) | [
"def",
"on_hover",
"(",
"self",
",",
"callback",
",",
"remove",
"=",
"False",
")",
":",
"self",
".",
"_hover_callbacks",
".",
"register_callback",
"(",
"callback",
",",
"remove",
"=",
"remove",
")"
] | The hover callback takes an unpacked set of keyword arguments. | [
"The",
"hover",
"callback",
"takes",
"an",
"unpacked",
"set",
"of",
"keyword",
"arguments",
"."
] | 74488d4699a5663fc28aabf94ebf08d956a30598 | https://github.com/jupyter-widgets/ipyleaflet/blob/74488d4699a5663fc28aabf94ebf08d956a30598/ipyleaflet/leaflet.py#L490-L494 | train |
jupyter-widgets/ipyleaflet | ipyleaflet/leaflet.py | Map._validate_controls | def _validate_controls(self, proposal):
'''Validate controls list.
Makes sure only one instance of any given layer can exist in the
controls list.
'''
self._control_ids = [c.model_id for c in proposal.value]
if len(set(self._control_ids)) != len(self._control_ids):
... | python | def _validate_controls(self, proposal):
'''Validate controls list.
Makes sure only one instance of any given layer can exist in the
controls list.
'''
self._control_ids = [c.model_id for c in proposal.value]
if len(set(self._control_ids)) != len(self._control_ids):
... | [
"def",
"_validate_controls",
"(",
"self",
",",
"proposal",
")",
":",
"self",
".",
"_control_ids",
"=",
"[",
"c",
".",
"model_id",
"for",
"c",
"in",
"proposal",
".",
"value",
"]",
"if",
"len",
"(",
"set",
"(",
"self",
".",
"_control_ids",
")",
")",
"!... | Validate controls list.
Makes sure only one instance of any given layer can exist in the
controls list. | [
"Validate",
"controls",
"list",
"."
] | 74488d4699a5663fc28aabf94ebf08d956a30598 | https://github.com/jupyter-widgets/ipyleaflet/blob/74488d4699a5663fc28aabf94ebf08d956a30598/ipyleaflet/leaflet.py#L881-L890 | train |
mbedmicro/pyOCD | pyocd/debug/context.py | DebugContext.read_core_register | def read_core_register(self, reg):
"""
read CPU register
Unpack floating point register values
"""
regIndex = register_name_to_index(reg)
regValue = self.read_core_register_raw(regIndex)
# Convert int to float.
if is_single_float_register(regIndex):
... | python | def read_core_register(self, reg):
"""
read CPU register
Unpack floating point register values
"""
regIndex = register_name_to_index(reg)
regValue = self.read_core_register_raw(regIndex)
# Convert int to float.
if is_single_float_register(regIndex):
... | [
"def",
"read_core_register",
"(",
"self",
",",
"reg",
")",
":",
"regIndex",
"=",
"register_name_to_index",
"(",
"reg",
")",
"regValue",
"=",
"self",
".",
"read_core_register_raw",
"(",
"regIndex",
")",
"# Convert int to float.",
"if",
"is_single_float_register",
"("... | read CPU register
Unpack floating point register values | [
"read",
"CPU",
"register",
"Unpack",
"floating",
"point",
"register",
"values"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/debug/context.py#L58-L70 | train |
mbedmicro/pyOCD | pyocd/debug/context.py | DebugContext.write_core_register | def write_core_register(self, reg, data):
"""
write a CPU register.
Will need to pack floating point register values before writing.
"""
regIndex = register_name_to_index(reg)
# Convert float to int.
if is_single_float_register(regIndex) and type(data) is float:
... | python | def write_core_register(self, reg, data):
"""
write a CPU register.
Will need to pack floating point register values before writing.
"""
regIndex = register_name_to_index(reg)
# Convert float to int.
if is_single_float_register(regIndex) and type(data) is float:
... | [
"def",
"write_core_register",
"(",
"self",
",",
"reg",
",",
"data",
")",
":",
"regIndex",
"=",
"register_name_to_index",
"(",
"reg",
")",
"# Convert float to int.",
"if",
"is_single_float_register",
"(",
"regIndex",
")",
"and",
"type",
"(",
"data",
")",
"is",
... | write a CPU register.
Will need to pack floating point register values before writing. | [
"write",
"a",
"CPU",
"register",
".",
"Will",
"need",
"to",
"pack",
"floating",
"point",
"register",
"values",
"before",
"writing",
"."
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/debug/context.py#L84-L95 | train |
mbedmicro/pyOCD | pyocd/probe/cmsis_dap_probe.py | CMSISDAPProbe.connect | def connect(self, protocol=None):
"""Initialize DAP IO pins for JTAG or SWD"""
# Convert protocol to port enum.
if protocol is not None:
port = self.PORT_MAP[protocol]
else:
port = DAPAccess.PORT.DEFAULT
try:
self._link.connect(port)
... | python | def connect(self, protocol=None):
"""Initialize DAP IO pins for JTAG or SWD"""
# Convert protocol to port enum.
if protocol is not None:
port = self.PORT_MAP[protocol]
else:
port = DAPAccess.PORT.DEFAULT
try:
self._link.connect(port)
... | [
"def",
"connect",
"(",
"self",
",",
"protocol",
"=",
"None",
")",
":",
"# Convert protocol to port enum.",
"if",
"protocol",
"is",
"not",
"None",
":",
"port",
"=",
"self",
".",
"PORT_MAP",
"[",
"protocol",
"]",
"else",
":",
"port",
"=",
"DAPAccess",
".",
... | Initialize DAP IO pins for JTAG or SWD | [
"Initialize",
"DAP",
"IO",
"pins",
"for",
"JTAG",
"or",
"SWD"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/cmsis_dap_probe.py#L165-L182 | train |
mbedmicro/pyOCD | pyocd/probe/cmsis_dap_probe.py | CMSISDAPProbe.set_clock | def set_clock(self, frequency):
"""Set the frequency for JTAG and SWD in Hz
This function is safe to call before connect is called.
"""
try:
self._link.set_clock(frequency)
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | python | def set_clock(self, frequency):
"""Set the frequency for JTAG and SWD in Hz
This function is safe to call before connect is called.
"""
try:
self._link.set_clock(frequency)
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | [
"def",
"set_clock",
"(",
"self",
",",
"frequency",
")",
":",
"try",
":",
"self",
".",
"_link",
".",
"set_clock",
"(",
"frequency",
")",
"except",
"DAPAccess",
".",
"Error",
"as",
"exc",
":",
"six",
".",
"raise_from",
"(",
"self",
".",
"_convert_exception... | Set the frequency for JTAG and SWD in Hz
This function is safe to call before connect is called. | [
"Set",
"the",
"frequency",
"for",
"JTAG",
"and",
"SWD",
"in",
"Hz"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/cmsis_dap_probe.py#L201-L209 | train |
mbedmicro/pyOCD | pyocd/probe/cmsis_dap_probe.py | CMSISDAPProbe.reset | def reset(self):
"""Reset the target"""
try:
self._invalidate_cached_registers()
self._link.reset()
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | python | def reset(self):
"""Reset the target"""
try:
self._invalidate_cached_registers()
self._link.reset()
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | [
"def",
"reset",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_invalidate_cached_registers",
"(",
")",
"self",
".",
"_link",
".",
"reset",
"(",
")",
"except",
"DAPAccess",
".",
"Error",
"as",
"exc",
":",
"six",
".",
"raise_from",
"(",
"self",
".",
... | Reset the target | [
"Reset",
"the",
"target"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/cmsis_dap_probe.py#L211-L217 | train |
mbedmicro/pyOCD | pyocd/probe/cmsis_dap_probe.py | CMSISDAPProbe.assert_reset | def assert_reset(self, asserted):
"""Assert or de-assert target reset line"""
try:
self._invalidate_cached_registers()
self._link.assert_reset(asserted)
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | python | def assert_reset(self, asserted):
"""Assert or de-assert target reset line"""
try:
self._invalidate_cached_registers()
self._link.assert_reset(asserted)
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | [
"def",
"assert_reset",
"(",
"self",
",",
"asserted",
")",
":",
"try",
":",
"self",
".",
"_invalidate_cached_registers",
"(",
")",
"self",
".",
"_link",
".",
"assert_reset",
"(",
"asserted",
")",
"except",
"DAPAccess",
".",
"Error",
"as",
"exc",
":",
"six",... | Assert or de-assert target reset line | [
"Assert",
"or",
"de",
"-",
"assert",
"target",
"reset",
"line"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/cmsis_dap_probe.py#L219-L225 | train |
mbedmicro/pyOCD | pyocd/debug/svd/parser.py | _get_text | def _get_text(node, tag, default=None):
"""Get the text for the provided tag from the provided node"""
try:
return node.find(tag).text
except AttributeError:
return default | python | def _get_text(node, tag, default=None):
"""Get the text for the provided tag from the provided node"""
try:
return node.find(tag).text
except AttributeError:
return default | [
"def",
"_get_text",
"(",
"node",
",",
"tag",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"node",
".",
"find",
"(",
"tag",
")",
".",
"text",
"except",
"AttributeError",
":",
"return",
"default"
] | Get the text for the provided tag from the provided node | [
"Get",
"the",
"text",
"for",
"the",
"provided",
"tag",
"from",
"the",
"provided",
"node"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/debug/svd/parser.py#L33-L38 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.init | def init(self):
"""
Cortex M initialization. The bus must be accessible when this method is called.
"""
if not self.call_delegate('will_start_debug_core', core=self):
if self.halt_on_connect:
self.halt()
self._read_core_type()
self._che... | python | def init(self):
"""
Cortex M initialization. The bus must be accessible when this method is called.
"""
if not self.call_delegate('will_start_debug_core', core=self):
if self.halt_on_connect:
self.halt()
self._read_core_type()
self._che... | [
"def",
"init",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"call_delegate",
"(",
"'will_start_debug_core'",
",",
"core",
"=",
"self",
")",
":",
"if",
"self",
".",
"halt_on_connect",
":",
"self",
".",
"halt",
"(",
")",
"self",
".",
"_read_core_type",... | Cortex M initialization. The bus must be accessible when this method is called. | [
"Cortex",
"M",
"initialization",
".",
"The",
"bus",
"must",
"be",
"accessible",
"when",
"this",
"method",
"is",
"called",
"."
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L478-L490 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.write_memory | def write_memory(self, addr, value, transfer_size=32):
"""
write a memory location.
By default the transfer size is a word
"""
self.ap.write_memory(addr, value, transfer_size) | python | def write_memory(self, addr, value, transfer_size=32):
"""
write a memory location.
By default the transfer size is a word
"""
self.ap.write_memory(addr, value, transfer_size) | [
"def",
"write_memory",
"(",
"self",
",",
"addr",
",",
"value",
",",
"transfer_size",
"=",
"32",
")",
":",
"self",
".",
"ap",
".",
"write_memory",
"(",
"addr",
",",
"value",
",",
"transfer_size",
")"
] | write a memory location.
By default the transfer size is a word | [
"write",
"a",
"memory",
"location",
".",
"By",
"default",
"the",
"transfer",
"size",
"is",
"a",
"word"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L592-L597 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.read_memory | def read_memory(self, addr, transfer_size=32, now=True):
"""
read a memory location. By default, a word will
be read
"""
result = self.ap.read_memory(addr, transfer_size, now)
# Read callback returned for async reads.
def read_memory_cb():
return self... | python | def read_memory(self, addr, transfer_size=32, now=True):
"""
read a memory location. By default, a word will
be read
"""
result = self.ap.read_memory(addr, transfer_size, now)
# Read callback returned for async reads.
def read_memory_cb():
return self... | [
"def",
"read_memory",
"(",
"self",
",",
"addr",
",",
"transfer_size",
"=",
"32",
",",
"now",
"=",
"True",
")",
":",
"result",
"=",
"self",
".",
"ap",
".",
"read_memory",
"(",
"addr",
",",
"transfer_size",
",",
"now",
")",
"# Read callback returned for asyn... | read a memory location. By default, a word will
be read | [
"read",
"a",
"memory",
"location",
".",
"By",
"default",
"a",
"word",
"will",
"be",
"read"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L599-L613 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.read_memory_block8 | def read_memory_block8(self, addr, size):
"""
read a block of unaligned bytes in memory. Returns
an array of byte values
"""
data = self.ap.read_memory_block8(addr, size)
return self.bp_manager.filter_memory_unaligned_8(addr, size, data) | python | def read_memory_block8(self, addr, size):
"""
read a block of unaligned bytes in memory. Returns
an array of byte values
"""
data = self.ap.read_memory_block8(addr, size)
return self.bp_manager.filter_memory_unaligned_8(addr, size, data) | [
"def",
"read_memory_block8",
"(",
"self",
",",
"addr",
",",
"size",
")",
":",
"data",
"=",
"self",
".",
"ap",
".",
"read_memory_block8",
"(",
"addr",
",",
"size",
")",
"return",
"self",
".",
"bp_manager",
".",
"filter_memory_unaligned_8",
"(",
"addr",
",",... | read a block of unaligned bytes in memory. Returns
an array of byte values | [
"read",
"a",
"block",
"of",
"unaligned",
"bytes",
"in",
"memory",
".",
"Returns",
"an",
"array",
"of",
"byte",
"values"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L615-L621 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.read_memory_block32 | def read_memory_block32(self, addr, size):
"""
read a block of aligned words in memory. Returns
an array of word values
"""
data = self.ap.read_memory_block32(addr, size)
return self.bp_manager.filter_memory_aligned_32(addr, size, data) | python | def read_memory_block32(self, addr, size):
"""
read a block of aligned words in memory. Returns
an array of word values
"""
data = self.ap.read_memory_block32(addr, size)
return self.bp_manager.filter_memory_aligned_32(addr, size, data) | [
"def",
"read_memory_block32",
"(",
"self",
",",
"addr",
",",
"size",
")",
":",
"data",
"=",
"self",
".",
"ap",
".",
"read_memory_block32",
"(",
"addr",
",",
"size",
")",
"return",
"self",
".",
"bp_manager",
".",
"filter_memory_aligned_32",
"(",
"addr",
","... | read a block of aligned words in memory. Returns
an array of word values | [
"read",
"a",
"block",
"of",
"aligned",
"words",
"in",
"memory",
".",
"Returns",
"an",
"array",
"of",
"word",
"values"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L635-L641 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.halt | def halt(self):
"""
halt the core
"""
self.notify(Notification(event=Target.EVENT_PRE_HALT, source=self, data=Target.HALT_REASON_USER))
self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT)
self.flush()
self.notify(Notification(even... | python | def halt(self):
"""
halt the core
"""
self.notify(Notification(event=Target.EVENT_PRE_HALT, source=self, data=Target.HALT_REASON_USER))
self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT)
self.flush()
self.notify(Notification(even... | [
"def",
"halt",
"(",
"self",
")",
":",
"self",
".",
"notify",
"(",
"Notification",
"(",
"event",
"=",
"Target",
".",
"EVENT_PRE_HALT",
",",
"source",
"=",
"self",
",",
"data",
"=",
"Target",
".",
"HALT_REASON_USER",
")",
")",
"self",
".",
"write_memory",
... | halt the core | [
"halt",
"the",
"core"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L643-L650 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.step | def step(self, disable_interrupts=True, start=0, end=0):
"""
perform an instruction level step. This function preserves the previous
interrupt mask state
"""
# Was 'if self.get_state() != TARGET_HALTED:'
# but now value of dhcsr is saved
dhcsr = self.read_memory(... | python | def step(self, disable_interrupts=True, start=0, end=0):
"""
perform an instruction level step. This function preserves the previous
interrupt mask state
"""
# Was 'if self.get_state() != TARGET_HALTED:'
# but now value of dhcsr is saved
dhcsr = self.read_memory(... | [
"def",
"step",
"(",
"self",
",",
"disable_interrupts",
"=",
"True",
",",
"start",
"=",
"0",
",",
"end",
"=",
"0",
")",
":",
"# Was 'if self.get_state() != TARGET_HALTED:'",
"# but now value of dhcsr is saved",
"dhcsr",
"=",
"self",
".",
"read_memory",
"(",
"Cortex... | perform an instruction level step. This function preserves the previous
interrupt mask state | [
"perform",
"an",
"instruction",
"level",
"step",
".",
"This",
"function",
"preserves",
"the",
"previous",
"interrupt",
"mask",
"state"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L652-L708 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.reset_and_halt | def reset_and_halt(self, reset_type=None):
"""
perform a reset and stop the core on the reset handler
"""
delegateResult = self.call_delegate('set_reset_catch', core=self, reset_type=reset_type)
# halt the target
if not delegateResult:
self.h... | python | def reset_and_halt(self, reset_type=None):
"""
perform a reset and stop the core on the reset handler
"""
delegateResult = self.call_delegate('set_reset_catch', core=self, reset_type=reset_type)
# halt the target
if not delegateResult:
self.h... | [
"def",
"reset_and_halt",
"(",
"self",
",",
"reset_type",
"=",
"None",
")",
":",
"delegateResult",
"=",
"self",
".",
"call_delegate",
"(",
"'set_reset_catch'",
",",
"core",
"=",
"self",
",",
"reset_type",
"=",
"reset_type",
")",
"# halt the target",
"if",
"not"... | perform a reset and stop the core on the reset handler | [
"perform",
"a",
"reset",
"and",
"stop",
"the",
"core",
"on",
"the",
"reset",
"handler"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L889-L925 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.resume | def resume(self):
"""
resume the execution
"""
if self.get_state() != Target.TARGET_HALTED:
logging.debug('cannot resume: target not halted')
return
self.notify(Notification(event=Target.EVENT_PRE_RUN, source=self, data=Target.RUN_TYPE_RESUME))
sel... | python | def resume(self):
"""
resume the execution
"""
if self.get_state() != Target.TARGET_HALTED:
logging.debug('cannot resume: target not halted')
return
self.notify(Notification(event=Target.EVENT_PRE_RUN, source=self, data=Target.RUN_TYPE_RESUME))
sel... | [
"def",
"resume",
"(",
"self",
")",
":",
"if",
"self",
".",
"get_state",
"(",
")",
"!=",
"Target",
".",
"TARGET_HALTED",
":",
"logging",
".",
"debug",
"(",
"'cannot resume: target not halted'",
")",
"return",
"self",
".",
"notify",
"(",
"Notification",
"(",
... | resume the execution | [
"resume",
"the",
"execution"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L956-L968 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.read_core_registers_raw | def read_core_registers_raw(self, reg_list):
"""
Read one or more core registers
Read core registers in reg_list and return a list of values.
If any register in reg_list is a string, find the number
associated to this register in the lookup table CORE_REGISTER.
"""
... | python | def read_core_registers_raw(self, reg_list):
"""
Read one or more core registers
Read core registers in reg_list and return a list of values.
If any register in reg_list is a string, find the number
associated to this register in the lookup table CORE_REGISTER.
"""
... | [
"def",
"read_core_registers_raw",
"(",
"self",
",",
"reg_list",
")",
":",
"# convert to index only",
"reg_list",
"=",
"[",
"register_name_to_index",
"(",
"reg",
")",
"for",
"reg",
"in",
"reg_list",
"]",
"# Sanity check register values",
"for",
"reg",
"in",
"reg_list... | Read one or more core registers
Read core registers in reg_list and return a list of values.
If any register in reg_list is a string, find the number
associated to this register in the lookup table CORE_REGISTER. | [
"Read",
"one",
"or",
"more",
"core",
"registers"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L996-L1081 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.write_core_registers_raw | def write_core_registers_raw(self, reg_list, data_list):
"""
Write one or more core registers
Write core registers in reg_list with the associated value in
data_list. If any register in reg_list is a string, find the number
associated to this register in the lookup table CORE_R... | python | def write_core_registers_raw(self, reg_list, data_list):
"""
Write one or more core registers
Write core registers in reg_list with the associated value in
data_list. If any register in reg_list is a string, find the number
associated to this register in the lookup table CORE_R... | [
"def",
"write_core_registers_raw",
"(",
"self",
",",
"reg_list",
",",
"data_list",
")",
":",
"assert",
"len",
"(",
"reg_list",
")",
"==",
"len",
"(",
"data_list",
")",
"# convert to index only",
"reg_list",
"=",
"[",
"register_name_to_index",
"(",
"reg",
")",
... | Write one or more core registers
Write core registers in reg_list with the associated value in
data_list. If any register in reg_list is a string, find the number
associated to this register in the lookup table CORE_REGISTER. | [
"Write",
"one",
"or",
"more",
"core",
"registers"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L1104-L1176 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.set_watchpoint | def set_watchpoint(self, addr, size, type):
"""
set a hardware watchpoint
"""
return self.dwt.set_watchpoint(addr, size, type) | python | def set_watchpoint(self, addr, size, type):
"""
set a hardware watchpoint
"""
return self.dwt.set_watchpoint(addr, size, type) | [
"def",
"set_watchpoint",
"(",
"self",
",",
"addr",
",",
"size",
",",
"type",
")",
":",
"return",
"self",
".",
"dwt",
".",
"set_watchpoint",
"(",
"addr",
",",
"size",
",",
"type",
")"
] | set a hardware watchpoint | [
"set",
"a",
"hardware",
"watchpoint"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L1199-L1203 | train |
mbedmicro/pyOCD | pyocd/coresight/cortex_m.py | CortexM.remove_watchpoint | def remove_watchpoint(self, addr, size, type):
"""
remove a hardware watchpoint
"""
return self.dwt.remove_watchpoint(addr, size, type) | python | def remove_watchpoint(self, addr, size, type):
"""
remove a hardware watchpoint
"""
return self.dwt.remove_watchpoint(addr, size, type) | [
"def",
"remove_watchpoint",
"(",
"self",
",",
"addr",
",",
"size",
",",
"type",
")",
":",
"return",
"self",
".",
"dwt",
".",
"remove_watchpoint",
"(",
"addr",
",",
"size",
",",
"type",
")"
] | remove a hardware watchpoint | [
"remove",
"a",
"hardware",
"watchpoint"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L1205-L1209 | train |
mbedmicro/pyOCD | pyocd/target/builtin/target_CC3220SF.py | Flash_cc3220sf.init | def init(self):
"""
Download the flash algorithm in RAM
"""
self.target.halt()
self.target.reset_and_halt()
# update core register to execute the init subroutine
result = self._call_function_and_wait(self.flash_algo['pc_init'], init=True)
# check the r... | python | def init(self):
"""
Download the flash algorithm in RAM
"""
self.target.halt()
self.target.reset_and_halt()
# update core register to execute the init subroutine
result = self._call_function_and_wait(self.flash_algo['pc_init'], init=True)
# check the r... | [
"def",
"init",
"(",
"self",
")",
":",
"self",
".",
"target",
".",
"halt",
"(",
")",
"self",
".",
"target",
".",
"reset_and_halt",
"(",
")",
"# update core register to execute the init subroutine",
"result",
"=",
"self",
".",
"_call_function_and_wait",
"(",
"self... | Download the flash algorithm in RAM | [
"Download",
"the",
"flash",
"algorithm",
"in",
"RAM"
] | 41a174718a9739f3cbe785c2ba21cb7fd1310c6f | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/target/builtin/target_CC3220SF.py#L75-L111 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.