repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
eventbrite/rebar | src/rebar/group.py | StateValidatorFormGroup.is_valid | def is_valid(self, *states):
"""Returns True if no errors are thrown for the specified state."""
# if no state is specified, fallback to the base FormGroup's is_valid
if not states:
return super(StateValidatorFormGroup, self).is_valid()
# see if the states pass for all form... | python | def is_valid(self, *states):
"""Returns True if no errors are thrown for the specified state."""
# if no state is specified, fallback to the base FormGroup's is_valid
if not states:
return super(StateValidatorFormGroup, self).is_valid()
# see if the states pass for all form... | [
"def",
"is_valid",
"(",
"self",
",",
"*",
"states",
")",
":",
"# if no state is specified, fallback to the base FormGroup's is_valid",
"if",
"not",
"states",
":",
"return",
"super",
"(",
"StateValidatorFormGroup",
",",
"self",
")",
".",
"is_valid",
"(",
")",
"# see ... | Returns True if no errors are thrown for the specified state. | [
"Returns",
"True",
"if",
"no",
"errors",
"are",
"thrown",
"for",
"the",
"specified",
"state",
"."
] | 32f8914a2c5529519009d21c85f0d47cc6601901 | https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/group.py#L259-L271 | train | Returns True if all the validators for the specified states pass. |
brunato/lograptor | lograptor/report.py | ReportData.make_text | def make_text(self, width):
"""
Make the text representation of a report data element.
"""
def mformat(reslist):
_text = ""
_buffer = reslist[0]
for j in range(1, len(reslist)):
if (_buffer == "") or (len(_buffer) + len(reslist[j])) <= ... | python | def make_text(self, width):
"""
Make the text representation of a report data element.
"""
def mformat(reslist):
_text = ""
_buffer = reslist[0]
for j in range(1, len(reslist)):
if (_buffer == "") or (len(_buffer) + len(reslist[j])) <= ... | [
"def",
"make_text",
"(",
"self",
",",
"width",
")",
":",
"def",
"mformat",
"(",
"reslist",
")",
":",
"_text",
"=",
"\"\"",
"_buffer",
"=",
"reslist",
"[",
"0",
"]",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"reslist",
")",
")",
":",
... | Make the text representation of a report data element. | [
"Make",
"the",
"text",
"representation",
"of",
"a",
"report",
"data",
"element",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L209-L277 | train | Make the text representation of a report data element. |
brunato/lograptor | lograptor/report.py | ReportData.make_html | def make_html(self):
"""
Make the text representation of a report element as html.
"""
html = None
if self.function == 'total':
html = u'<table border="0" width="100%" rules="cols" cellpadding="2">\n'\
'<tr><th colspan="2" align="left"><h3><font col... | python | def make_html(self):
"""
Make the text representation of a report element as html.
"""
html = None
if self.function == 'total':
html = u'<table border="0" width="100%" rules="cols" cellpadding="2">\n'\
'<tr><th colspan="2" align="left"><h3><font col... | [
"def",
"make_html",
"(",
"self",
")",
":",
"html",
"=",
"None",
"if",
"self",
".",
"function",
"==",
"'total'",
":",
"html",
"=",
"u'<table border=\"0\" width=\"100%\" rules=\"cols\" cellpadding=\"2\">\\n'",
"'<tr><th colspan=\"2\" align=\"left\"><h3><font color=\"{1}\">'",
"... | Make the text representation of a report element as html. | [
"Make",
"the",
"text",
"representation",
"of",
"a",
"report",
"element",
"as",
"html",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L279-L358 | train | Make the text representation of a report element as html. |
brunato/lograptor | lograptor/report.py | ReportData.make_csv | def make_csv(self):
"""
Get the text representation of a report element as csv.
"""
import csv
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import StringIO
out = StringIO()
writer = csv.writer(out, d... | python | def make_csv(self):
"""
Get the text representation of a report element as csv.
"""
import csv
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import StringIO
out = StringIO()
writer = csv.writer(out, d... | [
"def",
"make_csv",
"(",
"self",
")",
":",
"import",
"csv",
"try",
":",
"from",
"StringIO",
"import",
"StringIO",
"# Python 2.7",
"except",
"ImportError",
":",
"from",
"io",
"import",
"StringIO",
"out",
"=",
"StringIO",
"(",
")",
"writer",
"=",
"csv",
".",
... | Get the text representation of a report element as csv. | [
"Get",
"the",
"text",
"representation",
"of",
"a",
"report",
"element",
"as",
"csv",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L360-L397 | train | Make the text representation of a report element as csv. |
brunato/lograptor | lograptor/report.py | Subreport.make | def make(self, apps):
"""
Make subreport items from results.
"""
for (appname, app) in sorted(apps.items(), key=lambda x: (x[1].priority, x[0])):
logger.info('Getting report results from %r', appname)
for report_data in app.report_data:
if report_... | python | def make(self, apps):
"""
Make subreport items from results.
"""
for (appname, app) in sorted(apps.items(), key=lambda x: (x[1].priority, x[0])):
logger.info('Getting report results from %r', appname)
for report_data in app.report_data:
if report_... | [
"def",
"make",
"(",
"self",
",",
"apps",
")",
":",
"for",
"(",
"appname",
",",
"app",
")",
"in",
"sorted",
"(",
"apps",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
"[",
"1",
"]",
".",
"priority",
",",
"x",
"[",
"0... | Make subreport items from results. | [
"Make",
"subreport",
"items",
"from",
"results",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L420-L493 | train | Make subreport items from results. |
brunato/lograptor | lograptor/report.py | Subreport.make_format | def make_format(self, fmt, width):
"""
Make subreport text in a specified format
"""
if not self.report_data:
return
for data_item in self.report_data:
if data_item.results:
if fmt is None or fmt == 'text':
... | python | def make_format(self, fmt, width):
"""
Make subreport text in a specified format
"""
if not self.report_data:
return
for data_item in self.report_data:
if data_item.results:
if fmt is None or fmt == 'text':
... | [
"def",
"make_format",
"(",
"self",
",",
"fmt",
",",
"width",
")",
":",
"if",
"not",
"self",
".",
"report_data",
":",
"return",
"for",
"data_item",
"in",
"self",
".",
"report_data",
":",
"if",
"data_item",
".",
"results",
":",
"if",
"fmt",
"is",
"None",... | Make subreport text in a specified format | [
"Make",
"subreport",
"text",
"in",
"a",
"specified",
"format"
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L495-L509 | train | Make subreport text in a specified format |
brunato/lograptor | lograptor/report.py | Subreport.compact_tables | def compact_tables(self):
"""
Compact report items of type "table" with same results type. Report items of type "tables" in the
same subreport is merged into one. The data are ordered by 1st column.
"""
items_to_del = set()
for i in range(len(self.report_data)):
... | python | def compact_tables(self):
"""
Compact report items of type "table" with same results type. Report items of type "tables" in the
same subreport is merged into one. The data are ordered by 1st column.
"""
items_to_del = set()
for i in range(len(self.report_data)):
... | [
"def",
"compact_tables",
"(",
"self",
")",
":",
"items_to_del",
"=",
"set",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"report_data",
")",
")",
":",
"if",
"i",
"in",
"items_to_del",
":",
"continue",
"if",
"self",
".",
"report_... | Compact report items of type "table" with same results type. Report items of type "tables" in the
same subreport is merged into one. The data are ordered by 1st column. | [
"Compact",
"report",
"items",
"of",
"type",
"table",
"with",
"same",
"results",
"type",
".",
"Report",
"items",
"of",
"type",
"tables",
"in",
"the",
"same",
"subreport",
"is",
"merged",
"into",
"one",
".",
"The",
"data",
"are",
"ordered",
"by",
"1st",
"c... | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L511-L530 | train | Compact report items of type table with same results type. |
brunato/lograptor | lograptor/report.py | Report.make | def make(self, apps):
"""
Create the report from application results
"""
for subreport in self.subreports:
logger.debug('Make subreport "{0}"'.format(subreport.name))
subreport.make(apps)
for subreport in self.subreports:
subreport.compact_tab... | python | def make(self, apps):
"""
Create the report from application results
"""
for subreport in self.subreports:
logger.debug('Make subreport "{0}"'.format(subreport.name))
subreport.make(apps)
for subreport in self.subreports:
subreport.compact_tab... | [
"def",
"make",
"(",
"self",
",",
"apps",
")",
":",
"for",
"subreport",
"in",
"self",
".",
"subreports",
":",
"logger",
".",
"debug",
"(",
"'Make subreport \"{0}\"'",
".",
"format",
"(",
"subreport",
".",
"name",
")",
")",
"subreport",
".",
"make",
"(",
... | Create the report from application results | [
"Create",
"the",
"report",
"from",
"application",
"results"
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L566-L575 | train | Create the report from application results |
brunato/lograptor | lograptor/report.py | Report.get_report_parts | def get_report_parts(self, apps, formats):
"""
Make report item texts in a specified format.
"""
for fmt in formats:
width = 100 if fmt is not None else tui.get_terminal_size()[0]
for sr in self.subreports:
sr.make_format(fmt, width)
logge... | python | def get_report_parts(self, apps, formats):
"""
Make report item texts in a specified format.
"""
for fmt in formats:
width = 100 if fmt is not None else tui.get_terminal_size()[0]
for sr in self.subreports:
sr.make_format(fmt, width)
logge... | [
"def",
"get_report_parts",
"(",
"self",
",",
"apps",
",",
"formats",
")",
":",
"for",
"fmt",
"in",
"formats",
":",
"width",
"=",
"100",
"if",
"fmt",
"is",
"not",
"None",
"else",
"tui",
".",
"get_terminal_size",
"(",
")",
"[",
"0",
"]",
"for",
"sr",
... | Make report item texts in a specified format. | [
"Make",
"report",
"item",
"texts",
"in",
"a",
"specified",
"format",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L580-L622 | train | Make report items in a specified format. |
brunato/lograptor | lograptor/report.py | Report.set_stats | def set_stats(self, run_stats):
"""
Set run statistics for the report.
"""
self.stats = run_stats.copy()
self.stats['files'] = ', '.join(self.stats['files'])
self.stats['tot_files'] = len(run_stats['files'])
self.stats['extra_tags'] = ', '.join(self.stats['extra_t... | python | def set_stats(self, run_stats):
"""
Set run statistics for the report.
"""
self.stats = run_stats.copy()
self.stats['files'] = ', '.join(self.stats['files'])
self.stats['tot_files'] = len(run_stats['files'])
self.stats['extra_tags'] = ', '.join(self.stats['extra_t... | [
"def",
"set_stats",
"(",
"self",
",",
"run_stats",
")",
":",
"self",
".",
"stats",
"=",
"run_stats",
".",
"copy",
"(",
")",
"self",
".",
"stats",
"[",
"'files'",
"]",
"=",
"', '",
".",
"join",
"(",
"self",
".",
"stats",
"[",
"'files'",
"]",
")",
... | Set run statistics for the report. | [
"Set",
"run",
"statistics",
"for",
"the",
"report",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L630-L637 | train | Set run statistics for the report. |
brunato/lograptor | lograptor/report.py | Report.make_html_page | def make_html_page(self, valumap):
"""
Builds the report as html page, using the template page from file.
"""
logger.info('Making an html report using template %r.', self.html_template)
fh = open(self.html_template)
template = fh.read()
fh.close()
parts =... | python | def make_html_page(self, valumap):
"""
Builds the report as html page, using the template page from file.
"""
logger.info('Making an html report using template %r.', self.html_template)
fh = open(self.html_template)
template = fh.read()
fh.close()
parts =... | [
"def",
"make_html_page",
"(",
"self",
",",
"valumap",
")",
":",
"logger",
".",
"info",
"(",
"'Making an html report using template %r.'",
",",
"self",
".",
"html_template",
")",
"fh",
"=",
"open",
"(",
"self",
".",
"html_template",
")",
"template",
"=",
"fh",
... | Builds the report as html page, using the template page from file. | [
"Builds",
"the",
"report",
"as",
"html",
"page",
"using",
"the",
"template",
"page",
"from",
"file",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L639-L658 | train | Builds the report as html page using the template page from file. |
brunato/lograptor | lograptor/report.py | Report.make_text_page | def make_text_page(self, valumap):
"""
Builds the report as text page, using the template page from file.
"""
logger.info('Making a text report page using template %r.', self.text_template)
fh = open(self.text_template)
template = fh.read()
fh.close()
... | python | def make_text_page(self, valumap):
"""
Builds the report as text page, using the template page from file.
"""
logger.info('Making a text report page using template %r.', self.text_template)
fh = open(self.text_template)
template = fh.read()
fh.close()
... | [
"def",
"make_text_page",
"(",
"self",
",",
"valumap",
")",
":",
"logger",
".",
"info",
"(",
"'Making a text report page using template %r.'",
",",
"self",
".",
"text_template",
")",
"fh",
"=",
"open",
"(",
"self",
".",
"text_template",
")",
"template",
"=",
"f... | Builds the report as text page, using the template page from file. | [
"Builds",
"the",
"report",
"as",
"text",
"page",
"using",
"the",
"template",
"page",
"from",
"file",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L660-L678 | train | Builds a text report page from the template file. |
brunato/lograptor | lograptor/report.py | Report.make_csv_tables | def make_csv_tables(self):
"""
Builds the report as a list of csv tables with titles.
"""
logger.info('Generate csv report tables')
report_parts = []
for sr in self.subreports:
for data_item in sr.report_data:
report_parts.append(TextPart(fmt='... | python | def make_csv_tables(self):
"""
Builds the report as a list of csv tables with titles.
"""
logger.info('Generate csv report tables')
report_parts = []
for sr in self.subreports:
for data_item in sr.report_data:
report_parts.append(TextPart(fmt='... | [
"def",
"make_csv_tables",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Generate csv report tables'",
")",
"report_parts",
"=",
"[",
"]",
"for",
"sr",
"in",
"self",
".",
"subreports",
":",
"for",
"data_item",
"in",
"sr",
".",
"report_data",
":",
"re... | Builds the report as a list of csv tables with titles. | [
"Builds",
"the",
"report",
"as",
"a",
"list",
"of",
"csv",
"tables",
"with",
"titles",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L680-L689 | train | Builds the report as a list of csv tables with titles. |
projectshift/shift-boiler | boiler/collections/paginated_collection.py | PaginatedCollection.fetch_items | def fetch_items(self):
"""
Fetch items
Performs a query to retrieve items based on current query and
pagination settings.
"""
offset = self.per_page * (self.page - 1)
items = self._query.limit(self.per_page).offset(offset).all()
return items | python | def fetch_items(self):
"""
Fetch items
Performs a query to retrieve items based on current query and
pagination settings.
"""
offset = self.per_page * (self.page - 1)
items = self._query.limit(self.per_page).offset(offset).all()
return items | [
"def",
"fetch_items",
"(",
"self",
")",
":",
"offset",
"=",
"self",
".",
"per_page",
"*",
"(",
"self",
".",
"page",
"-",
"1",
")",
"items",
"=",
"self",
".",
"_query",
".",
"limit",
"(",
"self",
".",
"per_page",
")",
".",
"offset",
"(",
"offset",
... | Fetch items
Performs a query to retrieve items based on current query and
pagination settings. | [
"Fetch",
"items",
"Performs",
"a",
"query",
"to",
"retrieve",
"items",
"based",
"on",
"current",
"query",
"and",
"pagination",
"settings",
"."
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/collections/paginated_collection.py#L66-L74 | train | Fetch items based on current query and pagination settings. |
projectshift/shift-boiler | boiler/collections/paginated_collection.py | PaginatedCollection.dict | def dict(self):
""" Returns current collection as a dictionary """
collection = dict(
page=self.page,
per_page=self.per_page,
total_items=self.total_items,
total_pages=self.total_pages,
pagination=self.pagination,
items=list(self.it... | python | def dict(self):
""" Returns current collection as a dictionary """
collection = dict(
page=self.page,
per_page=self.per_page,
total_items=self.total_items,
total_pages=self.total_pages,
pagination=self.pagination,
items=list(self.it... | [
"def",
"dict",
"(",
"self",
")",
":",
"collection",
"=",
"dict",
"(",
"page",
"=",
"self",
".",
"page",
",",
"per_page",
"=",
"self",
".",
"per_page",
",",
"total_items",
"=",
"self",
".",
"total_items",
",",
"total_pages",
"=",
"self",
".",
"total_pag... | Returns current collection as a dictionary | [
"Returns",
"current",
"collection",
"as",
"a",
"dictionary"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/collections/paginated_collection.py#L76-L86 | train | Returns current collection as a dictionary |
projectshift/shift-boiler | boiler/collections/paginated_collection.py | PaginatedCollection.next_page | def next_page(self):
"""
Next page
Uses query object to fetch next slice of items unless on last page in
which case does nothing
"""
if self.is_last_page():
return False
self.page += 1
self.items = self.fetch_items()
return True | python | def next_page(self):
"""
Next page
Uses query object to fetch next slice of items unless on last page in
which case does nothing
"""
if self.is_last_page():
return False
self.page += 1
self.items = self.fetch_items()
return True | [
"def",
"next_page",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_last_page",
"(",
")",
":",
"return",
"False",
"self",
".",
"page",
"+=",
"1",
"self",
".",
"items",
"=",
"self",
".",
"fetch_items",
"(",
")",
"return",
"True"
] | Next page
Uses query object to fetch next slice of items unless on last page in
which case does nothing | [
"Next",
"page",
"Uses",
"query",
"object",
"to",
"fetch",
"next",
"slice",
"of",
"items",
"unless",
"on",
"last",
"page",
"in",
"which",
"case",
"does",
"nothing"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/collections/paginated_collection.py#L96-L107 | train | Returns True if there are items on the next page False otherwise |
projectshift/shift-boiler | boiler/collections/paginated_collection.py | PaginatedCollection.previous_page | def previous_page(self):
"""
Previous page
Uses query object to fetch previous slice of items unless on first
page in which case does nothing
"""
if self.is_first_page():
return False
self.page -= 1
self.items = self.fetch_items()
retu... | python | def previous_page(self):
"""
Previous page
Uses query object to fetch previous slice of items unless on first
page in which case does nothing
"""
if self.is_first_page():
return False
self.page -= 1
self.items = self.fetch_items()
retu... | [
"def",
"previous_page",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_first_page",
"(",
")",
":",
"return",
"False",
"self",
".",
"page",
"-=",
"1",
"self",
".",
"items",
"=",
"self",
".",
"fetch_items",
"(",
")",
"return",
"True"
] | Previous page
Uses query object to fetch previous slice of items unless on first
page in which case does nothing | [
"Previous",
"page",
"Uses",
"query",
"object",
"to",
"fetch",
"previous",
"slice",
"of",
"items",
"unless",
"on",
"first",
"page",
"in",
"which",
"case",
"does",
"nothing"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/collections/paginated_collection.py#L109-L120 | train | Returns True if this is the first page False otherwise |
brunato/lograptor | setup.py | my_bdist_rpm._make_spec_file | def _make_spec_file(self):
"""
Customize spec file inserting %config section
"""
spec_file = setuptools.command.bdist_rpm.bdist_rpm._make_spec_file(self)
spec_file.append('%config(noreplace) /etc/lograptor/lograptor.conf')
spec_file.append('%config(noreplace) /etc/lograpt... | python | def _make_spec_file(self):
"""
Customize spec file inserting %config section
"""
spec_file = setuptools.command.bdist_rpm.bdist_rpm._make_spec_file(self)
spec_file.append('%config(noreplace) /etc/lograptor/lograptor.conf')
spec_file.append('%config(noreplace) /etc/lograpt... | [
"def",
"_make_spec_file",
"(",
"self",
")",
":",
"spec_file",
"=",
"setuptools",
".",
"command",
".",
"bdist_rpm",
".",
"bdist_rpm",
".",
"_make_spec_file",
"(",
"self",
")",
"spec_file",
".",
"append",
"(",
"'%config(noreplace) /etc/lograptor/lograptor.conf'",
")",... | Customize spec file inserting %config section | [
"Customize",
"spec",
"file",
"inserting",
"%config",
"section"
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/setup.py#L125-L133 | train | Customize spec file inserting %config section |
projectshift/shift-boiler | boiler/user/event_handlers.py | user_save_event | def user_save_event(user):
""" Handle persist event for user entities """
msg = 'User ({}){} updated/saved'.format(user.id, user.email)
current_app.logger.info(msg) | python | def user_save_event(user):
""" Handle persist event for user entities """
msg = 'User ({}){} updated/saved'.format(user.id, user.email)
current_app.logger.info(msg) | [
"def",
"user_save_event",
"(",
"user",
")",
":",
"msg",
"=",
"'User ({}){} updated/saved'",
".",
"format",
"(",
"user",
".",
"id",
",",
"user",
".",
"email",
")",
"current_app",
".",
"logger",
".",
"info",
"(",
"msg",
")"
] | Handle persist event for user entities | [
"Handle",
"persist",
"event",
"for",
"user",
"entities"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/event_handlers.py#L14-L17 | train | Log user update event for user entities |
projectshift/shift-boiler | boiler/user/event_handlers.py | user_got_role_event | def user_got_role_event(user, role):
""" User got new role """
msg = 'User ({}){} got new role [{}]'
current_app.logger.info(msg.format(user.id, user.email, role.handle)) | python | def user_got_role_event(user, role):
""" User got new role """
msg = 'User ({}){} got new role [{}]'
current_app.logger.info(msg.format(user.id, user.email, role.handle)) | [
"def",
"user_got_role_event",
"(",
"user",
",",
"role",
")",
":",
"msg",
"=",
"'User ({}){} got new role [{}]'",
"current_app",
".",
"logger",
".",
"info",
"(",
"msg",
".",
"format",
"(",
"user",
".",
"id",
",",
"user",
".",
"email",
",",
"role",
".",
"h... | User got new role | [
"User",
"got",
"new",
"role"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/event_handlers.py#L107-L110 | train | Log user got new role |
projectshift/shift-boiler | boiler/user/models.py | User.generate_hash | def generate_hash(self, length=30):
""" Generate random string of given length """
import random, string
chars = string.ascii_letters + string.digits
ran = random.SystemRandom().choice
hash = ''.join(ran(chars) for i in range(length))
return hash | python | def generate_hash(self, length=30):
""" Generate random string of given length """
import random, string
chars = string.ascii_letters + string.digits
ran = random.SystemRandom().choice
hash = ''.join(ran(chars) for i in range(length))
return hash | [
"def",
"generate_hash",
"(",
"self",
",",
"length",
"=",
"30",
")",
":",
"import",
"random",
",",
"string",
"chars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"ran",
"=",
"random",
".",
"SystemRandom",
"(",
")",
".",
"choice",
... | Generate random string of given length | [
"Generate",
"random",
"string",
"of",
"given",
"length"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L163-L169 | train | Generate random string of given length |
projectshift/shift-boiler | boiler/user/models.py | User.gravatar | def gravatar(self, size):
""" Get url to gravatar """
hash = md5(self.email.encode('utf-8')).hexdigest()
url = 'http://www.gravatar.com/avatar/{}?d=mm&s={}'
return url.format(hash, size) | python | def gravatar(self, size):
""" Get url to gravatar """
hash = md5(self.email.encode('utf-8')).hexdigest()
url = 'http://www.gravatar.com/avatar/{}?d=mm&s={}'
return url.format(hash, size) | [
"def",
"gravatar",
"(",
"self",
",",
"size",
")",
":",
"hash",
"=",
"md5",
"(",
"self",
".",
"email",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"url",
"=",
"'http://www.gravatar.com/avatar/{}?d=mm&s={}'",
"return",
"url",
".",
... | Get url to gravatar | [
"Get",
"url",
"to",
"gravatar"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L171-L175 | train | Get url to gravatar |
projectshift/shift-boiler | boiler/user/models.py | User.is_locked | def is_locked(self):
"""
Is locked?
Checks locking and possibly unlocks upon timeout if account was
previously locked.
"""
now = datetime.datetime.utcnow()
if self.locked_until and self.locked_until >= now:
return True
elif self.locked_until an... | python | def is_locked(self):
"""
Is locked?
Checks locking and possibly unlocks upon timeout if account was
previously locked.
"""
now = datetime.datetime.utcnow()
if self.locked_until and self.locked_until >= now:
return True
elif self.locked_until an... | [
"def",
"is_locked",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"self",
".",
"locked_until",
"and",
"self",
".",
"locked_until",
">=",
"now",
":",
"return",
"True",
"elif",
"self",
".",
"locked_until",
... | Is locked?
Checks locking and possibly unlocks upon timeout if account was
previously locked. | [
"Is",
"locked?",
"Checks",
"locking",
"and",
"possibly",
"unlocks",
"upon",
"timeout",
"if",
"account",
"was",
"previously",
"locked",
"."
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L200-L213 | train | Checks if the current account is locked and unlocks upon timeout. |
projectshift/shift-boiler | boiler/user/models.py | User.lock_account | def lock_account(self, minutes=30):
""" Lock user account for a period """
period = datetime.timedelta(minutes=minutes)
self.locked_until = datetime.datetime.utcnow() + period | python | def lock_account(self, minutes=30):
""" Lock user account for a period """
period = datetime.timedelta(minutes=minutes)
self.locked_until = datetime.datetime.utcnow() + period | [
"def",
"lock_account",
"(",
"self",
",",
"minutes",
"=",
"30",
")",
":",
"period",
"=",
"datetime",
".",
"timedelta",
"(",
"minutes",
"=",
"minutes",
")",
"self",
".",
"locked_until",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"per... | Lock user account for a period | [
"Lock",
"user",
"account",
"for",
"a",
"period"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L215-L218 | train | Lock user account for a period |
projectshift/shift-boiler | boiler/user/models.py | User.increment_failed_logins | def increment_failed_logins(self):
""" Increment failed logins counter"""
if not self.failed_logins:
self.failed_logins = 1
elif not self.failed_login_limit_reached():
self.failed_logins += 1
else:
self.reset_login_counter()
self.lock_accou... | python | def increment_failed_logins(self):
""" Increment failed logins counter"""
if not self.failed_logins:
self.failed_logins = 1
elif not self.failed_login_limit_reached():
self.failed_logins += 1
else:
self.reset_login_counter()
self.lock_accou... | [
"def",
"increment_failed_logins",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"failed_logins",
":",
"self",
".",
"failed_logins",
"=",
"1",
"elif",
"not",
"self",
".",
"failed_login_limit_reached",
"(",
")",
":",
"self",
".",
"failed_logins",
"+=",
"1",... | Increment failed logins counter | [
"Increment",
"failed",
"logins",
"counter"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L224-L232 | train | Increment failed logins counter |
projectshift/shift-boiler | boiler/user/models.py | User.failed_login_limit_reached | def failed_login_limit_reached(self):
""" A boolean method to check for failed login limit being reached"""
login_limit = 10
if self.failed_logins and self.failed_logins >= login_limit:
return True
else:
return False | python | def failed_login_limit_reached(self):
""" A boolean method to check for failed login limit being reached"""
login_limit = 10
if self.failed_logins and self.failed_logins >= login_limit:
return True
else:
return False | [
"def",
"failed_login_limit_reached",
"(",
"self",
")",
":",
"login_limit",
"=",
"10",
"if",
"self",
".",
"failed_logins",
"and",
"self",
".",
"failed_logins",
">=",
"login_limit",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | A boolean method to check for failed login limit being reached | [
"A",
"boolean",
"method",
"to",
"check",
"for",
"failed",
"login",
"limit",
"being",
"reached"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L238-L244 | train | A boolean method to check if the failed login limit is reached |
projectshift/shift-boiler | boiler/user/models.py | User.email_secure | def email_secure(self):
""" Obfuscated email used for display """
email = self._email
if not email: return ''
address, host = email.split('@')
if len(address) <= 2: return ('*' * len(address)) + '@' + host
import re
host = '@' + host
obfuscated = re.sub(r... | python | def email_secure(self):
""" Obfuscated email used for display """
email = self._email
if not email: return ''
address, host = email.split('@')
if len(address) <= 2: return ('*' * len(address)) + '@' + host
import re
host = '@' + host
obfuscated = re.sub(r... | [
"def",
"email_secure",
"(",
"self",
")",
":",
"email",
"=",
"self",
".",
"_email",
"if",
"not",
"email",
":",
"return",
"''",
"address",
",",
"host",
"=",
"email",
".",
"split",
"(",
"'@'",
")",
"if",
"len",
"(",
"address",
")",
"<=",
"2",
":",
"... | Obfuscated email used for display | [
"Obfuscated",
"email",
"used",
"for",
"display"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L256-L266 | train | Obfuscated email used for display |
projectshift/shift-boiler | boiler/user/models.py | User.email | def email(self, email):
""" Set email and generate confirmation """
if email == self.email:
return
email = email.lower()
if self._email is None:
self._email = email
self.require_email_confirmation()
else:
self.email_new = email
... | python | def email(self, email):
""" Set email and generate confirmation """
if email == self.email:
return
email = email.lower()
if self._email is None:
self._email = email
self.require_email_confirmation()
else:
self.email_new = email
... | [
"def",
"email",
"(",
"self",
",",
"email",
")",
":",
"if",
"email",
"==",
"self",
".",
"email",
":",
"return",
"email",
"=",
"email",
".",
"lower",
"(",
")",
"if",
"self",
".",
"_email",
"is",
"None",
":",
"self",
".",
"_email",
"=",
"email",
"se... | Set email and generate confirmation | [
"Set",
"email",
"and",
"generate",
"confirmation"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L269-L280 | train | Set email and generate confirmation |
projectshift/shift-boiler | boiler/user/models.py | User.require_email_confirmation | def require_email_confirmation(self):
""" Mark email as unconfirmed"""
self.email_confirmed = False
self.email_link = self.generate_hash(50)
now = datetime.datetime.utcnow()
self.email_link_expires = now + datetime.timedelta(hours=24) | python | def require_email_confirmation(self):
""" Mark email as unconfirmed"""
self.email_confirmed = False
self.email_link = self.generate_hash(50)
now = datetime.datetime.utcnow()
self.email_link_expires = now + datetime.timedelta(hours=24) | [
"def",
"require_email_confirmation",
"(",
"self",
")",
":",
"self",
".",
"email_confirmed",
"=",
"False",
"self",
".",
"email_link",
"=",
"self",
".",
"generate_hash",
"(",
"50",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"self"... | Mark email as unconfirmed | [
"Mark",
"email",
"as",
"unconfirmed"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L282-L287 | train | Mark email as unconfirmed |
projectshift/shift-boiler | boiler/user/models.py | User.confirm_email | def confirm_email(self):
""" Confirm email """
if self._email and self.email_new:
self._email = self.email_new
self.email_confirmed = True
self.email_link = None
self.email_new = None
self.email_link_expires = None | python | def confirm_email(self):
""" Confirm email """
if self._email and self.email_new:
self._email = self.email_new
self.email_confirmed = True
self.email_link = None
self.email_new = None
self.email_link_expires = None | [
"def",
"confirm_email",
"(",
"self",
")",
":",
"if",
"self",
".",
"_email",
"and",
"self",
".",
"email_new",
":",
"self",
".",
"_email",
"=",
"self",
".",
"email_new",
"self",
".",
"email_confirmed",
"=",
"True",
"self",
".",
"email_link",
"=",
"None",
... | Confirm email | [
"Confirm",
"email"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L289-L297 | train | Confirm email |
projectshift/shift-boiler | boiler/user/models.py | User.cancel_email_change | def cancel_email_change(self):
""" Cancel email change for new users and roll back data """
if not self.email_new:
return
self.email_new = None
self.email_confirmed = True
self.email_link = None
self.email_new = None
self.email_link_expires = None | python | def cancel_email_change(self):
""" Cancel email change for new users and roll back data """
if not self.email_new:
return
self.email_new = None
self.email_confirmed = True
self.email_link = None
self.email_new = None
self.email_link_expires = None | [
"def",
"cancel_email_change",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"email_new",
":",
"return",
"self",
".",
"email_new",
"=",
"None",
"self",
".",
"email_confirmed",
"=",
"True",
"self",
".",
"email_link",
"=",
"None",
"self",
".",
"email_new",... | Cancel email change for new users and roll back data | [
"Cancel",
"email",
"change",
"for",
"new",
"users",
"and",
"roll",
"back",
"data"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L299-L308 | train | Cancel email change for new users and roll back data |
projectshift/shift-boiler | boiler/user/models.py | User.email_link_expired | def email_link_expired(self, now=None):
""" Check if email link expired """
if not now: now = datetime.datetime.utcnow()
return self.email_link_expires < now | python | def email_link_expired(self, now=None):
""" Check if email link expired """
if not now: now = datetime.datetime.utcnow()
return self.email_link_expires < now | [
"def",
"email_link_expired",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"if",
"not",
"now",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"self",
".",
"email_link_expires",
"<",
"now"
] | Check if email link expired | [
"Check",
"if",
"email",
"link",
"expired"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L310-L313 | train | Check if email link expired |
projectshift/shift-boiler | boiler/user/models.py | User.password | def password(self, password):
""" Encode a string and set as password """
from boiler.user.util.passlib import passlib_context
password = str(password)
encrypted = passlib_context.encrypt(password)
self._password = encrypted | python | def password(self, password):
""" Encode a string and set as password """
from boiler.user.util.passlib import passlib_context
password = str(password)
encrypted = passlib_context.encrypt(password)
self._password = encrypted | [
"def",
"password",
"(",
"self",
",",
"password",
")",
":",
"from",
"boiler",
".",
"user",
".",
"util",
".",
"passlib",
"import",
"passlib_context",
"password",
"=",
"str",
"(",
"password",
")",
"encrypted",
"=",
"passlib_context",
".",
"encrypt",
"(",
"pas... | Encode a string and set as password | [
"Encode",
"a",
"string",
"and",
"set",
"as",
"password"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L325-L330 | train | Encode a string and set as password |
projectshift/shift-boiler | boiler/user/models.py | User.verify_password | def verify_password(self, password):
""" Verify a given string for being valid password """
if self.password is None:
return False
from boiler.user.util.passlib import passlib_context
return passlib_context.verify(str(password), self.password) | python | def verify_password(self, password):
""" Verify a given string for being valid password """
if self.password is None:
return False
from boiler.user.util.passlib import passlib_context
return passlib_context.verify(str(password), self.password) | [
"def",
"verify_password",
"(",
"self",
",",
"password",
")",
":",
"if",
"self",
".",
"password",
"is",
"None",
":",
"return",
"False",
"from",
"boiler",
".",
"user",
".",
"util",
".",
"passlib",
"import",
"passlib_context",
"return",
"passlib_context",
".",
... | Verify a given string for being valid password | [
"Verify",
"a",
"given",
"string",
"for",
"being",
"valid",
"password"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L332-L338 | train | Verify a given string for being valid password |
projectshift/shift-boiler | boiler/user/models.py | User.generate_password_link | def generate_password_link(self):
""" Generates a link to reset password """
self.password_link = self.generate_hash(50)
now = datetime.datetime.utcnow()
self.password_link_expires = now + datetime.timedelta(hours=24) | python | def generate_password_link(self):
""" Generates a link to reset password """
self.password_link = self.generate_hash(50)
now = datetime.datetime.utcnow()
self.password_link_expires = now + datetime.timedelta(hours=24) | [
"def",
"generate_password_link",
"(",
"self",
")",
":",
"self",
".",
"password_link",
"=",
"self",
".",
"generate_hash",
"(",
"50",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"self",
".",
"password_link_expires",
"=",
"now",
"+"... | Generates a link to reset password | [
"Generates",
"a",
"link",
"to",
"reset",
"password"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L340-L344 | train | Generates a link to reset password |
projectshift/shift-boiler | boiler/user/models.py | User.password_link_expired | def password_link_expired(self, now=None):
""" Check if password link expired """
if not now: now = datetime.datetime.utcnow()
return self.password_link_expires < now | python | def password_link_expired(self, now=None):
""" Check if password link expired """
if not now: now = datetime.datetime.utcnow()
return self.password_link_expires < now | [
"def",
"password_link_expired",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"if",
"not",
"now",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"self",
".",
"password_link_expires",
"<",
"now"
] | Check if password link expired | [
"Check",
"if",
"password",
"link",
"expired"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L346-L349 | train | Check if password link expired |
projectshift/shift-boiler | boiler/user/models.py | User.add_role | def add_role(self, role):
"""
Add role to user
Role must be valid and saved first, otherwise will
raise an exception.
"""
schema = RoleSchema()
ok = schema.process(role)
if not ok or not role.id:
err = 'Role must be valid and saved before addin... | python | def add_role(self, role):
"""
Add role to user
Role must be valid and saved first, otherwise will
raise an exception.
"""
schema = RoleSchema()
ok = schema.process(role)
if not ok or not role.id:
err = 'Role must be valid and saved before addin... | [
"def",
"add_role",
"(",
"self",
",",
"role",
")",
":",
"schema",
"=",
"RoleSchema",
"(",
")",
"ok",
"=",
"schema",
".",
"process",
"(",
"role",
")",
"if",
"not",
"ok",
"or",
"not",
"role",
".",
"id",
":",
"err",
"=",
"'Role must be valid and saved befo... | Add role to user
Role must be valid and saved first, otherwise will
raise an exception. | [
"Add",
"role",
"to",
"user",
"Role",
"must",
"be",
"valid",
"and",
"saved",
"first",
"otherwise",
"will",
"raise",
"an",
"exception",
"."
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L363-L375 | train | Add a role to the user s list of roles. |
projectshift/shift-boiler | boiler/user/models.py | User.remove_role | def remove_role(self, role):
""" Remove role from user """
if role in self.__roles:
self.__roles.remove(role) | python | def remove_role(self, role):
""" Remove role from user """
if role in self.__roles:
self.__roles.remove(role) | [
"def",
"remove_role",
"(",
"self",
",",
"role",
")",
":",
"if",
"role",
"in",
"self",
".",
"__roles",
":",
"self",
".",
"__roles",
".",
"remove",
"(",
"role",
")"
] | Remove role from user | [
"Remove",
"role",
"from",
"user"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L377-L380 | train | Remove a role from the user |
projectshift/shift-boiler | boiler/user/models.py | User.has_role | def has_role(self, role_or_handle):
""" Checks if user has role """
if not isinstance(role_or_handle, str):
return role_or_handle in self.roles
has_role = False
for role in self.roles:
if role.handle == role_or_handle:
has_role = True
... | python | def has_role(self, role_or_handle):
""" Checks if user has role """
if not isinstance(role_or_handle, str):
return role_or_handle in self.roles
has_role = False
for role in self.roles:
if role.handle == role_or_handle:
has_role = True
... | [
"def",
"has_role",
"(",
"self",
",",
"role_or_handle",
")",
":",
"if",
"not",
"isinstance",
"(",
"role_or_handle",
",",
"str",
")",
":",
"return",
"role_or_handle",
"in",
"self",
".",
"roles",
"has_role",
"=",
"False",
"for",
"role",
"in",
"self",
".",
"... | Checks if user has role | [
"Checks",
"if",
"user",
"has",
"role"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L382-L393 | train | Checks if user has role |
projectshift/shift-boiler | boiler/user/models.py | User.roles | def roles(self):
""" Roles accessor """
roles = list(self.__roles)
default_role = Role(
handle='user',
title='User role',
description='All registered users get this role by default'
)
roles.append(default_role)
return tuple(roles) | python | def roles(self):
""" Roles accessor """
roles = list(self.__roles)
default_role = Role(
handle='user',
title='User role',
description='All registered users get this role by default'
)
roles.append(default_role)
return tuple(roles) | [
"def",
"roles",
"(",
"self",
")",
":",
"roles",
"=",
"list",
"(",
"self",
".",
"__roles",
")",
"default_role",
"=",
"Role",
"(",
"handle",
"=",
"'user'",
",",
"title",
"=",
"'User role'",
",",
"description",
"=",
"'All registered users get this role by default... | Roles accessor | [
"Roles",
"accessor"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/models.py#L396-L406 | train | Return a tuple of all roles. |
Ceasar/twosheds | twosheds/builtins.py | cd | def cd(*args):
"""
An argument of - is equivalent to $OLDPWD. If - is the first argument, and
the directory change is successful, the absolute pathname of the new
working directory is written to the standard output.
"""
if args[0] == "-":
try:
newpwd, os.environ["OLDPWD"] = o... | python | def cd(*args):
"""
An argument of - is equivalent to $OLDPWD. If - is the first argument, and
the directory change is successful, the absolute pathname of the new
working directory is written to the standard output.
"""
if args[0] == "-":
try:
newpwd, os.environ["OLDPWD"] = o... | [
"def",
"cd",
"(",
"*",
"args",
")",
":",
"if",
"args",
"[",
"0",
"]",
"==",
"\"-\"",
":",
"try",
":",
"newpwd",
",",
"os",
".",
"environ",
"[",
"\"OLDPWD\"",
"]",
"=",
"os",
".",
"environ",
"[",
"\"OLDPWD\"",
"]",
",",
"os",
".",
"getcwd",
"(",... | An argument of - is equivalent to $OLDPWD. If - is the first argument, and
the directory change is successful, the absolute pathname of the new
working directory is written to the standard output. | [
"An",
"argument",
"of",
"-",
"is",
"equivalent",
"to",
"$OLDPWD",
".",
"If",
"-",
"is",
"the",
"first",
"argument",
"and",
"the",
"directory",
"change",
"is",
"successful",
"the",
"absolute",
"pathname",
"of",
"the",
"new",
"working",
"directory",
"is",
"w... | 55b0a207e3a06b85e9a9567069b3822a651501a7 | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/builtins.py#L4-L20 | train | Change the working directory of a new object. |
ronhanson/python-tbx | fabfile/git.py | push | def push(remote='origin', branch='master'):
"""git push commit"""
print(cyan("Pulling changes from repo ( %s / %s)..." % (remote, branch)))
local("git push %s %s" % (remote, branch)) | python | def push(remote='origin', branch='master'):
"""git push commit"""
print(cyan("Pulling changes from repo ( %s / %s)..." % (remote, branch)))
local("git push %s %s" % (remote, branch)) | [
"def",
"push",
"(",
"remote",
"=",
"'origin'",
",",
"branch",
"=",
"'master'",
")",
":",
"print",
"(",
"cyan",
"(",
"\"Pulling changes from repo ( %s / %s)...\"",
"%",
"(",
"remote",
",",
"branch",
")",
")",
")",
"local",
"(",
"\"git push %s %s\"",
"%",
"(",... | git push commit | [
"git",
"push",
"commit"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/fabfile/git.py#L7-L10 | train | Push changes from the remote repository to the given branch |
ronhanson/python-tbx | fabfile/git.py | pull | def pull(remote='origin', branch='master'):
"""git pull commit"""
print(cyan("Pulling changes from repo ( %s / %s)..." % (remote, branch)))
local("git pull %s %s" % (remote, branch)) | python | def pull(remote='origin', branch='master'):
"""git pull commit"""
print(cyan("Pulling changes from repo ( %s / %s)..." % (remote, branch)))
local("git pull %s %s" % (remote, branch)) | [
"def",
"pull",
"(",
"remote",
"=",
"'origin'",
",",
"branch",
"=",
"'master'",
")",
":",
"print",
"(",
"cyan",
"(",
"\"Pulling changes from repo ( %s / %s)...\"",
"%",
"(",
"remote",
",",
"branch",
")",
")",
")",
"local",
"(",
"\"git pull %s %s\"",
"%",
"(",... | git pull commit | [
"git",
"pull",
"commit"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/fabfile/git.py#L14-L17 | train | Pulls changes from a remote branch |
ronhanson/python-tbx | fabfile/git.py | sync | def sync(remote='origin', branch='master'):
"""git pull and push commit"""
pull(branch, remote)
push(branch, remote)
print(cyan("Git Synced!")) | python | def sync(remote='origin', branch='master'):
"""git pull and push commit"""
pull(branch, remote)
push(branch, remote)
print(cyan("Git Synced!")) | [
"def",
"sync",
"(",
"remote",
"=",
"'origin'",
",",
"branch",
"=",
"'master'",
")",
":",
"pull",
"(",
"branch",
",",
"remote",
")",
"push",
"(",
"branch",
",",
"remote",
")",
"print",
"(",
"cyan",
"(",
"\"Git Synced!\"",
")",
")"
] | git pull and push commit | [
"git",
"pull",
"and",
"push",
"commit"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/fabfile/git.py#L21-L25 | train | sync git repository |
mardix/Mocha | mocha/contrib/app_data.py | get | def get(key, node=None, default=None):
"""
Retrieve data
:param key:
:param node: the node_key or the dot notation key to retrieve sub data
get('myapp', 'this.is.a.nested.dict.data')
get('my_other_data')
:param default:
:return: dict_dot dict object
"""
d = AppDa... | python | def get(key, node=None, default=None):
"""
Retrieve data
:param key:
:param node: the node_key or the dot notation key to retrieve sub data
get('myapp', 'this.is.a.nested.dict.data')
get('my_other_data')
:param default:
:return: dict_dot dict object
"""
d = AppDa... | [
"def",
"get",
"(",
"key",
",",
"node",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"d",
"=",
"AppData",
".",
"get_by_key",
"(",
"key",
")",
"if",
"d",
":",
"data",
"=",
"utils",
".",
"dict_dot",
"(",
"d",
")",
"return",
"data",
".",
"ge... | Retrieve data
:param key:
:param node: the node_key or the dot notation key to retrieve sub data
get('myapp', 'this.is.a.nested.dict.data')
get('my_other_data')
:param default:
:return: dict_dot dict object | [
"Retrieve",
"data",
":",
"param",
"key",
":",
":",
"param",
"node",
":",
"the",
"node_key",
"or",
"the",
"dot",
"notation",
"key",
"to",
"retrieve",
"sub",
"data",
"get",
"(",
"myapp",
"this",
".",
"is",
".",
"a",
".",
"nested",
".",
"dict",
".",
"... | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/app_data.py#L15-L29 | train | Retrieve data from the object by node_key |
mardix/Mocha | mocha/contrib/app_data.py | set | def set(key, value={}, reset=False, init=False):
"""
Set data
:param key: A unique to set, best to use __name__
:param value: dict - the value to save
:param reset: bool - If true, it will reset the value to the current one.
if False, it will just update the stored value with the c... | python | def set(key, value={}, reset=False, init=False):
"""
Set data
:param key: A unique to set, best to use __name__
:param value: dict - the value to save
:param reset: bool - If true, it will reset the value to the current one.
if False, it will just update the stored value with the c... | [
"def",
"set",
"(",
"key",
",",
"value",
"=",
"{",
"}",
",",
"reset",
"=",
"False",
",",
"init",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"App Data value must be a dict\"",
")"... | Set data
:param key: A unique to set, best to use __name__
:param value: dict - the value to save
:param reset: bool - If true, it will reset the value to the current one.
if False, it will just update the stored value with the current
one
:param init: bool - If True, ... | [
"Set",
"data",
":",
"param",
"key",
":",
"A",
"unique",
"to",
"set",
"best",
"to",
"use",
"__name__",
":",
"param",
"value",
":",
"dict",
"-",
"the",
"value",
"to",
"save",
":",
"param",
"reset",
":",
"bool",
"-",
"If",
"true",
"it",
"will",
"reset... | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/app_data.py#L32-L56 | train | Set the value of the key in the App Data. |
ZEDGR/pychal | challonge/attachments.py | update | def update(tournament, match, attachment, **params):
"""Update the attributes of a match attachment."""
api.fetch(
"PUT",
"tournaments/%s/matches/%s/attachments/%s" % (tournament, match, attachment),
"match_attachment",
**params) | python | def update(tournament, match, attachment, **params):
"""Update the attributes of a match attachment."""
api.fetch(
"PUT",
"tournaments/%s/matches/%s/attachments/%s" % (tournament, match, attachment),
"match_attachment",
**params) | [
"def",
"update",
"(",
"tournament",
",",
"match",
",",
"attachment",
",",
"*",
"*",
"params",
")",
":",
"api",
".",
"fetch",
"(",
"\"PUT\"",
",",
"\"tournaments/%s/matches/%s/attachments/%s\"",
"%",
"(",
"tournament",
",",
"match",
",",
"attachment",
")",
",... | Update the attributes of a match attachment. | [
"Update",
"the",
"attributes",
"of",
"a",
"match",
"attachment",
"."
] | 3600fa9e0557a2a14eb1ad0c0711d28dad3693d7 | https://github.com/ZEDGR/pychal/blob/3600fa9e0557a2a14eb1ad0c0711d28dad3693d7/challonge/attachments.py#L27-L33 | train | Update the attributes of a match attachment. |
MacHu-GWU/sqlalchemy_mate-project | sqlalchemy_mate/crud/selecting.py | count_row | def count_row(engine, table):
"""
Return number of rows in a table.
Example::
>>> count_row(engine, table_user)
3
**中文文档**
返回一个表中的行数。
"""
return engine.execute(select([func.count()]).select_from(table)).fetchone()[0] | python | def count_row(engine, table):
"""
Return number of rows in a table.
Example::
>>> count_row(engine, table_user)
3
**中文文档**
返回一个表中的行数。
"""
return engine.execute(select([func.count()]).select_from(table)).fetchone()[0] | [
"def",
"count_row",
"(",
"engine",
",",
"table",
")",
":",
"return",
"engine",
".",
"execute",
"(",
"select",
"(",
"[",
"func",
".",
"count",
"(",
")",
"]",
")",
".",
"select_from",
"(",
"table",
")",
")",
".",
"fetchone",
"(",
")",
"[",
"0",
"]"... | Return number of rows in a table.
Example::
>>> count_row(engine, table_user)
3
**中文文档**
返回一个表中的行数。 | [
"Return",
"number",
"of",
"rows",
"in",
"a",
"table",
"."
] | 946754744c8870f083fd7b4339fca15d1d6128b2 | https://github.com/MacHu-GWU/sqlalchemy_mate-project/blob/946754744c8870f083fd7b4339fca15d1d6128b2/sqlalchemy_mate/crud/selecting.py#L10-L23 | train | Return number of rows in a table. |
Kortemme-Lab/klab | klab/gfx/colors.py | ggplot_color_wheel | def ggplot_color_wheel(n, start = 15, saturation_adjustment = None, saturation = 0.65, lightness = 1.0, prefix = ''):
'''Returns a list of colors with the same distributed spread as used in ggplot2.
A saturation of 0.5 will leave the input color at the usual saturation e.g. if start is 240 (240/360 = 0.66 = ... | python | def ggplot_color_wheel(n, start = 15, saturation_adjustment = None, saturation = 0.65, lightness = 1.0, prefix = ''):
'''Returns a list of colors with the same distributed spread as used in ggplot2.
A saturation of 0.5 will leave the input color at the usual saturation e.g. if start is 240 (240/360 = 0.66 = ... | [
"def",
"ggplot_color_wheel",
"(",
"n",
",",
"start",
"=",
"15",
",",
"saturation_adjustment",
"=",
"None",
",",
"saturation",
"=",
"0.65",
",",
"lightness",
"=",
"1.0",
",",
"prefix",
"=",
"''",
")",
":",
"hues",
"=",
"range",
"(",
"start",
",",
"start... | Returns a list of colors with the same distributed spread as used in ggplot2.
A saturation of 0.5 will leave the input color at the usual saturation e.g. if start is 240 (240/360 = 0.66 = blue) and saturation is 0.5 then #0000ff will be returned. | [
"Returns",
"a",
"list",
"of",
"colors",
"with",
"the",
"same",
"distributed",
"spread",
"as",
"used",
"in",
"ggplot2",
".",
"A",
"saturation",
"of",
"0",
".",
"5",
"will",
"leave",
"the",
"input",
"color",
"at",
"the",
"usual",
"saturation",
"e",
".",
... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/gfx/colors.py#L34-L43 | train | Returns a list of colors that can be used in ggplot2.
|
Kortemme-Lab/klab | klab/gfx/colors.py | get_spaced_plot_colors | def get_spaced_plot_colors(n, start = 45, saturation_adjustment = 0.7, saturation = 0.65, lightness = 1.0, prefix = ''):
'''Returns a list of colors with the same distributed spread as used in ggplot2 (color wheel) but shaken up a little
so that adjacent series have differing hues for larger values of n.'''
... | python | def get_spaced_plot_colors(n, start = 45, saturation_adjustment = 0.7, saturation = 0.65, lightness = 1.0, prefix = ''):
'''Returns a list of colors with the same distributed spread as used in ggplot2 (color wheel) but shaken up a little
so that adjacent series have differing hues for larger values of n.'''
... | [
"def",
"get_spaced_plot_colors",
"(",
"n",
",",
"start",
"=",
"45",
",",
"saturation_adjustment",
"=",
"0.7",
",",
"saturation",
"=",
"0.65",
",",
"lightness",
"=",
"1.0",
",",
"prefix",
"=",
"''",
")",
":",
"assert",
"(",
"n",
">",
"0",
")",
"if",
"... | Returns a list of colors with the same distributed spread as used in ggplot2 (color wheel) but shaken up a little
so that adjacent series have differing hues for larger values of n. | [
"Returns",
"a",
"list",
"of",
"colors",
"with",
"the",
"same",
"distributed",
"spread",
"as",
"used",
"in",
"ggplot2",
"(",
"color",
"wheel",
")",
"but",
"shaken",
"up",
"a",
"little",
"so",
"that",
"adjacent",
"series",
"have",
"differing",
"hues",
"for",... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/gfx/colors.py#L46-L61 | train | Returns a list of colors with the same distributed spread as used in ggplot2 but shaken up a little
so that adjacent series have differing hues for larger values of n. |
projectshift/shift-boiler | boiler/user/util/oauth_providers.py | OauthProviders.get_providers | def get_providers(self):
"""
Get OAuth providers
Returns a dictionary of oauth applications ready to be registered with
flask oauth extension at application bootstrap.
"""
if self.providers:
return self.providers
providers = dict()
for provide... | python | def get_providers(self):
"""
Get OAuth providers
Returns a dictionary of oauth applications ready to be registered with
flask oauth extension at application bootstrap.
"""
if self.providers:
return self.providers
providers = dict()
for provide... | [
"def",
"get_providers",
"(",
"self",
")",
":",
"if",
"self",
".",
"providers",
":",
"return",
"self",
".",
"providers",
"providers",
"=",
"dict",
"(",
")",
"for",
"provider",
"in",
"self",
".",
"config",
":",
"configurator",
"=",
"provider",
".",
"lower"... | Get OAuth providers
Returns a dictionary of oauth applications ready to be registered with
flask oauth extension at application bootstrap. | [
"Get",
"OAuth",
"providers",
"Returns",
"a",
"dictionary",
"of",
"oauth",
"applications",
"ready",
"to",
"be",
"registered",
"with",
"flask",
"oauth",
"extension",
"at",
"application",
"bootstrap",
"."
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/util/oauth_providers.py#L21-L47 | train | Get OAuth providers and their associated resources |
projectshift/shift-boiler | boiler/user/util/oauth_providers.py | OauthProviders.token_getter | def token_getter(provider, token=None):
""" Generic token getter for all the providers """
session_key = provider + '_token'
if token is None:
token = session.get(session_key)
return token | python | def token_getter(provider, token=None):
""" Generic token getter for all the providers """
session_key = provider + '_token'
if token is None:
token = session.get(session_key)
return token | [
"def",
"token_getter",
"(",
"provider",
",",
"token",
"=",
"None",
")",
":",
"session_key",
"=",
"provider",
"+",
"'_token'",
"if",
"token",
"is",
"None",
":",
"token",
"=",
"session",
".",
"get",
"(",
"session_key",
")",
"return",
"token"
] | Generic token getter for all the providers | [
"Generic",
"token",
"getter",
"for",
"all",
"the",
"providers"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/util/oauth_providers.py#L50-L55 | train | Generic token getter for all the providers |
projectshift/shift-boiler | boiler/user/util/oauth_providers.py | OauthProviders.register_token_getter | def register_token_getter(self, provider):
""" Register callback to retrieve token from session """
app = oauth.remote_apps[provider]
decorator = getattr(app, 'tokengetter')
def getter(token=None):
return self.token_getter(provider, token)
decorator(getter) | python | def register_token_getter(self, provider):
""" Register callback to retrieve token from session """
app = oauth.remote_apps[provider]
decorator = getattr(app, 'tokengetter')
def getter(token=None):
return self.token_getter(provider, token)
decorator(getter) | [
"def",
"register_token_getter",
"(",
"self",
",",
"provider",
")",
":",
"app",
"=",
"oauth",
".",
"remote_apps",
"[",
"provider",
"]",
"decorator",
"=",
"getattr",
"(",
"app",
",",
"'tokengetter'",
")",
"def",
"getter",
"(",
"token",
"=",
"None",
")",
":... | Register callback to retrieve token from session | [
"Register",
"callback",
"to",
"retrieve",
"token",
"from",
"session"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/util/oauth_providers.py#L57-L65 | train | Register callback to retrieve token from session |
projectshift/shift-boiler | boiler/user/util/oauth_providers.py | OauthProviders.vkontakte_config | def vkontakte_config(self, id, secret, scope=None, offline=False, **_):
""" Get config dictionary for vkontakte oauth """
if scope is None: scope = 'email,offline'
if offline: scope += ',offline'
token_params = dict(scope=scope)
config = dict(
request_token_url=None,... | python | def vkontakte_config(self, id, secret, scope=None, offline=False, **_):
""" Get config dictionary for vkontakte oauth """
if scope is None: scope = 'email,offline'
if offline: scope += ',offline'
token_params = dict(scope=scope)
config = dict(
request_token_url=None,... | [
"def",
"vkontakte_config",
"(",
"self",
",",
"id",
",",
"secret",
",",
"scope",
"=",
"None",
",",
"offline",
"=",
"False",
",",
"*",
"*",
"_",
")",
":",
"if",
"scope",
"is",
"None",
":",
"scope",
"=",
"'email,offline'",
"if",
"offline",
":",
"scope",... | Get config dictionary for vkontakte oauth | [
"Get",
"config",
"dictionary",
"for",
"vkontakte",
"oauth"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/util/oauth_providers.py#L87-L102 | train | Get config dictionary for vkontakte oauth |
projectshift/shift-boiler | boiler/user/util/oauth_providers.py | OauthProviders.instagram_config | def instagram_config(self, id, secret, scope=None, **_):
""" Get config dictionary for instagram oauth """
scope = scope if scope else 'basic'
token_params = dict(scope=scope)
config = dict(
# request_token_url=None,
access_token_url='/oauth/access_token/',
... | python | def instagram_config(self, id, secret, scope=None, **_):
""" Get config dictionary for instagram oauth """
scope = scope if scope else 'basic'
token_params = dict(scope=scope)
config = dict(
# request_token_url=None,
access_token_url='/oauth/access_token/',
... | [
"def",
"instagram_config",
"(",
"self",
",",
"id",
",",
"secret",
",",
"scope",
"=",
"None",
",",
"*",
"*",
"_",
")",
":",
"scope",
"=",
"scope",
"if",
"scope",
"else",
"'basic'",
"token_params",
"=",
"dict",
"(",
"scope",
"=",
"scope",
")",
"config"... | Get config dictionary for instagram oauth | [
"Get",
"config",
"dictionary",
"for",
"instagram",
"oauth"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/util/oauth_providers.py#L123-L137 | train | Get config dictionary for instagram oauth |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix.convert | def convert(self, chain_id, residue_id, from_scheme, to_scheme):
'''The API conversion function. This converts between the different residue ID schemes.'''
# At the cost of three function calls, we ignore the case of the scheme parameters to be more user-friendly.
from_scheme = from_scheme.lowe... | python | def convert(self, chain_id, residue_id, from_scheme, to_scheme):
'''The API conversion function. This converts between the different residue ID schemes.'''
# At the cost of three function calls, we ignore the case of the scheme parameters to be more user-friendly.
from_scheme = from_scheme.lowe... | [
"def",
"convert",
"(",
"self",
",",
"chain_id",
",",
"residue_id",
",",
"from_scheme",
",",
"to_scheme",
")",
":",
"# At the cost of three function calls, we ignore the case of the scheme parameters to be more user-friendly.",
"from_scheme",
"=",
"from_scheme",
".",
"lower",
... | The API conversion function. This converts between the different residue ID schemes. | [
"The",
"API",
"conversion",
"function",
".",
"This",
"converts",
"between",
"the",
"different",
"residue",
"ID",
"schemes",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L143-L151 | train | The API conversion function. This converts between the different residue ID schemes. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._convert | def _convert(self, chain_id, residue_id, from_scheme, to_scheme):
'''The actual 'private' conversion function.'''
# There are 12 valid combinations but rather than write them all out explicitly, we will use recursion, sacrificing speed for brevity
if from_scheme == 'rosetta':
atom_i... | python | def _convert(self, chain_id, residue_id, from_scheme, to_scheme):
'''The actual 'private' conversion function.'''
# There are 12 valid combinations but rather than write them all out explicitly, we will use recursion, sacrificing speed for brevity
if from_scheme == 'rosetta':
atom_i... | [
"def",
"_convert",
"(",
"self",
",",
"chain_id",
",",
"residue_id",
",",
"from_scheme",
",",
"to_scheme",
")",
":",
"# There are 12 valid combinations but rather than write them all out explicitly, we will use recursion, sacrificing speed for brevity",
"if",
"from_scheme",
"==",
... | The actual 'private' conversion function. | [
"The",
"actual",
"private",
"conversion",
"function",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L153-L186 | train | The actual private conversion function. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix.convert_from_rosetta | def convert_from_rosetta(self, residue_id, to_scheme):
'''A simpler conversion function to convert from Rosetta numbering without requiring the chain identifier.'''
assert(type(residue_id) == types.IntType)
# Find the chain_id associated with the residue_id
# Scan *all* sequences witho... | python | def convert_from_rosetta(self, residue_id, to_scheme):
'''A simpler conversion function to convert from Rosetta numbering without requiring the chain identifier.'''
assert(type(residue_id) == types.IntType)
# Find the chain_id associated with the residue_id
# Scan *all* sequences witho... | [
"def",
"convert_from_rosetta",
"(",
"self",
",",
"residue_id",
",",
"to_scheme",
")",
":",
"assert",
"(",
"type",
"(",
"residue_id",
")",
"==",
"types",
".",
"IntType",
")",
"# Find the chain_id associated with the residue_id",
"# Scan *all* sequences without breaking out... | A simpler conversion function to convert from Rosetta numbering without requiring the chain identifier. | [
"A",
"simpler",
"conversion",
"function",
"to",
"convert",
"from",
"Rosetta",
"numbering",
"without",
"requiring",
"the",
"chain",
"identifier",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L189-L206 | train | A simpler conversion function to convert from Rosetta numbering without requiring the chain identifier. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._validate | def _validate(self):
'''Validate the mappings.'''
self._validate_fasta_vs_seqres()
self._validate_mapping_signature()
self._validate_id_types()
self._validate_residue_types() | python | def _validate(self):
'''Validate the mappings.'''
self._validate_fasta_vs_seqres()
self._validate_mapping_signature()
self._validate_id_types()
self._validate_residue_types() | [
"def",
"_validate",
"(",
"self",
")",
":",
"self",
".",
"_validate_fasta_vs_seqres",
"(",
")",
"self",
".",
"_validate_mapping_signature",
"(",
")",
"self",
".",
"_validate_id_types",
"(",
")",
"self",
".",
"_validate_residue_types",
"(",
")"
] | Validate the mappings. | [
"Validate",
"the",
"mappings",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L210-L216 | train | Validate the mappings. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._validate_fasta_vs_seqres | def _validate_fasta_vs_seqres(self):
'''Check that the FASTA and SEQRES sequences agree (they sometimes differ)'''
pdb_id = self.pdb_id
for chain_id, sequence in self.pdb.seqres_sequences.iteritems():
if str(sequence) != self.FASTA[pdb_id][chain_id]:
if self.pdb_id in... | python | def _validate_fasta_vs_seqres(self):
'''Check that the FASTA and SEQRES sequences agree (they sometimes differ)'''
pdb_id = self.pdb_id
for chain_id, sequence in self.pdb.seqres_sequences.iteritems():
if str(sequence) != self.FASTA[pdb_id][chain_id]:
if self.pdb_id in... | [
"def",
"_validate_fasta_vs_seqres",
"(",
"self",
")",
":",
"pdb_id",
"=",
"self",
".",
"pdb_id",
"for",
"chain_id",
",",
"sequence",
"in",
"self",
".",
"pdb",
".",
"seqres_sequences",
".",
"iteritems",
"(",
")",
":",
"if",
"str",
"(",
"sequence",
")",
"!... | Check that the FASTA and SEQRES sequences agree (they sometimes differ) | [
"Check",
"that",
"the",
"FASTA",
"and",
"SEQRES",
"sequences",
"agree",
"(",
"they",
"sometimes",
"differ",
")"
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L218-L229 | train | Check that the FASTA and SEQRES sequences agree (th sometimes differ ) |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._validate_mapping_signature | def _validate_mapping_signature(self):
'''Make sure the domains and ranges of the SequenceMaps match the Sequences.'''
# rosetta_to_atom_sequence_maps
for chain_id, sequence_map in self.rosetta_to_atom_sequence_maps.iteritems():
# Check that all Rosetta residues have a mapping
... | python | def _validate_mapping_signature(self):
'''Make sure the domains and ranges of the SequenceMaps match the Sequences.'''
# rosetta_to_atom_sequence_maps
for chain_id, sequence_map in self.rosetta_to_atom_sequence_maps.iteritems():
# Check that all Rosetta residues have a mapping
... | [
"def",
"_validate_mapping_signature",
"(",
"self",
")",
":",
"# rosetta_to_atom_sequence_maps",
"for",
"chain_id",
",",
"sequence_map",
"in",
"self",
".",
"rosetta_to_atom_sequence_maps",
".",
"iteritems",
"(",
")",
":",
"# Check that all Rosetta residues have a mapping",
"... | Make sure the domains and ranges of the SequenceMaps match the Sequences. | [
"Make",
"sure",
"the",
"domains",
"and",
"ranges",
"of",
"the",
"SequenceMaps",
"match",
"the",
"Sequences",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L232-L300 | train | Make sure the domains and ranges of the SequenceMaps match the Sequences. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._validate_id_types | def _validate_id_types(self):
'''Check that the ID types are integers for Rosetta, SEQRES, and UniParc sequences and 6-character PDB IDs for the ATOM sequences.'''
for sequences in [self.uniparc_sequences, self.fasta_sequences, self.seqres_sequences, self.rosetta_sequences]:
for chain_id, s... | python | def _validate_id_types(self):
'''Check that the ID types are integers for Rosetta, SEQRES, and UniParc sequences and 6-character PDB IDs for the ATOM sequences.'''
for sequences in [self.uniparc_sequences, self.fasta_sequences, self.seqres_sequences, self.rosetta_sequences]:
for chain_id, s... | [
"def",
"_validate_id_types",
"(",
"self",
")",
":",
"for",
"sequences",
"in",
"[",
"self",
".",
"uniparc_sequences",
",",
"self",
".",
"fasta_sequences",
",",
"self",
".",
"seqres_sequences",
",",
"self",
".",
"rosetta_sequences",
"]",
":",
"for",
"chain_id",
... | Check that the ID types are integers for Rosetta, SEQRES, and UniParc sequences and 6-character PDB IDs for the ATOM sequences. | [
"Check",
"that",
"the",
"ID",
"types",
"are",
"integers",
"for",
"Rosetta",
"SEQRES",
"and",
"UniParc",
"sequences",
"and",
"6",
"-",
"character",
"PDB",
"IDs",
"for",
"the",
"ATOM",
"sequences",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L303-L317 | train | Check that the ID types are integers for Rosetta SEQRES and UniParc sequences and 6 - character PDB IDs for the ATOM sequences. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._validate_residue_types | def _validate_residue_types(self):
'''Make sure all the residue types map through translation.'''
for chain_id, sequence_map in self.rosetta_to_atom_sequence_maps.iteritems():
rosetta_sequence = self.rosetta_sequences[chain_id]
atom_sequence = self.atom_sequences[chain_id]
... | python | def _validate_residue_types(self):
'''Make sure all the residue types map through translation.'''
for chain_id, sequence_map in self.rosetta_to_atom_sequence_maps.iteritems():
rosetta_sequence = self.rosetta_sequences[chain_id]
atom_sequence = self.atom_sequences[chain_id]
... | [
"def",
"_validate_residue_types",
"(",
"self",
")",
":",
"for",
"chain_id",
",",
"sequence_map",
"in",
"self",
".",
"rosetta_to_atom_sequence_maps",
".",
"iteritems",
"(",
")",
":",
"rosetta_sequence",
"=",
"self",
".",
"rosetta_sequences",
"[",
"chain_id",
"]",
... | Make sure all the residue types map through translation. | [
"Make",
"sure",
"all",
"the",
"residue",
"types",
"map",
"through",
"translation",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L320-L343 | train | Make sure all the residue types map through translation. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._create_inverse_maps | def _create_inverse_maps(self):
'''Create the inverse mappings (UniParc -> SEQRES -> ATOM -> Rosetta).'''
# We have already determined that the inverse maps are well-defined (the normal maps are injective). The inverse maps will be partial maps in general.
self.atom_to_rosetta_sequence_maps = ... | python | def _create_inverse_maps(self):
'''Create the inverse mappings (UniParc -> SEQRES -> ATOM -> Rosetta).'''
# We have already determined that the inverse maps are well-defined (the normal maps are injective). The inverse maps will be partial maps in general.
self.atom_to_rosetta_sequence_maps = ... | [
"def",
"_create_inverse_maps",
"(",
"self",
")",
":",
"# We have already determined that the inverse maps are well-defined (the normal maps are injective). The inverse maps will be partial maps in general.",
"self",
".",
"atom_to_rosetta_sequence_maps",
"=",
"{",
"}",
"for",
"chain_id",
... | Create the inverse mappings (UniParc -> SEQRES -> ATOM -> Rosetta). | [
"Create",
"the",
"inverse",
"mappings",
"(",
"UniParc",
"-",
">",
"SEQRES",
"-",
">",
"ATOM",
"-",
">",
"Rosetta",
")",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L347-L372 | train | Create the inverse mappings for the current class. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._create_sequence_maps | def _create_sequence_maps(self):
'''Get all of the SequenceMaps - Rosetta->ATOM, ATOM->SEQRES/FASTA, SEQRES->UniParc.'''
if self.sifts:
self.sifts_atom_to_seqres_sequence_maps = self.sifts.atom_to_seqres_sequence_maps
self.sifts_seqres_to_uniparc_sequence_maps = self.sifts.seqre... | python | def _create_sequence_maps(self):
'''Get all of the SequenceMaps - Rosetta->ATOM, ATOM->SEQRES/FASTA, SEQRES->UniParc.'''
if self.sifts:
self.sifts_atom_to_seqres_sequence_maps = self.sifts.atom_to_seqres_sequence_maps
self.sifts_seqres_to_uniparc_sequence_maps = self.sifts.seqre... | [
"def",
"_create_sequence_maps",
"(",
"self",
")",
":",
"if",
"self",
".",
"sifts",
":",
"self",
".",
"sifts_atom_to_seqres_sequence_maps",
"=",
"self",
".",
"sifts",
".",
"atom_to_seqres_sequence_maps",
"self",
".",
"sifts_seqres_to_uniparc_sequence_maps",
"=",
"self"... | Get all of the SequenceMaps - Rosetta->ATOM, ATOM->SEQRES/FASTA, SEQRES->UniParc. | [
"Get",
"all",
"of",
"the",
"SequenceMaps",
"-",
"Rosetta",
"-",
">",
"ATOM",
"ATOM",
"-",
">",
"SEQRES",
"/",
"FASTA",
"SEQRES",
"-",
">",
"UniParc",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L374-L405 | train | Create all of the SequenceMaps - Rosetta - ATOM - FASTA - SEQRES - FASTA - UNIPARC. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._merge_sifts_maps | def _merge_sifts_maps(self):
''' Make sure that the pdbml_atom_to_seqres_sequence_maps and clustal_seqres_to_uniparc_sequence_maps agree with SIFTS and merge the maps.
SIFTS may have more entries since we discard PDB residues which break Rosetta.
SIFTS may have less entries for s... | python | def _merge_sifts_maps(self):
''' Make sure that the pdbml_atom_to_seqres_sequence_maps and clustal_seqres_to_uniparc_sequence_maps agree with SIFTS and merge the maps.
SIFTS may have more entries since we discard PDB residues which break Rosetta.
SIFTS may have less entries for s... | [
"def",
"_merge_sifts_maps",
"(",
"self",
")",
":",
"if",
"self",
".",
"pdb_id",
"in",
"do_not_use_the_sequence_aligner",
":",
"assert",
"(",
"self",
".",
"sifts",
")",
"self",
".",
"atom_to_seqres_sequence_maps",
"=",
"self",
".",
"sifts_atom_to_seqres_sequence_maps... | Make sure that the pdbml_atom_to_seqres_sequence_maps and clustal_seqres_to_uniparc_sequence_maps agree with SIFTS and merge the maps.
SIFTS may have more entries since we discard PDB residues which break Rosetta.
SIFTS may have less entries for some cases e.g. 1AR1, chain C where SIFTS ... | [
"Make",
"sure",
"that",
"the",
"pdbml_atom_to_seqres_sequence_maps",
"and",
"clustal_seqres_to_uniparc_sequence_maps",
"agree",
"with",
"SIFTS",
"and",
"merge",
"the",
"maps",
".",
"SIFTS",
"may",
"have",
"more",
"entries",
"since",
"we",
"discard",
"PDB",
"residues",... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L407-L474 | train | Merge the SIFTS atom to seqres sequence maps. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._prune_maps_to_sequences | def _prune_maps_to_sequences(self):
''' When we merge the SIFTS maps, we can extend the sequence maps such that they have elements in their domain that we removed
from the sequence e.g. 1A2P, residue 'B 3 ' is removed because Rosetta barfs on it. Here, we prune the maps so that their
d... | python | def _prune_maps_to_sequences(self):
''' When we merge the SIFTS maps, we can extend the sequence maps such that they have elements in their domain that we removed
from the sequence e.g. 1A2P, residue 'B 3 ' is removed because Rosetta barfs on it. Here, we prune the maps so that their
d... | [
"def",
"_prune_maps_to_sequences",
"(",
"self",
")",
":",
"for",
"c",
",",
"seq",
"in",
"self",
".",
"atom_sequences",
".",
"iteritems",
"(",
")",
":",
"res_ids",
"=",
"[",
"r",
"[",
"0",
"]",
"for",
"r",
"in",
"seq",
"]",
"for_removal",
"=",
"[",
... | When we merge the SIFTS maps, we can extend the sequence maps such that they have elements in their domain that we removed
from the sequence e.g. 1A2P, residue 'B 3 ' is removed because Rosetta barfs on it. Here, we prune the maps so that their
domains do not have elements that were removed fr... | [
"When",
"we",
"merge",
"the",
"SIFTS",
"maps",
"we",
"can",
"extend",
"the",
"sequence",
"maps",
"such",
"that",
"they",
"have",
"elements",
"in",
"their",
"domain",
"that",
"we",
"removed",
"from",
"the",
"sequence",
"e",
".",
"g",
".",
"1A2P",
"residue... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L476-L488 | train | Prune the SIFTS maps so that they have elements in their respective sequence maps. |
Kortemme-Lab/klab | klab/bio/relatrix.py | ResidueRelatrix._create_sequences | def _create_sequences(self):
'''Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc.'''
# Create the Rosetta sequences and the maps from the Rosetta sequences to the ATOM sequences
try:
self.pdb.construct_pdb_to_rosetta_residue_map(self.rosetta_scripts_path, rosetta_dat... | python | def _create_sequences(self):
'''Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc.'''
# Create the Rosetta sequences and the maps from the Rosetta sequences to the ATOM sequences
try:
self.pdb.construct_pdb_to_rosetta_residue_map(self.rosetta_scripts_path, rosetta_dat... | [
"def",
"_create_sequences",
"(",
"self",
")",
":",
"# Create the Rosetta sequences and the maps from the Rosetta sequences to the ATOM sequences",
"try",
":",
"self",
".",
"pdb",
".",
"construct_pdb_to_rosetta_residue_map",
"(",
"self",
".",
"rosetta_scripts_path",
",",
"rosett... | Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc. | [
"Get",
"all",
"of",
"the",
"Sequences",
"-",
"Rosetta",
"ATOM",
"SEQRES",
"FASTA",
"UniParc",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/relatrix.py#L505-L558 | train | Get all of the Sequences - Rosetta ATOM SEQRES FASTA UniParc. |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | SearchableModel.search | def search(cls,
query_string,
options=None,
enable_facet_discovery=False,
return_facets=None,
facet_options=None,
facet_refinements=None,
deadline=None,
**kwargs):
"""
Searches the ind... | python | def search(cls,
query_string,
options=None,
enable_facet_discovery=False,
return_facets=None,
facet_options=None,
facet_refinements=None,
deadline=None,
**kwargs):
"""
Searches the ind... | [
"def",
"search",
"(",
"cls",
",",
"query_string",
",",
"options",
"=",
"None",
",",
"enable_facet_discovery",
"=",
"False",
",",
"return_facets",
"=",
"None",
",",
"facet_options",
"=",
"None",
",",
"facet_refinements",
"=",
"None",
",",
"deadline",
"=",
"No... | Searches the index. Conveniently searches only for documents that belong to instances of this class.
:param query_string: The query to match against documents in the index. See search.Query() for details.
:param options: A QueryOptions describing post-processing of search results.
:param enable... | [
"Searches",
"the",
"index",
".",
"Conveniently",
"searches",
"only",
"for",
"documents",
"that",
"belong",
"to",
"instances",
"of",
"this",
"class",
"."
] | 4f999336b464704a0929cec135c1f09fb1ddfb7c | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L49-L94 | train | Search the index for documents that belong to this class. |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | SearchableModel.search_update_index | def search_update_index(self):
"""
Updates the search index for this instance.
This happens automatically on put.
"""
doc_id = self.search_get_document_id(self.key)
fields = [search.AtomField('class_name', name) for name in self.search_get_class_names()]
index ... | python | def search_update_index(self):
"""
Updates the search index for this instance.
This happens automatically on put.
"""
doc_id = self.search_get_document_id(self.key)
fields = [search.AtomField('class_name', name) for name in self.search_get_class_names()]
index ... | [
"def",
"search_update_index",
"(",
"self",
")",
":",
"doc_id",
"=",
"self",
".",
"search_get_document_id",
"(",
"self",
".",
"key",
")",
"fields",
"=",
"[",
"search",
".",
"AtomField",
"(",
"'class_name'",
",",
"name",
")",
"for",
"name",
"in",
"self",
"... | Updates the search index for this instance.
This happens automatically on put. | [
"Updates",
"the",
"search",
"index",
"for",
"this",
"instance",
"."
] | 4f999336b464704a0929cec135c1f09fb1ddfb7c | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L96-L143 | train | Updates the search index for this instance. This happens automatically on put. |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | SearchableModel.search_get_class_names | def search_get_class_names(cls):
"""
Returns class names for use in document indexing.
"""
if hasattr(cls, '_class_key'):
class_names = []
for n in cls._class_key():
class_names.append(n)
return class_names
else:
ret... | python | def search_get_class_names(cls):
"""
Returns class names for use in document indexing.
"""
if hasattr(cls, '_class_key'):
class_names = []
for n in cls._class_key():
class_names.append(n)
return class_names
else:
ret... | [
"def",
"search_get_class_names",
"(",
"cls",
")",
":",
"if",
"hasattr",
"(",
"cls",
",",
"'_class_key'",
")",
":",
"class_names",
"=",
"[",
"]",
"for",
"n",
"in",
"cls",
".",
"_class_key",
"(",
")",
":",
"class_names",
".",
"append",
"(",
"n",
")",
"... | Returns class names for use in document indexing. | [
"Returns",
"class",
"names",
"for",
"use",
"in",
"document",
"indexing",
"."
] | 4f999336b464704a0929cec135c1f09fb1ddfb7c | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L146-L156 | train | Returns class names for use in document indexing. |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | SearchableModel.from_urlsafe | def from_urlsafe(cls, urlsafe):
"""
Returns an instance of the model from a urlsafe string.
:param urlsafe: urlsafe key
:return: Instance of cls
"""
try:
key = ndb.Key(urlsafe=urlsafe)
except:
return None
obj = key.get()
if... | python | def from_urlsafe(cls, urlsafe):
"""
Returns an instance of the model from a urlsafe string.
:param urlsafe: urlsafe key
:return: Instance of cls
"""
try:
key = ndb.Key(urlsafe=urlsafe)
except:
return None
obj = key.get()
if... | [
"def",
"from_urlsafe",
"(",
"cls",
",",
"urlsafe",
")",
":",
"try",
":",
"key",
"=",
"ndb",
".",
"Key",
"(",
"urlsafe",
"=",
"urlsafe",
")",
"except",
":",
"return",
"None",
"obj",
"=",
"key",
".",
"get",
"(",
")",
"if",
"obj",
"and",
"isinstance",... | Returns an instance of the model from a urlsafe string.
:param urlsafe: urlsafe key
:return: Instance of cls | [
"Returns",
"an",
"instance",
"of",
"the",
"model",
"from",
"a",
"urlsafe",
"string",
"."
] | 4f999336b464704a0929cec135c1f09fb1ddfb7c | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L159-L172 | train | Returns an instance of cls from a urlsafe string. |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | SearchableModel.get_from_search_doc | def get_from_search_doc(cls, doc_id):
"""
Returns an instance of the model from a search document id.
:param doc_id: Search document id
:return: Instance of cls
"""
# If the document was passed instead of the doc_id, get the document.
if hasattr(doc_id, 'doc_id')... | python | def get_from_search_doc(cls, doc_id):
"""
Returns an instance of the model from a search document id.
:param doc_id: Search document id
:return: Instance of cls
"""
# If the document was passed instead of the doc_id, get the document.
if hasattr(doc_id, 'doc_id')... | [
"def",
"get_from_search_doc",
"(",
"cls",
",",
"doc_id",
")",
":",
"# If the document was passed instead of the doc_id, get the document.",
"if",
"hasattr",
"(",
"doc_id",
",",
"'doc_id'",
")",
":",
"doc_id",
"=",
"doc_id",
".",
"doc_id",
"return",
"cls",
".",
"from... | Returns an instance of the model from a search document id.
:param doc_id: Search document id
:return: Instance of cls | [
"Returns",
"an",
"instance",
"of",
"the",
"model",
"from",
"a",
"search",
"document",
"id",
"."
] | 4f999336b464704a0929cec135c1f09fb1ddfb7c | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L175-L185 | train | Returns an instance of the model from a search document id. |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | SearchableModel._pre_delete_hook | def _pre_delete_hook(cls, key):
"""
Removes instance from index.
"""
if cls.searching_enabled:
doc_id = cls.search_get_document_id(key)
index = cls.search_get_index()
index.delete(doc_id) | python | def _pre_delete_hook(cls, key):
"""
Removes instance from index.
"""
if cls.searching_enabled:
doc_id = cls.search_get_document_id(key)
index = cls.search_get_index()
index.delete(doc_id) | [
"def",
"_pre_delete_hook",
"(",
"cls",
",",
"key",
")",
":",
"if",
"cls",
".",
"searching_enabled",
":",
"doc_id",
"=",
"cls",
".",
"search_get_document_id",
"(",
"key",
")",
"index",
"=",
"cls",
".",
"search_get_index",
"(",
")",
"index",
".",
"delete",
... | Removes instance from index. | [
"Removes",
"instance",
"from",
"index",
"."
] | 4f999336b464704a0929cec135c1f09fb1ddfb7c | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L188-L195 | train | Remove instance from index. |
adaptive-learning/proso-apps | proso/models/environment.py | Environment.process_answer | def process_answer(self, user, item, asked, answered, time, answer, response_time, guess, **kwargs):
"""
This method is used during the answer streaming and is called after the
predictive model for each answer.
Args:
user (int):
identifier of ther user answer... | python | def process_answer(self, user, item, asked, answered, time, answer, response_time, guess, **kwargs):
"""
This method is used during the answer streaming and is called after the
predictive model for each answer.
Args:
user (int):
identifier of ther user answer... | [
"def",
"process_answer",
"(",
"self",
",",
"user",
",",
"item",
",",
"asked",
",",
"answered",
",",
"time",
",",
"answer",
",",
"response_time",
",",
"guess",
",",
"*",
"*",
"kwargs",
")",
":",
"pass"
] | This method is used during the answer streaming and is called after the
predictive model for each answer.
Args:
user (int):
identifier of ther user answering the question
asked (int):
identifier of the asked item
answered (int):
... | [
"This",
"method",
"is",
"used",
"during",
"the",
"answer",
"streaming",
"and",
"is",
"called",
"after",
"the",
"predictive",
"model",
"for",
"each",
"answer",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/models/environment.py#L18-L38 | train | This method is used during the answer streaming and is called after the answer streaming is called for each answer. |
Apstra/aeon-venos | pylib/aeon/nxos/autoload/guestshell.py | _guestshell.sudoers | def sudoers(self, enable):
"""
This method is used to enable/disable bash sudo commands running
through the guestshell virtual service. By default sudo access
is prevented due to the setting in the 'sudoers' file. Therefore
the setting must be disabled in the file to enable sud... | python | def sudoers(self, enable):
"""
This method is used to enable/disable bash sudo commands running
through the guestshell virtual service. By default sudo access
is prevented due to the setting in the 'sudoers' file. Therefore
the setting must be disabled in the file to enable sud... | [
"def",
"sudoers",
"(",
"self",
",",
"enable",
")",
":",
"f_sudoers",
"=",
"\"/isan/vdc_1/virtual-instance/guestshell+/rootfs/etc/sudoers\"",
"if",
"enable",
"is",
"True",
":",
"sed_cmd",
"=",
"r\" 's/\\(^Defaults *requiretty\\)/#\\1/g' \"",
"elif",
"enable",
"is",
"False"... | This method is used to enable/disable bash sudo commands running
through the guestshell virtual service. By default sudo access
is prevented due to the setting in the 'sudoers' file. Therefore
the setting must be disabled in the file to enable sudo commands.
This method assumes that t... | [
"This",
"method",
"is",
"used",
"to",
"enable",
"/",
"disable",
"bash",
"sudo",
"commands",
"running",
"through",
"the",
"guestshell",
"virtual",
"service",
".",
"By",
"default",
"sudo",
"access",
"is",
"prevented",
"due",
"to",
"the",
"setting",
"in",
"the"... | 4d4f73d5904831ddc78c30922a8a226c90cf7d90 | https://github.com/Apstra/aeon-venos/blob/4d4f73d5904831ddc78c30922a8a226c90cf7d90/pylib/aeon/nxos/autoload/guestshell.py#L150-L177 | train | This method is used to enable sudo commands running
through the guestshell virtual service. |
Apstra/aeon-venos | pylib/aeon/nxos/autoload/guestshell.py | _guestshell._get_sz_info | def _get_sz_info(self):
"""
Obtains the current resource allocations, assumes that the
guestshell is in an 'Activated' state
"""
if 'None' == self._state:
return None
cmd = 'show virtual-service detail name guestshell+'
got = self.cli(cmd)
got... | python | def _get_sz_info(self):
"""
Obtains the current resource allocations, assumes that the
guestshell is in an 'Activated' state
"""
if 'None' == self._state:
return None
cmd = 'show virtual-service detail name guestshell+'
got = self.cli(cmd)
got... | [
"def",
"_get_sz_info",
"(",
"self",
")",
":",
"if",
"'None'",
"==",
"self",
".",
"_state",
":",
"return",
"None",
"cmd",
"=",
"'show virtual-service detail name guestshell+'",
"got",
"=",
"self",
".",
"cli",
"(",
"cmd",
")",
"got",
"=",
"got",
"[",
"'TABLE... | Obtains the current resource allocations, assumes that the
guestshell is in an 'Activated' state | [
"Obtains",
"the",
"current",
"resource",
"allocations",
"assumes",
"that",
"the",
"guestshell",
"is",
"in",
"an",
"Activated",
"state"
] | 4d4f73d5904831ddc78c30922a8a226c90cf7d90 | https://github.com/Apstra/aeon-venos/blob/4d4f73d5904831ddc78c30922a8a226c90cf7d90/pylib/aeon/nxos/autoload/guestshell.py#L198-L215 | train | Gets the current resource allocations |
assamite/creamas | creamas/image.py | fractal_dimension | def fractal_dimension(image):
'''Estimates the fractal dimension of an image with box counting.
Counts pixels with value 0 as empty and everything else as non-empty.
Input image has to be grayscale.
See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Fractal_dimension>`_.
:param image: numpy.ndarra... | python | def fractal_dimension(image):
'''Estimates the fractal dimension of an image with box counting.
Counts pixels with value 0 as empty and everything else as non-empty.
Input image has to be grayscale.
See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Fractal_dimension>`_.
:param image: numpy.ndarra... | [
"def",
"fractal_dimension",
"(",
"image",
")",
":",
"pixels",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"image",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"j",
"in",
"range",
"(",
"image",
".",
"shape",
"[",
"1",
"]",
")",
":",
"if",
... | Estimates the fractal dimension of an image with box counting.
Counts pixels with value 0 as empty and everything else as non-empty.
Input image has to be grayscale.
See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Fractal_dimension>`_.
:param image: numpy.ndarray
:returns: estimation of fractal... | [
"Estimates",
"the",
"fractal",
"dimension",
"of",
"an",
"image",
"with",
"box",
"counting",
".",
"Counts",
"pixels",
"with",
"value",
"0",
"as",
"empty",
"and",
"everything",
"else",
"as",
"non",
"-",
"empty",
".",
"Input",
"image",
"has",
"to",
"be",
"g... | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/image.py#L11-L46 | train | Estimates the fractal dimension of an image with box counting. |
assamite/creamas | creamas/image.py | channel_portion | def channel_portion(image, channel):
'''Estimates the amount of a color relative to other colors.
:param image: numpy.ndarray
:param channel: int
:returns: portion of a channel in an image
:rtype: float
'''
# Separate color channels
rgb = []
for i in range(3):
rgb.append(im... | python | def channel_portion(image, channel):
'''Estimates the amount of a color relative to other colors.
:param image: numpy.ndarray
:param channel: int
:returns: portion of a channel in an image
:rtype: float
'''
# Separate color channels
rgb = []
for i in range(3):
rgb.append(im... | [
"def",
"channel_portion",
"(",
"image",
",",
"channel",
")",
":",
"# Separate color channels",
"rgb",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"rgb",
".",
"append",
"(",
"image",
"[",
":",
",",
":",
",",
"i",
"]",
".",
"astype"... | Estimates the amount of a color relative to other colors.
:param image: numpy.ndarray
:param channel: int
:returns: portion of a channel in an image
:rtype: float | [
"Estimates",
"the",
"amount",
"of",
"a",
"color",
"relative",
"to",
"other",
"colors",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/image.py#L49-L67 | train | Estimates the amount of a color relative to other colors. |
assamite/creamas | creamas/image.py | intensity | def intensity(image):
'''Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float
'''
if len(image.shape) > 2:
# Convert to grayscale
image = cv2.cvtColor(image, cv2... | python | def intensity(image):
'''Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float
'''
if len(image.shape) > 2:
# Convert to grayscale
image = cv2.cvtColor(image, cv2... | [
"def",
"intensity",
"(",
"image",
")",
":",
"if",
"len",
"(",
"image",
".",
"shape",
")",
">",
"2",
":",
"# Convert to grayscale",
"image",
"=",
"cv2",
".",
"cvtColor",
"(",
"image",
",",
"cv2",
".",
"COLOR_RGB2GRAY",
")",
"/",
"255",
"elif",
"issubcla... | Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float | [
"Calculates",
"the",
"average",
"intensity",
"of",
"the",
"pixels",
"in",
"an",
"image",
".",
"Accepts",
"both",
"RGB",
"and",
"grayscale",
"images",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/image.py#L70-L83 | train | Calculates the average intensity of the pixels in an image. |
Kortemme-Lab/klab | klab/cloning/dna.py | sliding_window | def sliding_window(sequence, win_size, step=1):
"""
Returns a generator that will iterate through
the defined chunks of input sequence. Input sequence
must be iterable.
Credit: http://scipher.wordpress.com/2010/12/02/simple-sliding-window-iterator-in-python/
https://github.com/xguse/scipherPyP... | python | def sliding_window(sequence, win_size, step=1):
"""
Returns a generator that will iterate through
the defined chunks of input sequence. Input sequence
must be iterable.
Credit: http://scipher.wordpress.com/2010/12/02/simple-sliding-window-iterator-in-python/
https://github.com/xguse/scipherPyP... | [
"def",
"sliding_window",
"(",
"sequence",
",",
"win_size",
",",
"step",
"=",
"1",
")",
":",
"# Verify the inputs",
"try",
":",
"it",
"=",
"iter",
"(",
"sequence",
")",
"except",
"TypeError",
":",
"raise",
"ValueError",
"(",
"\"sequence must be iterable.\"",
")... | Returns a generator that will iterate through
the defined chunks of input sequence. Input sequence
must be iterable.
Credit: http://scipher.wordpress.com/2010/12/02/simple-sliding-window-iterator-in-python/
https://github.com/xguse/scipherPyProj/blob/master/scipherSrc/defs/basicDefs.py | [
"Returns",
"a",
"generator",
"that",
"will",
"iterate",
"through",
"the",
"defined",
"chunks",
"of",
"input",
"sequence",
".",
"Input",
"sequence",
"must",
"be",
"iterable",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/cloning/dna.py#L103-L132 | train | Returns a generator that will iterate through the defined chunks of input sequence. |
Kortemme-Lab/klab | klab/cloning/dna.py | dna_to_re | def dna_to_re(seq):
"""
Return a compiled regular expression that will match anything described by
the input sequence. For example, a sequence that contains a 'N' matched
any base at that position.
"""
seq = seq.replace('K', '[GT]')
seq = seq.replace('M', '[AC]')
seq = seq.replace('R... | python | def dna_to_re(seq):
"""
Return a compiled regular expression that will match anything described by
the input sequence. For example, a sequence that contains a 'N' matched
any base at that position.
"""
seq = seq.replace('K', '[GT]')
seq = seq.replace('M', '[AC]')
seq = seq.replace('R... | [
"def",
"dna_to_re",
"(",
"seq",
")",
":",
"seq",
"=",
"seq",
".",
"replace",
"(",
"'K'",
",",
"'[GT]'",
")",
"seq",
"=",
"seq",
".",
"replace",
"(",
"'M'",
",",
"'[AC]'",
")",
"seq",
"=",
"seq",
".",
"replace",
"(",
"'R'",
",",
"'[AG]'",
")",
"... | Return a compiled regular expression that will match anything described by
the input sequence. For example, a sequence that contains a 'N' matched
any base at that position. | [
"Return",
"a",
"compiled",
"regular",
"expression",
"that",
"will",
"match",
"anything",
"described",
"by",
"the",
"input",
"sequence",
".",
"For",
"example",
"a",
"sequence",
"that",
"contains",
"a",
"N",
"matched",
"any",
"base",
"at",
"that",
"position",
... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/cloning/dna.py#L139-L159 | train | Return a compiled regular expression that will match any base at that position. |
Kortemme-Lab/klab | klab/cloning/dna.py | case_highlight | def case_highlight(seq, subseq):
"""
Highlights all instances of subseq in seq by making them uppercase and
everything else lowercase.
"""
return re.subs(subseq.lower(), subseq.upper(), seq.lower()) | python | def case_highlight(seq, subseq):
"""
Highlights all instances of subseq in seq by making them uppercase and
everything else lowercase.
"""
return re.subs(subseq.lower(), subseq.upper(), seq.lower()) | [
"def",
"case_highlight",
"(",
"seq",
",",
"subseq",
")",
":",
"return",
"re",
".",
"subs",
"(",
"subseq",
".",
"lower",
"(",
")",
",",
"subseq",
".",
"upper",
"(",
")",
",",
"seq",
".",
"lower",
"(",
")",
")"
] | Highlights all instances of subseq in seq by making them uppercase and
everything else lowercase. | [
"Highlights",
"all",
"instances",
"of",
"subseq",
"in",
"seq",
"by",
"making",
"them",
"uppercase",
"and",
"everything",
"else",
"lowercase",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/cloning/dna.py#L161-L166 | train | Highlights all instances of subseq in seq by making them uppercase and everything else lowercase. |
inveniosoftware/invenio-pidrelations | invenio_pidrelations/indexers.py | index_relations | def index_relations(sender, pid_type, json=None,
record=None, index=None, **kwargs):
"""Add relations to the indexed record."""
if not json:
json = {}
pid = PersistentIdentifier.query.filter(
PersistentIdentifier.object_uuid == record.id,
PersistentIdentifier.pid_... | python | def index_relations(sender, pid_type, json=None,
record=None, index=None, **kwargs):
"""Add relations to the indexed record."""
if not json:
json = {}
pid = PersistentIdentifier.query.filter(
PersistentIdentifier.object_uuid == record.id,
PersistentIdentifier.pid_... | [
"def",
"index_relations",
"(",
"sender",
",",
"pid_type",
",",
"json",
"=",
"None",
",",
"record",
"=",
"None",
",",
"index",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"json",
":",
"json",
"=",
"{",
"}",
"pid",
"=",
"PersistentId... | Add relations to the indexed record. | [
"Add",
"relations",
"to",
"the",
"indexed",
"record",
"."
] | a49f3725cf595b663c5b04814280b231f88bc333 | https://github.com/inveniosoftware/invenio-pidrelations/blob/a49f3725cf595b663c5b04814280b231f88bc333/invenio_pidrelations/indexers.py#L37-L51 | train | Add relations to the indexed record. |
inveniosoftware/invenio-pidrelations | invenio_pidrelations/indexers.py | index_siblings | def index_siblings(pid, include_pid=False, children=None,
neighbors_eager=False, eager=False, with_deposits=True):
"""Send sibling records of the passed pid for indexing.
Note: By default does not index the 'pid' itself,
only zero or more siblings.
:param pid: PID (recid) of w... | python | def index_siblings(pid, include_pid=False, children=None,
neighbors_eager=False, eager=False, with_deposits=True):
"""Send sibling records of the passed pid for indexing.
Note: By default does not index the 'pid' itself,
only zero or more siblings.
:param pid: PID (recid) of w... | [
"def",
"index_siblings",
"(",
"pid",
",",
"include_pid",
"=",
"False",
",",
"children",
"=",
"None",
",",
"neighbors_eager",
"=",
"False",
",",
"eager",
"=",
"False",
",",
"with_deposits",
"=",
"True",
")",
":",
"assert",
"not",
"(",
"neighbors_eager",
"an... | Send sibling records of the passed pid for indexing.
Note: By default does not index the 'pid' itself,
only zero or more siblings.
:param pid: PID (recid) of whose siblings are to be indexed.
:param children: Overrides children with a fixed list of PID.
Children should contain the 'pid' ... | [
"Send",
"sibling",
"records",
"of",
"the",
"passed",
"pid",
"for",
"indexing",
"."
] | a49f3725cf595b663c5b04814280b231f88bc333 | https://github.com/inveniosoftware/invenio-pidrelations/blob/a49f3725cf595b663c5b04814280b231f88bc333/invenio_pidrelations/indexers.py#L54-L124 | train | Index siblings of the passed pid. |
brunato/lograptor | lograptor/filemap.py | GlobDict.iter_paths | def iter_paths(self, pathnames=None, mapfunc=None):
"""
Special iteration on paths. Yields couples of path and items. If a expanded path
doesn't match with any files a couple with path and `None` is returned.
:param pathnames: Iterable with a set of pathnames. If is `None` uses the all ... | python | def iter_paths(self, pathnames=None, mapfunc=None):
"""
Special iteration on paths. Yields couples of path and items. If a expanded path
doesn't match with any files a couple with path and `None` is returned.
:param pathnames: Iterable with a set of pathnames. If is `None` uses the all ... | [
"def",
"iter_paths",
"(",
"self",
",",
"pathnames",
"=",
"None",
",",
"mapfunc",
"=",
"None",
")",
":",
"pathnames",
"=",
"pathnames",
"or",
"self",
".",
"_pathnames",
"if",
"self",
".",
"recursive",
"and",
"not",
"pathnames",
":",
"pathnames",
"=",
"[",... | Special iteration on paths. Yields couples of path and items. If a expanded path
doesn't match with any files a couple with path and `None` is returned.
:param pathnames: Iterable with a set of pathnames. If is `None` uses the all \
the stored pathnames.
:param mapfunc: A mapping functi... | [
"Special",
"iteration",
"on",
"paths",
".",
"Yields",
"couples",
"of",
"path",
"and",
"items",
".",
"If",
"a",
"expanded",
"path",
"doesn",
"t",
"match",
"with",
"any",
"files",
"a",
"couple",
"with",
"path",
"and",
"None",
"is",
"returned",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/filemap.py#L111-L154 | train | Iterate over the pathnames and return a set of items. |
brunato/lograptor | lograptor/filemap.py | FileMap.check_stat | def check_stat(self, path):
"""
Checks logfile stat information for excluding files not in datetime period.
On Linux it's possible to checks only modification time, because file creation info
are not available, so it's possible to exclude only older files.
In Unix BSD systems and... | python | def check_stat(self, path):
"""
Checks logfile stat information for excluding files not in datetime period.
On Linux it's possible to checks only modification time, because file creation info
are not available, so it's possible to exclude only older files.
In Unix BSD systems and... | [
"def",
"check_stat",
"(",
"self",
",",
"path",
")",
":",
"statinfo",
"=",
"os",
".",
"stat",
"(",
"path",
")",
"st_mtime",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"statinfo",
".",
"st_mtime",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
... | Checks logfile stat information for excluding files not in datetime period.
On Linux it's possible to checks only modification time, because file creation info
are not available, so it's possible to exclude only older files.
In Unix BSD systems and windows information about file creation date an... | [
"Checks",
"logfile",
"stat",
"information",
"for",
"excluding",
"files",
"not",
"in",
"datetime",
"period",
".",
"On",
"Linux",
"it",
"s",
"possible",
"to",
"checks",
"only",
"modification",
"time",
"because",
"file",
"creation",
"info",
"are",
"not",
"availab... | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/filemap.py#L192-L210 | train | Checks the stat information for excluding files not in datetime period. |
brunato/lograptor | lograptor/filemap.py | FileMap.add | def add(self, files, items):
"""
Add a list of files with a reference to a list of objects.
"""
if isinstance(files, (str, bytes)):
files = iter([files])
for pathname in files:
try:
values = self._filemap[pathname]
except KeyErr... | python | def add(self, files, items):
"""
Add a list of files with a reference to a list of objects.
"""
if isinstance(files, (str, bytes)):
files = iter([files])
for pathname in files:
try:
values = self._filemap[pathname]
except KeyErr... | [
"def",
"add",
"(",
"self",
",",
"files",
",",
"items",
")",
":",
"if",
"isinstance",
"(",
"files",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"files",
"=",
"iter",
"(",
"[",
"files",
"]",
")",
"for",
"pathname",
"in",
"files",
":",
"try",
":... | Add a list of files with a reference to a list of objects. | [
"Add",
"a",
"list",
"of",
"files",
"with",
"a",
"reference",
"to",
"a",
"list",
"of",
"objects",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/filemap.py#L212-L224 | train | Add a list of files with a reference to a list of objects. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersExperiment.setup | def setup(self):
"""First time setup."""
super(RogersExperiment, self).setup()
for net in random.sample(self.networks(role="experiment"),
self.catch_repeats):
net.role = "catch"
for net in self.networks():
source = RogersSource(n... | python | def setup(self):
"""First time setup."""
super(RogersExperiment, self).setup()
for net in random.sample(self.networks(role="experiment"),
self.catch_repeats):
net.role = "catch"
for net in self.networks():
source = RogersSource(n... | [
"def",
"setup",
"(",
"self",
")",
":",
"super",
"(",
"RogersExperiment",
",",
"self",
")",
".",
"setup",
"(",
")",
"for",
"net",
"in",
"random",
".",
"sample",
"(",
"self",
".",
"networks",
"(",
"role",
"=",
"\"experiment\"",
")",
",",
"self",
".",
... | First time setup. | [
"First",
"time",
"setup",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L40-L61 | train | First time setup. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersExperiment.create_node | def create_node(self, network, participant):
"""Make a new node for participants."""
if network.role == "practice" or network.role == "catch":
return RogersAgentFounder(network=network, participant=participant)
elif network.size(type=Agent) < network.generation_size:
retu... | python | def create_node(self, network, participant):
"""Make a new node for participants."""
if network.role == "practice" or network.role == "catch":
return RogersAgentFounder(network=network, participant=participant)
elif network.size(type=Agent) < network.generation_size:
retu... | [
"def",
"create_node",
"(",
"self",
",",
"network",
",",
"participant",
")",
":",
"if",
"network",
".",
"role",
"==",
"\"practice\"",
"or",
"network",
".",
"role",
"==",
"\"catch\"",
":",
"return",
"RogersAgentFounder",
"(",
"network",
"=",
"network",
",",
... | Make a new node for participants. | [
"Make",
"a",
"new",
"node",
"for",
"participants",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L69-L76 | train | Make a new node for participants. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersExperiment.submission_successful | def submission_successful(self, participant):
"""Run when a participant submits successfully."""
key = participant.uniqueid[0:5]
finished_participants = Participant.query.filter_by(status=101).all()
num_finished_participants = len(finished_participants)
current_generation = int(... | python | def submission_successful(self, participant):
"""Run when a participant submits successfully."""
key = participant.uniqueid[0:5]
finished_participants = Participant.query.filter_by(status=101).all()
num_finished_participants = len(finished_participants)
current_generation = int(... | [
"def",
"submission_successful",
"(",
"self",
",",
"participant",
")",
":",
"key",
"=",
"participant",
".",
"uniqueid",
"[",
"0",
":",
"5",
"]",
"finished_participants",
"=",
"Participant",
".",
"query",
".",
"filter_by",
"(",
"status",
"=",
"101",
")",
"."... | Run when a participant submits successfully. | [
"Run",
"when",
"a",
"participant",
"submits",
"successfully",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L82-L104 | train | Run when a participant submits successfully. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersExperiment.recruit | def recruit(self):
"""Recruit more participants."""
participants = Participant.query.\
with_entities(Participant.status).all()
# if all networks are full, close recruitment,
if not self.networks(full=False):
print "All networks are full, closing recruitment."
... | python | def recruit(self):
"""Recruit more participants."""
participants = Participant.query.\
with_entities(Participant.status).all()
# if all networks are full, close recruitment,
if not self.networks(full=False):
print "All networks are full, closing recruitment."
... | [
"def",
"recruit",
"(",
"self",
")",
":",
"participants",
"=",
"Participant",
".",
"query",
".",
"with_entities",
"(",
"Participant",
".",
"status",
")",
".",
"all",
"(",
")",
"# if all networks are full, close recruitment,",
"if",
"not",
"self",
".",
"networks",... | Recruit more participants. | [
"Recruit",
"more",
"participants",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L106-L127 | train | Recruit more participants. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersExperiment.bonus | def bonus(self, participant=None):
"""Calculate a participants bonus."""
if participant is None:
raise(ValueError("You must specify the participant to \
calculate the bonus."))
participant_id = participant.uniqueid
key = participant_id[0:5]
... | python | def bonus(self, participant=None):
"""Calculate a participants bonus."""
if participant is None:
raise(ValueError("You must specify the participant to \
calculate the bonus."))
participant_id = participant.uniqueid
key = participant_id[0:5]
... | [
"def",
"bonus",
"(",
"self",
",",
"participant",
"=",
"None",
")",
":",
"if",
"participant",
"is",
"None",
":",
"raise",
"(",
"ValueError",
"(",
"\"You must specify the participant to \\\n calculate the bonus.\"",
")",
")",
"participant_id",
... | Calculate a participants bonus. | [
"Calculate",
"a",
"participants",
"bonus",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L129-L150 | train | Calculate a participants bonus. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersExperiment.attention_check | def attention_check(self, participant=None):
"""Check a participant paid attention."""
participant_nodes = Node.query.join(Node.network)\
.filter(and_(Node.participant_id == participant.uniqueid,
Network.role == "catch"))\
.all()
scores = [n.score... | python | def attention_check(self, participant=None):
"""Check a participant paid attention."""
participant_nodes = Node.query.join(Node.network)\
.filter(and_(Node.participant_id == participant.uniqueid,
Network.role == "catch"))\
.all()
scores = [n.score... | [
"def",
"attention_check",
"(",
"self",
",",
"participant",
"=",
"None",
")",
":",
"participant_nodes",
"=",
"Node",
".",
"query",
".",
"join",
"(",
"Node",
".",
"network",
")",
".",
"filter",
"(",
"and_",
"(",
"Node",
".",
"participant_id",
"==",
"partic... | Check a participant paid attention. | [
"Check",
"a",
"participant",
"paid",
"attention",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L152-L166 | train | Check a participant paid attention. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersExperiment.data_check | def data_check(self, participant):
"""Check a participants data."""
participant_id = participant.uniqueid
nodes = Node.query.filter_by(participant_id=participant_id).all()
if len(nodes) != self.experiment_repeats + self.practice_repeats:
print("Error: Participant has {} nod... | python | def data_check(self, participant):
"""Check a participants data."""
participant_id = participant.uniqueid
nodes = Node.query.filter_by(participant_id=participant_id).all()
if len(nodes) != self.experiment_repeats + self.practice_repeats:
print("Error: Participant has {} nod... | [
"def",
"data_check",
"(",
"self",
",",
"participant",
")",
":",
"participant_id",
"=",
"participant",
".",
"uniqueid",
"nodes",
"=",
"Node",
".",
"query",
".",
"filter_by",
"(",
"participant_id",
"=",
"participant_id",
")",
".",
"all",
"(",
")",
"if",
"len... | Check a participants data. | [
"Check",
"a",
"participants",
"data",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L168-L194 | train | Check a participants data. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersExperiment.add_node_to_network | def add_node_to_network(self, node, network):
"""Add participant's node to a network."""
network.add_node(node)
node.receive()
environment = network.nodes(type=Environment)[0]
environment.connect(whom=node)
gene = node.infos(type=LearningGene)[0].contents
if (ge... | python | def add_node_to_network(self, node, network):
"""Add participant's node to a network."""
network.add_node(node)
node.receive()
environment = network.nodes(type=Environment)[0]
environment.connect(whom=node)
gene = node.infos(type=LearningGene)[0].contents
if (ge... | [
"def",
"add_node_to_network",
"(",
"self",
",",
"node",
",",
"network",
")",
":",
"network",
".",
"add_node",
"(",
"node",
")",
"node",
".",
"receive",
"(",
")",
"environment",
"=",
"network",
".",
"nodes",
"(",
"type",
"=",
"Environment",
")",
"[",
"0... | Add participant's node to a network. | [
"Add",
"participant",
"s",
"node",
"to",
"a",
"network",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L196-L219 | train | Add participant s node to a network. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersAgent.calculate_fitness | def calculate_fitness(self):
"""Calculcate your fitness."""
if self.fitness is not None:
raise Exception("You are calculating the fitness of agent {}, "
.format(self.id) +
"but they already have a fitness")
infos = self.infos()
... | python | def calculate_fitness(self):
"""Calculcate your fitness."""
if self.fitness is not None:
raise Exception("You are calculating the fitness of agent {}, "
.format(self.id) +
"but they already have a fitness")
infos = self.infos()
... | [
"def",
"calculate_fitness",
"(",
"self",
")",
":",
"if",
"self",
".",
"fitness",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"You are calculating the fitness of agent {}, \"",
".",
"format",
"(",
"self",
".",
"id",
")",
"+",
"\"but they already have a f... | Calculcate your fitness. | [
"Calculcate",
"your",
"fitness",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L299-L328 | train | Calculates the fitness of the agent. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersAgent.update | def update(self, infos):
"""Process received infos."""
for info_in in infos:
if isinstance(info_in, LearningGene):
if random.random() < 0.10:
self.mutate(info_in)
else:
self.replicate(info_in) | python | def update(self, infos):
"""Process received infos."""
for info_in in infos:
if isinstance(info_in, LearningGene):
if random.random() < 0.10:
self.mutate(info_in)
else:
self.replicate(info_in) | [
"def",
"update",
"(",
"self",
",",
"infos",
")",
":",
"for",
"info_in",
"in",
"infos",
":",
"if",
"isinstance",
"(",
"info_in",
",",
"LearningGene",
")",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"0.10",
":",
"self",
".",
"mutate",
"(",
"i... | Process received infos. | [
"Process",
"received",
"infos",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L330-L337 | train | Process received infos. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersAgentFounder.update | def update(self, infos):
"""Process received infos."""
for info in infos:
if isinstance(info, LearningGene):
self.replicate(info) | python | def update(self, infos):
"""Process received infos."""
for info in infos:
if isinstance(info, LearningGene):
self.replicate(info) | [
"def",
"update",
"(",
"self",
",",
"infos",
")",
":",
"for",
"info",
"in",
"infos",
":",
"if",
"isinstance",
"(",
"info",
",",
"LearningGene",
")",
":",
"self",
".",
"replicate",
"(",
"info",
")"
] | Process received infos. | [
"Process",
"received",
"infos",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L351-L355 | train | Process received infos. |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | RogersEnvironment.create_state | def create_state(self, proportion):
"""Create an environmental state."""
if random.random() < 0.5:
proportion = 1 - proportion
State(origin=self, contents=proportion) | python | def create_state(self, proportion):
"""Create an environmental state."""
if random.random() < 0.5:
proportion = 1 - proportion
State(origin=self, contents=proportion) | [
"def",
"create_state",
"(",
"self",
",",
"proportion",
")",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"0.5",
":",
"proportion",
"=",
"1",
"-",
"proportion",
"State",
"(",
"origin",
"=",
"self",
",",
"contents",
"=",
"proportion",
")"
] | Create an environmental state. | [
"Create",
"an",
"environmental",
"state",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L363-L367 | train | Create an environmental state. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.