repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Kortemme-Lab/klab | klab/bio/fasta.py | FASTA.get_sequences | def get_sequences(self, pdb_id = None):
'''Create Sequence objects for each FASTA sequence.'''
sequences = {}
if pdb_id:
for chain_id, sequence in self.get(pdb_id, {}).iteritems():
sequences[chain_id] = Sequence.from_sequence(chain_id, sequence)
else:
... | python | def get_sequences(self, pdb_id = None):
'''Create Sequence objects for each FASTA sequence.'''
sequences = {}
if pdb_id:
for chain_id, sequence in self.get(pdb_id, {}).iteritems():
sequences[chain_id] = Sequence.from_sequence(chain_id, sequence)
else:
... | [
"def",
"get_sequences",
"(",
"self",
",",
"pdb_id",
"=",
"None",
")",
":",
"sequences",
"=",
"{",
"}",
"if",
"pdb_id",
":",
"for",
"chain_id",
",",
"sequence",
"in",
"self",
".",
"get",
"(",
"pdb_id",
",",
"{",
"}",
")",
".",
"iteritems",
"(",
")",... | Create Sequence objects for each FASTA sequence. | [
"Create",
"Sequence",
"objects",
"for",
"each",
"FASTA",
"sequence",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/fasta.py#L175-L186 | train |
Kortemme-Lab/klab | klab/bio/fasta.py | FASTA.get_chain_ids | def get_chain_ids(self, pdb_id = None, safe_call = False):
'''If the FASTA file only has one PDB ID, pdb_id does not need to be specified. Otherwise, the list of chains identifiers for pdb_id is returned.'''
if pdb_id == None and len(self.keys()) == 1:
return self[self.keys()[0]].keys()
... | python | def get_chain_ids(self, pdb_id = None, safe_call = False):
'''If the FASTA file only has one PDB ID, pdb_id does not need to be specified. Otherwise, the list of chains identifiers for pdb_id is returned.'''
if pdb_id == None and len(self.keys()) == 1:
return self[self.keys()[0]].keys()
... | [
"def",
"get_chain_ids",
"(",
"self",
",",
"pdb_id",
"=",
"None",
",",
"safe_call",
"=",
"False",
")",
":",
"if",
"pdb_id",
"==",
"None",
"and",
"len",
"(",
"self",
".",
"keys",
"(",
")",
")",
"==",
"1",
":",
"return",
"self",
"[",
"self",
".",
"k... | If the FASTA file only has one PDB ID, pdb_id does not need to be specified. Otherwise, the list of chains identifiers for pdb_id is returned. | [
"If",
"the",
"FASTA",
"file",
"only",
"has",
"one",
"PDB",
"ID",
"pdb_id",
"does",
"not",
"need",
"to",
"be",
"specified",
".",
"Otherwise",
"the",
"list",
"of",
"chains",
"identifiers",
"for",
"pdb_id",
"is",
"returned",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/fasta.py#L191-L203 | train |
Kortemme-Lab/klab | klab/bio/fasta.py | FASTA.match | def match(self, other):
''' This is a noisy terminal-printing function at present since there is no need to make it a proper API function.'''
colortext.message("FASTA Match")
for frompdbID, fromchains in sorted(self.iteritems()):
matched_pdbs = {}
matched_chains = {}
... | python | def match(self, other):
''' This is a noisy terminal-printing function at present since there is no need to make it a proper API function.'''
colortext.message("FASTA Match")
for frompdbID, fromchains in sorted(self.iteritems()):
matched_pdbs = {}
matched_chains = {}
... | [
"def",
"match",
"(",
"self",
",",
"other",
")",
":",
"colortext",
".",
"message",
"(",
"\"FASTA Match\"",
")",
"for",
"frompdbID",
",",
"fromchains",
"in",
"sorted",
"(",
"self",
".",
"iteritems",
"(",
")",
")",
":",
"matched_pdbs",
"=",
"{",
"}",
"mat... | This is a noisy terminal-printing function at present since there is no need to make it a proper API function. | [
"This",
"is",
"a",
"noisy",
"terminal",
"-",
"printing",
"function",
"at",
"present",
"since",
"there",
"is",
"no",
"need",
"to",
"make",
"it",
"a",
"proper",
"API",
"function",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/fasta.py#L205-L235 | train |
uw-it-aca/uw-restclients-sws | uw_sws/person.py | _process_json_data | def _process_json_data(person_data):
"""
Returns a uw_sws.models.SwsPerson object
"""
person = SwsPerson()
if person_data["BirthDate"]:
person.birth_date = parse(person_data["BirthDate"]).date()
person.directory_release = person_data["DirectoryRelease"]
person.email = person_data["Em... | python | def _process_json_data(person_data):
"""
Returns a uw_sws.models.SwsPerson object
"""
person = SwsPerson()
if person_data["BirthDate"]:
person.birth_date = parse(person_data["BirthDate"]).date()
person.directory_release = person_data["DirectoryRelease"]
person.email = person_data["Em... | [
"def",
"_process_json_data",
"(",
"person_data",
")",
":",
"person",
"=",
"SwsPerson",
"(",
")",
"if",
"person_data",
"[",
"\"BirthDate\"",
"]",
":",
"person",
".",
"birth_date",
"=",
"parse",
"(",
"person_data",
"[",
"\"BirthDate\"",
"]",
")",
".",
"date",
... | Returns a uw_sws.models.SwsPerson object | [
"Returns",
"a",
"uw_sws",
".",
"models",
".",
"SwsPerson",
"object"
] | 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/person.py#L23-L78 | train |
uw-it-aca/uw-restclients-sws | uw_sws/dao.py | SWS_DAO._make_notice_date | def _make_notice_date(self, response):
"""
Set the date attribte value in the notice mock data
"""
today = date.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
week = today + timedelta(days=2)
next_week = today + timedelt... | python | def _make_notice_date(self, response):
"""
Set the date attribte value in the notice mock data
"""
today = date.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
week = today + timedelta(days=2)
next_week = today + timedelt... | [
"def",
"_make_notice_date",
"(",
"self",
",",
"response",
")",
":",
"today",
"=",
"date",
".",
"today",
"(",
")",
"yesterday",
"=",
"today",
"-",
"timedelta",
"(",
"days",
"=",
"1",
")",
"tomorrow",
"=",
"today",
"+",
"timedelta",
"(",
"days",
"=",
"... | Set the date attribte value in the notice mock data | [
"Set",
"the",
"date",
"attribte",
"value",
"in",
"the",
"notice",
"mock",
"data"
] | 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/dao.py#L64-L99 | train |
Kortemme-Lab/klab | klab/scripting.py | relative_symlink | def relative_symlink(target, link_name):
"""Make a symlink to target using the shortest possible relative path."""
link_name = os.path.abspath(link_name)
abs_target = os.path.abspath(target)
rel_target = os.path.relpath(target, os.path.dirname(link_name))
if os.path.exists(link_name):
os.re... | python | def relative_symlink(target, link_name):
"""Make a symlink to target using the shortest possible relative path."""
link_name = os.path.abspath(link_name)
abs_target = os.path.abspath(target)
rel_target = os.path.relpath(target, os.path.dirname(link_name))
if os.path.exists(link_name):
os.re... | [
"def",
"relative_symlink",
"(",
"target",
",",
"link_name",
")",
":",
"link_name",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"link_name",
")",
"abs_target",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"target",
")",
"rel_target",
"=",
"os",
".",
"p... | Make a symlink to target using the shortest possible relative path. | [
"Make",
"a",
"symlink",
"to",
"target",
"using",
"the",
"shortest",
"possible",
"relative",
"path",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/scripting.py#L57-L65 | train |
ethan92429/onshapepy | onshapepy/part.py | Part.params | def params(self, dict):
"""Set configuration variables for an OnShape part."""
self._configuration.update(dict)
self._measurements.update() | python | def params(self, dict):
"""Set configuration variables for an OnShape part."""
self._configuration.update(dict)
self._measurements.update() | [
"def",
"params",
"(",
"self",
",",
"dict",
")",
":",
"self",
".",
"_configuration",
".",
"update",
"(",
"dict",
")",
"self",
".",
"_measurements",
".",
"update",
"(",
")"
] | Set configuration variables for an OnShape part. | [
"Set",
"configuration",
"variables",
"for",
"an",
"OnShape",
"part",
"."
] | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/part.py#L52-L55 | train |
ethan92429/onshapepy | onshapepy/part.py | Configuration.update | def update(self, params=None, client=c):
"""Push params to OnShape and synchronize the local copy
"""
uri = self.parent.uri
if not params or not self.res:
self.get_params()
return
d = self.payload
for k, v in params.items():
m = d["curr... | python | def update(self, params=None, client=c):
"""Push params to OnShape and synchronize the local copy
"""
uri = self.parent.uri
if not params or not self.res:
self.get_params()
return
d = self.payload
for k, v in params.items():
m = d["curr... | [
"def",
"update",
"(",
"self",
",",
"params",
"=",
"None",
",",
"client",
"=",
"c",
")",
":",
"uri",
"=",
"self",
".",
"parent",
".",
"uri",
"if",
"not",
"params",
"or",
"not",
"self",
".",
"res",
":",
"self",
".",
"get_params",
"(",
")",
"return"... | Push params to OnShape and synchronize the local copy | [
"Push",
"params",
"to",
"OnShape",
"and",
"synchronize",
"the",
"local",
"copy"
] | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/part.py#L72-L94 | train |
ethan92429/onshapepy | onshapepy/part.py | Configuration.get_params | def get_params(self):
"""Manually pull params defined in config from OnShape and return a python representation of the params.
Quantities are converted to pint quantities, Bools are converted to python bools and Enums are converted
to strings. Note that Enum names are autogenerated by OnShape an... | python | def get_params(self):
"""Manually pull params defined in config from OnShape and return a python representation of the params.
Quantities are converted to pint quantities, Bools are converted to python bools and Enums are converted
to strings. Note that Enum names are autogenerated by OnShape an... | [
"def",
"get_params",
"(",
"self",
")",
":",
"self",
".",
"res",
"=",
"c",
".",
"get_configuration",
"(",
"self",
".",
"parent",
".",
"uri",
".",
"as_dict",
"(",
")",
")"
] | Manually pull params defined in config from OnShape and return a python representation of the params.
Quantities are converted to pint quantities, Bools are converted to python bools and Enums are converted
to strings. Note that Enum names are autogenerated by OnShape and do not match the name on the On... | [
"Manually",
"pull",
"params",
"defined",
"in",
"config",
"from",
"OnShape",
"and",
"return",
"a",
"python",
"representation",
"of",
"the",
"params",
".",
"Quantities",
"are",
"converted",
"to",
"pint",
"quantities",
"Bools",
"are",
"converted",
"to",
"python",
... | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/part.py#L96-L100 | train |
ethan92429/onshapepy | onshapepy/part.py | Configuration.params | def params(self):
"""Get the params of response data from the API.
Returns:
- d (dict): Dictionary mapping of all configuration values
"""
payload = self.payload
d = {}
for i, p in enumerate(payload["currentConfiguration"]):
type_name = p["typeNam... | python | def params(self):
"""Get the params of response data from the API.
Returns:
- d (dict): Dictionary mapping of all configuration values
"""
payload = self.payload
d = {}
for i, p in enumerate(payload["currentConfiguration"]):
type_name = p["typeNam... | [
"def",
"params",
"(",
"self",
")",
":",
"payload",
"=",
"self",
".",
"payload",
"d",
"=",
"{",
"}",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"payload",
"[",
"\"currentConfiguration\"",
"]",
")",
":",
"type_name",
"=",
"p",
"[",
"\"typeName\"",
"... | Get the params of response data from the API.
Returns:
- d (dict): Dictionary mapping of all configuration values | [
"Get",
"the",
"params",
"of",
"response",
"data",
"from",
"the",
"API",
"."
] | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/part.py#L103-L127 | train |
ethan92429/onshapepy | onshapepy/part.py | Measurements.update | def update(self):
""" Update all local variable names to match OnShape. """
uri = self.parent.uri
script = r"""
function(context, queries) {
return getVariable(context, "measurements");
}
"""
self.res = c.evaluate_featurescript(uri.as_dict(), script) | python | def update(self):
""" Update all local variable names to match OnShape. """
uri = self.parent.uri
script = r"""
function(context, queries) {
return getVariable(context, "measurements");
}
"""
self.res = c.evaluate_featurescript(uri.as_dict(), script) | [
"def",
"update",
"(",
"self",
")",
":",
"uri",
"=",
"self",
".",
"parent",
".",
"uri",
"script",
"=",
"r",
"self",
".",
"res",
"=",
"c",
".",
"evaluate_featurescript",
"(",
"uri",
".",
"as_dict",
"(",
")",
",",
"script",
")"
] | Update all local variable names to match OnShape. | [
"Update",
"all",
"local",
"variable",
"names",
"to",
"match",
"OnShape",
"."
] | 61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/part.py#L146-L155 | train |
Kortemme-Lab/klab | klab/retrospect.py | LogReader.getFailedJobIDs | def getFailedJobIDs(self, extraLapse = TYPICAL_LAPSE):
'''Returns a list of which identify failed jobs in the scriptsRun table.
If a time stamp for a job can be found, we return this. The time stamp can be used to index the log.
If no time stamp was found, return the name of the script instead.
'''
scripts... | python | def getFailedJobIDs(self, extraLapse = TYPICAL_LAPSE):
'''Returns a list of which identify failed jobs in the scriptsRun table.
If a time stamp for a job can be found, we return this. The time stamp can be used to index the log.
If no time stamp was found, return the name of the script instead.
'''
scripts... | [
"def",
"getFailedJobIDs",
"(",
"self",
",",
"extraLapse",
"=",
"TYPICAL_LAPSE",
")",
":",
"scriptsRun",
"=",
"self",
".",
"scriptsRun",
"failedJobTimestamps",
"=",
"[",
"]",
"nodata",
"=",
"[",
"]",
"for",
"name",
",",
"details",
"in",
"sorted",
"(",
"scri... | Returns a list of which identify failed jobs in the scriptsRun table.
If a time stamp for a job can be found, we return this. The time stamp can be used to index the log.
If no time stamp was found, return the name of the script instead. | [
"Returns",
"a",
"list",
"of",
"which",
"identify",
"failed",
"jobs",
"in",
"the",
"scriptsRun",
"table",
".",
"If",
"a",
"time",
"stamp",
"for",
"a",
"job",
"can",
"be",
"found",
"we",
"return",
"this",
".",
"The",
"time",
"stamp",
"can",
"be",
"used",... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/retrospect.py#L302-L331 | train |
Kortemme-Lab/klab | klab/retrospect.py | LogReader.generateSummaryHTMLTable | def generateSummaryHTMLTable(self, extraLapse = TYPICAL_LAPSE):
'''Generates a summary in HTML of the status of the expected scripts broken based on the log.
This summary is returned as a list of strings.
'''
scriptsRun = self.scriptsRun
html = []
html.append("<table style='text-align:center;border:1px... | python | def generateSummaryHTMLTable(self, extraLapse = TYPICAL_LAPSE):
'''Generates a summary in HTML of the status of the expected scripts broken based on the log.
This summary is returned as a list of strings.
'''
scriptsRun = self.scriptsRun
html = []
html.append("<table style='text-align:center;border:1px... | [
"def",
"generateSummaryHTMLTable",
"(",
"self",
",",
"extraLapse",
"=",
"TYPICAL_LAPSE",
")",
":",
"scriptsRun",
"=",
"self",
".",
"scriptsRun",
"html",
"=",
"[",
"]",
"html",
".",
"append",
"(",
"\"<table style='text-align:center;border:1px solid black;margin-left: aut... | Generates a summary in HTML of the status of the expected scripts broken based on the log.
This summary is returned as a list of strings. | [
"Generates",
"a",
"summary",
"in",
"HTML",
"of",
"the",
"status",
"of",
"the",
"expected",
"scripts",
"broken",
"based",
"on",
"the",
"log",
".",
"This",
"summary",
"is",
"returned",
"as",
"a",
"list",
"of",
"strings",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/retrospect.py#L411-L482 | train |
TheGhouls/oct | oct/tools/results_to_csv.py | to_csv | def to_csv(args):
"""Take a sqlite filled database of results and return a csv file
:param str result_file: the path of the sqlite database
:param str output_file: the path of the csv output file
:param str delimiter: the desired delimiter for the output csv file
"""
result_file = args.result_f... | python | def to_csv(args):
"""Take a sqlite filled database of results and return a csv file
:param str result_file: the path of the sqlite database
:param str output_file: the path of the csv output file
:param str delimiter: the desired delimiter for the output csv file
"""
result_file = args.result_f... | [
"def",
"to_csv",
"(",
"args",
")",
":",
"result_file",
"=",
"args",
".",
"result_file",
"output_file",
"=",
"args",
".",
"output_file",
"delimiter",
"=",
"args",
".",
"delimiter",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"result_file",
")",
":... | Take a sqlite filled database of results and return a csv file
:param str result_file: the path of the sqlite database
:param str output_file: the path of the csv output file
:param str delimiter: the desired delimiter for the output csv file | [
"Take",
"a",
"sqlite",
"filled",
"database",
"of",
"results",
"and",
"return",
"a",
"csv",
"file"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/tools/results_to_csv.py#L8-L49 | train |
Kortemme-Lab/klab | klab/stats/misc.py | fraction_correct_fuzzy_linear_create_vector | def fraction_correct_fuzzy_linear_create_vector(z, z_cutoff, z_fuzzy_range):
'''A helper function for fraction_correct_fuzzy_linear.'''
assert(z_fuzzy_range * 2 < z_cutoff)
if (z == None or numpy.isnan(z)): # todo: and ignore_null_values: # If we are missing values then we either discount the case or consi... | python | def fraction_correct_fuzzy_linear_create_vector(z, z_cutoff, z_fuzzy_range):
'''A helper function for fraction_correct_fuzzy_linear.'''
assert(z_fuzzy_range * 2 < z_cutoff)
if (z == None or numpy.isnan(z)): # todo: and ignore_null_values: # If we are missing values then we either discount the case or consi... | [
"def",
"fraction_correct_fuzzy_linear_create_vector",
"(",
"z",
",",
"z_cutoff",
",",
"z_fuzzy_range",
")",
":",
"assert",
"(",
"z_fuzzy_range",
"*",
"2",
"<",
"z_cutoff",
")",
"if",
"(",
"z",
"==",
"None",
"or",
"numpy",
".",
"isnan",
"(",
"z",
")",
")",
... | A helper function for fraction_correct_fuzzy_linear. | [
"A",
"helper",
"function",
"for",
"fraction_correct_fuzzy_linear",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/stats/misc.py#L113-L135 | train |
Kortemme-Lab/klab | klab/cloning/gen9.py | apply_quality_control_checks | def apply_quality_control_checks(
seq,
check_gen9_seqs=True,
check_short_length=True,
check_local_gc_content=True,
check_global_gc_content=True):
"""
Raise a ValueError if the given sequence doesn't pass all of the Gen9
quality control design guidelines. Certain che... | python | def apply_quality_control_checks(
seq,
check_gen9_seqs=True,
check_short_length=True,
check_local_gc_content=True,
check_global_gc_content=True):
"""
Raise a ValueError if the given sequence doesn't pass all of the Gen9
quality control design guidelines. Certain che... | [
"def",
"apply_quality_control_checks",
"(",
"seq",
",",
"check_gen9_seqs",
"=",
"True",
",",
"check_short_length",
"=",
"True",
",",
"check_local_gc_content",
"=",
"True",
",",
"check_global_gc_content",
"=",
"True",
")",
":",
"seq",
"=",
"seq",
".",
"upper",
"(... | Raise a ValueError if the given sequence doesn't pass all of the Gen9
quality control design guidelines. Certain checks can be enabled or
disabled via the command line. | [
"Raise",
"a",
"ValueError",
"if",
"the",
"given",
"sequence",
"doesn",
"t",
"pass",
"all",
"of",
"the",
"Gen9",
"quality",
"control",
"design",
"guidelines",
".",
"Certain",
"checks",
"can",
"be",
"enabled",
"or",
"disabled",
"via",
"the",
"command",
"line",... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/cloning/gen9.py#L17-L90 | train |
Dapid/tmscoring | tmscoring/tmscore.py | Aligning.get_default_values | def get_default_values(self):
"""
Make a crude estimation of the alignment using the center of mass
and general C->N orientation.
"""
out = dict(dx=0, dy=0, dz=0, theta=0, phi=0, psi=0)
dx, dy, dz, _ = np.mean(self.coord1 - self.coord2, axis=1)
out['dx'] = dx
... | python | def get_default_values(self):
"""
Make a crude estimation of the alignment using the center of mass
and general C->N orientation.
"""
out = dict(dx=0, dy=0, dz=0, theta=0, phi=0, psi=0)
dx, dy, dz, _ = np.mean(self.coord1 - self.coord2, axis=1)
out['dx'] = dx
... | [
"def",
"get_default_values",
"(",
"self",
")",
":",
"out",
"=",
"dict",
"(",
"dx",
"=",
"0",
",",
"dy",
"=",
"0",
",",
"dz",
"=",
"0",
",",
"theta",
"=",
"0",
",",
"phi",
"=",
"0",
",",
"psi",
"=",
"0",
")",
"dx",
",",
"dy",
",",
"dz",
",... | Make a crude estimation of the alignment using the center of mass
and general C->N orientation. | [
"Make",
"a",
"crude",
"estimation",
"of",
"the",
"alignment",
"using",
"the",
"center",
"of",
"mass",
"and",
"general",
"C",
"-",
">",
"N",
"orientation",
"."
] | 353c567e201ee9835c8209f6130b80b1cfb5b10f | https://github.com/Dapid/tmscoring/blob/353c567e201ee9835c8209f6130b80b1cfb5b10f/tmscoring/tmscore.py#L45-L81 | train |
Dapid/tmscoring | tmscoring/tmscore.py | Aligning.get_matrix | def get_matrix(theta, phi, psi, dx, dy, dz,
matrix=np.zeros((4, 4), dtype=DTYPE),
angles=np.zeros(3, dtype=DTYPE)):
"""
Build the rotation-translation matrix.
It has the form:
[ | dx ]
[ R | dy ]
[ | dz ]
... | python | def get_matrix(theta, phi, psi, dx, dy, dz,
matrix=np.zeros((4, 4), dtype=DTYPE),
angles=np.zeros(3, dtype=DTYPE)):
"""
Build the rotation-translation matrix.
It has the form:
[ | dx ]
[ R | dy ]
[ | dz ]
... | [
"def",
"get_matrix",
"(",
"theta",
",",
"phi",
",",
"psi",
",",
"dx",
",",
"dy",
",",
"dz",
",",
"matrix",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"4",
")",
",",
"dtype",
"=",
"DTYPE",
")",
",",
"angles",
"=",
"np",
".",
"zeros",
"(",
... | Build the rotation-translation matrix.
It has the form:
[ | dx ]
[ R | dy ]
[ | dz ]
[ 0 0 0 | 1 ] | [
"Build",
"the",
"rotation",
"-",
"translation",
"matrix",
"."
] | 353c567e201ee9835c8209f6130b80b1cfb5b10f | https://github.com/Dapid/tmscoring/blob/353c567e201ee9835c8209f6130b80b1cfb5b10f/tmscoring/tmscore.py#L84-L118 | train |
Dapid/tmscoring | tmscoring/tmscore.py | Aligning._tm | def _tm(self, theta, phi, psi, dx, dy, dz):
"""
Compute the minimisation target, not normalised.
"""
matrix = self.get_matrix(theta, phi, psi, dx, dy, dz)
coord = matrix.dot(self.coord2)
dist = coord - self.coord1
d_i2 = (dist * dist).sum(axis=0)
tm = -(... | python | def _tm(self, theta, phi, psi, dx, dy, dz):
"""
Compute the minimisation target, not normalised.
"""
matrix = self.get_matrix(theta, phi, psi, dx, dy, dz)
coord = matrix.dot(self.coord2)
dist = coord - self.coord1
d_i2 = (dist * dist).sum(axis=0)
tm = -(... | [
"def",
"_tm",
"(",
"self",
",",
"theta",
",",
"phi",
",",
"psi",
",",
"dx",
",",
"dy",
",",
"dz",
")",
":",
"matrix",
"=",
"self",
".",
"get_matrix",
"(",
"theta",
",",
"phi",
",",
"psi",
",",
"dx",
",",
"dy",
",",
"dz",
")",
"coord",
"=",
... | Compute the minimisation target, not normalised. | [
"Compute",
"the",
"minimisation",
"target",
"not",
"normalised",
"."
] | 353c567e201ee9835c8209f6130b80b1cfb5b10f | https://github.com/Dapid/tmscoring/blob/353c567e201ee9835c8209f6130b80b1cfb5b10f/tmscoring/tmscore.py#L138-L150 | train |
Dapid/tmscoring | tmscoring/tmscore.py | Aligning.write | def write(self, outputfile='out.pdb', appended=False):
"""
Save the second PDB file aligned to the first.
If appended is True, both are saved as different chains.
"""
# FIXME some cases don't work.
matrix = self.get_matrix(**self.get_current_values())
out = open... | python | def write(self, outputfile='out.pdb', appended=False):
"""
Save the second PDB file aligned to the first.
If appended is True, both are saved as different chains.
"""
# FIXME some cases don't work.
matrix = self.get_matrix(**self.get_current_values())
out = open... | [
"def",
"write",
"(",
"self",
",",
"outputfile",
"=",
"'out.pdb'",
",",
"appended",
"=",
"False",
")",
":",
"matrix",
"=",
"self",
".",
"get_matrix",
"(",
"**",
"self",
".",
"get_current_values",
"(",
")",
")",
"out",
"=",
"open",
"(",
"outputfile",
","... | Save the second PDB file aligned to the first.
If appended is True, both are saved as different chains. | [
"Save",
"the",
"second",
"PDB",
"file",
"aligned",
"to",
"the",
"first",
"."
] | 353c567e201ee9835c8209f6130b80b1cfb5b10f | https://github.com/Dapid/tmscoring/blob/353c567e201ee9835c8209f6130b80b1cfb5b10f/tmscoring/tmscore.py#L187-L228 | train |
Dapid/tmscoring | tmscoring/tmscore.py | Aligning._load_data_alignment | def _load_data_alignment(self, chain1, chain2):
"""
Extract the sequences from the PDB file, perform the alignment,
and load the coordinates of the CA of the common residues.
"""
parser = PDB.PDBParser(QUIET=True)
ppb = PDB.PPBuilder()
structure1 = parser.get_str... | python | def _load_data_alignment(self, chain1, chain2):
"""
Extract the sequences from the PDB file, perform the alignment,
and load the coordinates of the CA of the common residues.
"""
parser = PDB.PDBParser(QUIET=True)
ppb = PDB.PPBuilder()
structure1 = parser.get_str... | [
"def",
"_load_data_alignment",
"(",
"self",
",",
"chain1",
",",
"chain2",
")",
":",
"parser",
"=",
"PDB",
".",
"PDBParser",
"(",
"QUIET",
"=",
"True",
")",
"ppb",
"=",
"PDB",
".",
"PPBuilder",
"(",
")",
"structure1",
"=",
"parser",
".",
"get_structure",
... | Extract the sequences from the PDB file, perform the alignment,
and load the coordinates of the CA of the common residues. | [
"Extract",
"the",
"sequences",
"from",
"the",
"PDB",
"file",
"perform",
"the",
"alignment",
"and",
"load",
"the",
"coordinates",
"of",
"the",
"CA",
"of",
"the",
"common",
"residues",
"."
] | 353c567e201ee9835c8209f6130b80b1cfb5b10f | https://github.com/Dapid/tmscoring/blob/353c567e201ee9835c8209f6130b80b1cfb5b10f/tmscoring/tmscore.py#L230-L259 | train |
Dapid/tmscoring | tmscoring/tmscore.py | Aligning._load_data_index | def _load_data_index(self, chain1, chain2):
"""
Load the coordinates of the CA of the common residues.
"""
parser = PDB.PDBParser(QUIET=True)
structure1 = parser.get_structure(chain1, self.pdb1)
structure2 = parser.get_structure(chain2, self.pdb2)
residues1 = li... | python | def _load_data_index(self, chain1, chain2):
"""
Load the coordinates of the CA of the common residues.
"""
parser = PDB.PDBParser(QUIET=True)
structure1 = parser.get_structure(chain1, self.pdb1)
structure2 = parser.get_structure(chain2, self.pdb2)
residues1 = li... | [
"def",
"_load_data_index",
"(",
"self",
",",
"chain1",
",",
"chain2",
")",
":",
"parser",
"=",
"PDB",
".",
"PDBParser",
"(",
"QUIET",
"=",
"True",
")",
"structure1",
"=",
"parser",
".",
"get_structure",
"(",
"chain1",
",",
"self",
".",
"pdb1",
")",
"st... | Load the coordinates of the CA of the common residues. | [
"Load",
"the",
"coordinates",
"of",
"the",
"CA",
"of",
"the",
"common",
"residues",
"."
] | 353c567e201ee9835c8209f6130b80b1cfb5b10f | https://github.com/Dapid/tmscoring/blob/353c567e201ee9835c8209f6130b80b1cfb5b10f/tmscoring/tmscore.py#L261-L297 | train |
uw-it-aca/uw-restclients-sws | uw_sws/section_status.py | _json_to_sectionstatus | def _json_to_sectionstatus(section_data):
"""
Returns a uw_sws.models.SectionStatus object
created from the passed json.
"""
section_status = SectionStatus()
if section_data["AddCodeRequired"] == 'true':
section_status.add_code_required = True
else:
section_status.add_code_re... | python | def _json_to_sectionstatus(section_data):
"""
Returns a uw_sws.models.SectionStatus object
created from the passed json.
"""
section_status = SectionStatus()
if section_data["AddCodeRequired"] == 'true':
section_status.add_code_required = True
else:
section_status.add_code_re... | [
"def",
"_json_to_sectionstatus",
"(",
"section_data",
")",
":",
"section_status",
"=",
"SectionStatus",
"(",
")",
"if",
"section_data",
"[",
"\"AddCodeRequired\"",
"]",
"==",
"'true'",
":",
"section_status",
".",
"add_code_required",
"=",
"True",
"else",
":",
"sec... | Returns a uw_sws.models.SectionStatus object
created from the passed json. | [
"Returns",
"a",
"uw_sws",
".",
"models",
".",
"SectionStatus",
"object",
"created",
"from",
"the",
"passed",
"json",
"."
] | 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section_status.py#L21-L52 | train |
Kortemme-Lab/klab | klab/bio/pdb_util.py | renumber_atoms | def renumber_atoms(lines):
'''
Takes in a list of PDB lines and renumbers the atoms appropriately
'''
new_lines = []
current_number = 1
for line in lines:
if line.startswith('ATOM') or line.startswith('HETATM'):
new_lines.append(
line[:6] + string.rjust('%d' %... | python | def renumber_atoms(lines):
'''
Takes in a list of PDB lines and renumbers the atoms appropriately
'''
new_lines = []
current_number = 1
for line in lines:
if line.startswith('ATOM') or line.startswith('HETATM'):
new_lines.append(
line[:6] + string.rjust('%d' %... | [
"def",
"renumber_atoms",
"(",
"lines",
")",
":",
"new_lines",
"=",
"[",
"]",
"current_number",
"=",
"1",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"startswith",
"(",
"'ATOM'",
")",
"or",
"line",
".",
"startswith",
"(",
"'HETATM'",
")",
":",... | Takes in a list of PDB lines and renumbers the atoms appropriately | [
"Takes",
"in",
"a",
"list",
"of",
"PDB",
"lines",
"and",
"renumbers",
"the",
"atoms",
"appropriately"
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb_util.py#L30-L46 | train |
Kortemme-Lab/klab | klab/bio/pdb_util.py | clean_alternate_location_indicators | def clean_alternate_location_indicators(lines):
'''
Keeps only the first atom, if alternated location identifiers are being used
Removes alternate location ID charactor
'''
new_lines = []
previously_seen_alt_atoms = set()
for line in lines:
if line.startswith('ATOM'):
alt... | python | def clean_alternate_location_indicators(lines):
'''
Keeps only the first atom, if alternated location identifiers are being used
Removes alternate location ID charactor
'''
new_lines = []
previously_seen_alt_atoms = set()
for line in lines:
if line.startswith('ATOM'):
alt... | [
"def",
"clean_alternate_location_indicators",
"(",
"lines",
")",
":",
"new_lines",
"=",
"[",
"]",
"previously_seen_alt_atoms",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"startswith",
"(",
"'ATOM'",
")",
":",
"alt_loc_id",
"=... | Keeps only the first atom, if alternated location identifiers are being used
Removes alternate location ID charactor | [
"Keeps",
"only",
"the",
"first",
"atom",
"if",
"alternated",
"location",
"identifiers",
"are",
"being",
"used",
"Removes",
"alternate",
"location",
"ID",
"charactor"
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb_util.py#L48-L71 | train |
Kortemme-Lab/klab | klab/bio/ligand.py | Ligand.parse_pdb_ligand_info | def parse_pdb_ligand_info(self, pdb_ligand_info):
'''This only parses the ligand type as all the other information should be in the .cif file. The XML file has
proper capitalization whereas the .cif file uses all caps for the ligand type.'''
mtchs = re.findall('(<ligand.*?</ligand>)', pdb_lig... | python | def parse_pdb_ligand_info(self, pdb_ligand_info):
'''This only parses the ligand type as all the other information should be in the .cif file. The XML file has
proper capitalization whereas the .cif file uses all caps for the ligand type.'''
mtchs = re.findall('(<ligand.*?</ligand>)', pdb_lig... | [
"def",
"parse_pdb_ligand_info",
"(",
"self",
",",
"pdb_ligand_info",
")",
":",
"mtchs",
"=",
"re",
".",
"findall",
"(",
"'(<ligand.*?</ligand>)'",
",",
"pdb_ligand_info",
",",
"re",
".",
"DOTALL",
")",
"for",
"m",
"in",
"mtchs",
":",
"if",
"m",
".",
"upper... | This only parses the ligand type as all the other information should be in the .cif file. The XML file has
proper capitalization whereas the .cif file uses all caps for the ligand type. | [
"This",
"only",
"parses",
"the",
"ligand",
"type",
"as",
"all",
"the",
"other",
"information",
"should",
"be",
"in",
"the",
".",
"cif",
"file",
".",
"The",
"XML",
"file",
"has",
"proper",
"capitalization",
"whereas",
"the",
".",
"cif",
"file",
"uses",
"a... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/ligand.py#L318-L326 | train |
Kortemme-Lab/klab | klab/bio/ligand.py | LigandMap.add_code_mapping | def add_code_mapping(self, from_pdb_code, to_pdb_code):
'''Add a code mapping without a given instance.'''
# Consistency check - make sure that we always map the same code e.g. 'LIG' to the same code e.g. 'GTP'
if from_pdb_code in self.code_map:
assert(self.code_map[from_pdb_code] =... | python | def add_code_mapping(self, from_pdb_code, to_pdb_code):
'''Add a code mapping without a given instance.'''
# Consistency check - make sure that we always map the same code e.g. 'LIG' to the same code e.g. 'GTP'
if from_pdb_code in self.code_map:
assert(self.code_map[from_pdb_code] =... | [
"def",
"add_code_mapping",
"(",
"self",
",",
"from_pdb_code",
",",
"to_pdb_code",
")",
":",
"if",
"from_pdb_code",
"in",
"self",
".",
"code_map",
":",
"assert",
"(",
"self",
".",
"code_map",
"[",
"from_pdb_code",
"]",
"==",
"to_pdb_code",
")",
"else",
":",
... | Add a code mapping without a given instance. | [
"Add",
"a",
"code",
"mapping",
"without",
"a",
"given",
"instance",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/ligand.py#L554-L561 | train |
mardix/Mocha | mocha/contrib/views/auth.py | Login.reset_password | def reset_password(self, action_token, signed_data):
"""Reset the user password. It was triggered by LOST-PASSWORD """
try:
action = "reset-password"
user = get_user_by_action_token(action, action_token)
if not user or not user.signed_data_match(signed_data, action):
... | python | def reset_password(self, action_token, signed_data):
"""Reset the user password. It was triggered by LOST-PASSWORD """
try:
action = "reset-password"
user = get_user_by_action_token(action, action_token)
if not user or not user.signed_data_match(signed_data, action):
... | [
"def",
"reset_password",
"(",
"self",
",",
"action_token",
",",
"signed_data",
")",
":",
"try",
":",
"action",
"=",
"\"reset-password\"",
"user",
"=",
"get_user_by_action_token",
"(",
"action",
",",
"action_token",
")",
"if",
"not",
"user",
"or",
"not",
"user"... | Reset the user password. It was triggered by LOST-PASSWORD | [
"Reset",
"the",
"user",
"password",
".",
"It",
"was",
"triggered",
"by",
"LOST",
"-",
"PASSWORD"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/views/auth.py#L337-L366 | train |
mardix/Mocha | mocha/contrib/views/auth.py | Login.verify_email | def verify_email(self, action_token, signed_data):
""" Verify email account, in which a link was sent to """
try:
action = "verify-email"
user = get_user_by_action_token(action, action_token)
if not user or not user.signed_data_match(signed_data, action):
... | python | def verify_email(self, action_token, signed_data):
""" Verify email account, in which a link was sent to """
try:
action = "verify-email"
user = get_user_by_action_token(action, action_token)
if not user or not user.signed_data_match(signed_data, action):
... | [
"def",
"verify_email",
"(",
"self",
",",
"action_token",
",",
"signed_data",
")",
":",
"try",
":",
"action",
"=",
"\"verify-email\"",
"user",
"=",
"get_user_by_action_token",
"(",
"action",
",",
"action_token",
")",
"if",
"not",
"user",
"or",
"not",
"user",
... | Verify email account, in which a link was sent to | [
"Verify",
"email",
"account",
"in",
"which",
"a",
"link",
"was",
"sent",
"to"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/views/auth.py#L372-L390 | train |
mardix/Mocha | mocha/contrib/views/auth.py | Login.oauth_connect | def oauth_connect(self, provider, action):
"""
This endpoint doesn't check if user is logged in, because it has two functions
1. If the user is not logged in, it will try to signup the user
- if the social info exist, it will login
- not, it will create a new account and... | python | def oauth_connect(self, provider, action):
"""
This endpoint doesn't check if user is logged in, because it has two functions
1. If the user is not logged in, it will try to signup the user
- if the social info exist, it will login
- not, it will create a new account and... | [
"def",
"oauth_connect",
"(",
"self",
",",
"provider",
",",
"action",
")",
":",
"valid_actions",
"=",
"[",
"\"connect\"",
",",
"\"authorized\"",
",",
"\"test\"",
"]",
"_redirect",
"=",
"views",
".",
"auth",
".",
"Account",
".",
"account_settings",
"if",
"is_a... | This endpoint doesn't check if user is logged in, because it has two functions
1. If the user is not logged in, it will try to signup the user
- if the social info exist, it will login
- not, it will create a new account and proceed
2. If user is logged in, it will try to create... | [
"This",
"endpoint",
"doesn",
"t",
"check",
"if",
"user",
"is",
"logged",
"in",
"because",
"it",
"has",
"two",
"functions"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/views/auth.py#L430-L537 | train |
projectshift/shift-boiler | boiler/abstract/abstract_service.py | AbstractService.log | def log(self, message, level=None):
""" Write a message to log """
if level is None:
level = logging.INFO
current_app.logger.log(msg=message, level=level) | python | def log(self, message, level=None):
""" Write a message to log """
if level is None:
level = logging.INFO
current_app.logger.log(msg=message, level=level) | [
"def",
"log",
"(",
"self",
",",
"message",
",",
"level",
"=",
"None",
")",
":",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"logging",
".",
"INFO",
"current_app",
".",
"logger",
".",
"log",
"(",
"msg",
"=",
"message",
",",
"level",
"=",
"level"... | Write a message to log | [
"Write",
"a",
"message",
"to",
"log"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/abstract/abstract_service.py#L15-L20 | train |
projectshift/shift-boiler | boiler/abstract/abstract_service.py | AbstractService.is_instance | def is_instance(self, model):
"""
Is instance?
Checks if provided object is instance of this service's model.
:param model: object
:return: bool
"""
result = isinstance(model, self.__model__)
if result is True:
return ... | python | def is_instance(self, model):
"""
Is instance?
Checks if provided object is instance of this service's model.
:param model: object
:return: bool
"""
result = isinstance(model, self.__model__)
if result is True:
return ... | [
"def",
"is_instance",
"(",
"self",
",",
"model",
")",
":",
"result",
"=",
"isinstance",
"(",
"model",
",",
"self",
".",
"__model__",
")",
"if",
"result",
"is",
"True",
":",
"return",
"True",
"err",
"=",
"'Object {} is not of type {}'",
"raise",
"ValueError",... | Is instance?
Checks if provided object is instance of this service's model.
:param model: object
:return: bool | [
"Is",
"instance?",
"Checks",
"if",
"provided",
"object",
"is",
"instance",
"of",
"this",
"service",
"s",
"model",
"."
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/abstract/abstract_service.py#L22-L35 | train |
projectshift/shift-boiler | boiler/abstract/abstract_service.py | AbstractService.create | def create(self, **kwargs):
"""
Create
Instantiates and persists new model populated from provided
arguments
:param kwargs: varargs, data to populate with
:return: object, persisted new instance of model
"""
model = self.new(**kwar... | python | def create(self, **kwargs):
"""
Create
Instantiates and persists new model populated from provided
arguments
:param kwargs: varargs, data to populate with
:return: object, persisted new instance of model
"""
model = self.new(**kwar... | [
"def",
"create",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"model",
"=",
"self",
".",
"new",
"(",
"**",
"kwargs",
")",
"return",
"self",
".",
"save",
"(",
"model",
")"
] | Create
Instantiates and persists new model populated from provided
arguments
:param kwargs: varargs, data to populate with
:return: object, persisted new instance of model | [
"Create",
"Instantiates",
"and",
"persists",
"new",
"model",
"populated",
"from",
"provided",
"arguments"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/abstract/abstract_service.py#L58-L68 | train |
projectshift/shift-boiler | boiler/abstract/abstract_service.py | AbstractService.save | def save(self, model, commit=True):
"""
Save
Puts model into unit of work for persistence. Can optionally
commit transaction. Returns persisted model as a result.
:param model: object, model to persist
:param commit: bool, commit transaction?
:... | python | def save(self, model, commit=True):
"""
Save
Puts model into unit of work for persistence. Can optionally
commit transaction. Returns persisted model as a result.
:param model: object, model to persist
:param commit: bool, commit transaction?
:... | [
"def",
"save",
"(",
"self",
",",
"model",
",",
"commit",
"=",
"True",
")",
":",
"self",
".",
"is_instance",
"(",
"model",
")",
"db",
".",
"session",
".",
"add",
"(",
"model",
")",
"if",
"commit",
":",
"db",
".",
"session",
".",
"commit",
"(",
")"... | Save
Puts model into unit of work for persistence. Can optionally
commit transaction. Returns persisted model as a result.
:param model: object, model to persist
:param commit: bool, commit transaction?
:return: object, saved model | [
"Save",
"Puts",
"model",
"into",
"unit",
"of",
"work",
"for",
"persistence",
".",
"Can",
"optionally",
"commit",
"transaction",
".",
"Returns",
"persisted",
"model",
"as",
"a",
"result",
"."
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/abstract/abstract_service.py#L70-L85 | train |
projectshift/shift-boiler | boiler/abstract/abstract_service.py | AbstractService.delete | def delete(self, model, commit=True):
"""
Delete
Puts model for deletion into unit of work and optionall commits
transaction
:param model: object, model to delete
:param commit: bool, commit?
:return: object, deleted model
... | python | def delete(self, model, commit=True):
"""
Delete
Puts model for deletion into unit of work and optionall commits
transaction
:param model: object, model to delete
:param commit: bool, commit?
:return: object, deleted model
... | [
"def",
"delete",
"(",
"self",
",",
"model",
",",
"commit",
"=",
"True",
")",
":",
"self",
".",
"is_instance",
"(",
"model",
")",
"db",
".",
"session",
".",
"delete",
"(",
"model",
")",
"if",
"commit",
":",
"db",
".",
"session",
".",
"commit",
"(",
... | Delete
Puts model for deletion into unit of work and optionall commits
transaction
:param model: object, model to delete
:param commit: bool, commit?
:return: object, deleted model | [
"Delete",
"Puts",
"model",
"for",
"deletion",
"into",
"unit",
"of",
"work",
"and",
"optionall",
"commits",
"transaction"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/abstract/abstract_service.py#L87-L102 | train |
fjwCode/cerium | cerium/utils.py | is_connectable | def is_connectable(host: str, port: Union[int, str]) -> bool:
"""Tries to connect to the device to see if it is connectable.
Args:
host: The host to connect.
port: The port to connect.
Returns:
True or False.
"""
socket_ = None
try:
socket_ = socket.create_conne... | python | def is_connectable(host: str, port: Union[int, str]) -> bool:
"""Tries to connect to the device to see if it is connectable.
Args:
host: The host to connect.
port: The port to connect.
Returns:
True or False.
"""
socket_ = None
try:
socket_ = socket.create_conne... | [
"def",
"is_connectable",
"(",
"host",
":",
"str",
",",
"port",
":",
"Union",
"[",
"int",
",",
"str",
"]",
")",
"->",
"bool",
":",
"socket_",
"=",
"None",
"try",
":",
"socket_",
"=",
"socket",
".",
"create_connection",
"(",
"(",
"host",
",",
"port",
... | Tries to connect to the device to see if it is connectable.
Args:
host: The host to connect.
port: The port to connect.
Returns:
True or False. | [
"Tries",
"to",
"connect",
"to",
"the",
"device",
"to",
"see",
"if",
"it",
"is",
"connectable",
"."
] | f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/utils.py#L34-L53 | train |
truveris/py-mdstat | mdstat/utils.py | group_lines | def group_lines(lines):
"""Split a list of lines using empty lines as separators."""
groups = []
group = []
for line in lines:
if line.strip() == "":
groups.append(group[:])
group = []
continue
group.append(line)
if group:
groups.append(g... | python | def group_lines(lines):
"""Split a list of lines using empty lines as separators."""
groups = []
group = []
for line in lines:
if line.strip() == "":
groups.append(group[:])
group = []
continue
group.append(line)
if group:
groups.append(g... | [
"def",
"group_lines",
"(",
"lines",
")",
":",
"groups",
"=",
"[",
"]",
"group",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"\"\"",
":",
"groups",
".",
"append",
"(",
"group",
"[",
":",
"]",
")"... | Split a list of lines using empty lines as separators. | [
"Split",
"a",
"list",
"of",
"lines",
"using",
"empty",
"lines",
"as",
"separators",
"."
] | 881af99d1168694d2f38e606af377ef6cabe2297 | https://github.com/truveris/py-mdstat/blob/881af99d1168694d2f38e606af377ef6cabe2297/mdstat/utils.py#L6-L21 | train |
assamite/creamas | creamas/examples/grid/main.py | DistributedGridEnvironment.set_neighbors | async def set_neighbors(self):
'''Set neighbors for multi-environments, their slave environments,
and agents.
'''
t = time.time()
self.logger.debug("Settings grid neighbors for the multi-environments.")
tasks = []
for i in range(len(self.grid)):
for j ... | python | async def set_neighbors(self):
'''Set neighbors for multi-environments, their slave environments,
and agents.
'''
t = time.time()
self.logger.debug("Settings grid neighbors for the multi-environments.")
tasks = []
for i in range(len(self.grid)):
for j ... | [
"async",
"def",
"set_neighbors",
"(",
"self",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Settings grid neighbors for the multi-environments.\"",
")",
"tasks",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(... | Set neighbors for multi-environments, their slave environments,
and agents. | [
"Set",
"neighbors",
"for",
"multi",
"-",
"environments",
"their",
"slave",
"environments",
"and",
"agents",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/grid/main.py#L151-L186 | train |
assamite/creamas | creamas/ds.py | ssh_exec | async def ssh_exec(server, cmd, timeout=10, **ssh_kwargs):
"""Execute a command on a given server using asynchronous SSH-connection.
The connection to the server is wrapped in :func:`asyncio.wait_for` and
given :attr:`timeout` is applied to it. If the server is not reachable
before timeout expires, :ex... | python | async def ssh_exec(server, cmd, timeout=10, **ssh_kwargs):
"""Execute a command on a given server using asynchronous SSH-connection.
The connection to the server is wrapped in :func:`asyncio.wait_for` and
given :attr:`timeout` is applied to it. If the server is not reachable
before timeout expires, :ex... | [
"async",
"def",
"ssh_exec",
"(",
"server",
",",
"cmd",
",",
"timeout",
"=",
"10",
",",
"**",
"ssh_kwargs",
")",
":",
"conn",
"=",
"await",
"asyncio",
".",
"wait_for",
"(",
"asyncssh",
".",
"connect",
"(",
"server",
",",
"**",
"ssh_kwargs",
")",
",",
... | Execute a command on a given server using asynchronous SSH-connection.
The connection to the server is wrapped in :func:`asyncio.wait_for` and
given :attr:`timeout` is applied to it. If the server is not reachable
before timeout expires, :exc:`asyncio.TimeoutError` is raised.
:param str server: Addres... | [
"Execute",
"a",
"command",
"on",
"a",
"given",
"server",
"using",
"asynchronous",
"SSH",
"-",
"connection",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/ds.py#L28-L52 | train |
assamite/creamas | creamas/ds.py | DistributedEnvironment.spawn_slaves | async def spawn_slaves(self, spawn_cmd, ports=None, **ssh_kwargs):
"""Spawn multi-environments on the nodes through SSH-connections.
:param spawn_cmd:
str or list, command(s) used to spawn the environment on each node.
If *list*, it must contain one command for each node in
... | python | async def spawn_slaves(self, spawn_cmd, ports=None, **ssh_kwargs):
"""Spawn multi-environments on the nodes through SSH-connections.
:param spawn_cmd:
str or list, command(s) used to spawn the environment on each node.
If *list*, it must contain one command for each node in
... | [
"async",
"def",
"spawn_slaves",
"(",
"self",
",",
"spawn_cmd",
",",
"ports",
"=",
"None",
",",
"**",
"ssh_kwargs",
")",
":",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"len",
"(",
"self",
".",
"nodes",
")",
")",
"rets",
"=",
"[",
"]",
"for",
... | Spawn multi-environments on the nodes through SSH-connections.
:param spawn_cmd:
str or list, command(s) used to spawn the environment on each node.
If *list*, it must contain one command for each node in
:attr:`nodes`. If *str*, the same command is used for each node.
... | [
"Spawn",
"multi",
"-",
"environments",
"on",
"the",
"nodes",
"through",
"SSH",
"-",
"connections",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/ds.py#L203-L251 | train |
assamite/creamas | creamas/ds.py | DistributedEnvironment.get_slave_managers | def get_slave_managers(self, as_coro=False):
"""Return all slave environment manager addresses.
:param bool as_coro:
If ``True`` returns awaitable coroutine, otherwise runs the calls
to the slave managers asynchoronously in the event loop.
This method returns the addres... | python | def get_slave_managers(self, as_coro=False):
"""Return all slave environment manager addresses.
:param bool as_coro:
If ``True`` returns awaitable coroutine, otherwise runs the calls
to the slave managers asynchoronously in the event loop.
This method returns the addres... | [
"def",
"get_slave_managers",
"(",
"self",
",",
"as_coro",
"=",
"False",
")",
":",
"async",
"def",
"slave_task",
"(",
"addr",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
")",
"return",
"await",
"r_manager",
".",
... | Return all slave environment manager addresses.
:param bool as_coro:
If ``True`` returns awaitable coroutine, otherwise runs the calls
to the slave managers asynchoronously in the event loop.
This method returns the addresses of the true slave environment
managers, i.e.... | [
"Return",
"all",
"slave",
"environment",
"manager",
"addresses",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/ds.py#L262-L280 | train |
berkeley-cocosci/Wallace | wallace/models.py | Participant.nodes | def nodes(self, type=None, failed=False):
"""Get nodes associated with this participant.
Return a list of nodes associated with the participant. If specified,
``type`` filters by class. By default failed nodes are excluded, to
include only failed nodes use ``failed=True``, for all nodes... | python | def nodes(self, type=None, failed=False):
"""Get nodes associated with this participant.
Return a list of nodes associated with the participant. If specified,
``type`` filters by class. By default failed nodes are excluded, to
include only failed nodes use ``failed=True``, for all nodes... | [
"def",
"nodes",
"(",
"self",
",",
"type",
"=",
"None",
",",
"failed",
"=",
"False",
")",
":",
"if",
"type",
"is",
"None",
":",
"type",
"=",
"Node",
"if",
"not",
"issubclass",
"(",
"type",
",",
"Node",
")",
":",
"raise",
"(",
"TypeError",
"(",
"\"... | Get nodes associated with this participant.
Return a list of nodes associated with the participant. If specified,
``type`` filters by class. By default failed nodes are excluded, to
include only failed nodes use ``failed=True``, for all nodes use
``failed=all``. | [
"Get",
"nodes",
"associated",
"with",
"this",
"participant",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L152-L179 | train |
berkeley-cocosci/Wallace | wallace/models.py | Network.print_verbose | def print_verbose(self):
"""Print a verbose representation of a network."""
print "Nodes: "
for a in (self.nodes(failed="all")):
print a
print "\nVectors: "
for v in (self.vectors(failed="all")):
print v
print "\nInfos: "
for i in (self.i... | python | def print_verbose(self):
"""Print a verbose representation of a network."""
print "Nodes: "
for a in (self.nodes(failed="all")):
print a
print "\nVectors: "
for v in (self.vectors(failed="all")):
print v
print "\nInfos: "
for i in (self.i... | [
"def",
"print_verbose",
"(",
"self",
")",
":",
"print",
"\"Nodes: \"",
"for",
"a",
"in",
"(",
"self",
".",
"nodes",
"(",
"failed",
"=",
"\"all\"",
")",
")",
":",
"print",
"a",
"print",
"\"\\nVectors: \"",
"for",
"v",
"in",
"(",
"self",
".",
"vectors",
... | Print a verbose representation of a network. | [
"Print",
"a",
"verbose",
"representation",
"of",
"a",
"network",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L559-L579 | train |
berkeley-cocosci/Wallace | wallace/models.py | Node.vectors | def vectors(self, direction="all", failed=False):
"""Get vectors that connect at this node.
Direction can be "incoming", "outgoing" or "all" (default).
Failed can be True, False or all
"""
# check direction
if direction not in ["all", "incoming", "outgoing"]:
... | python | def vectors(self, direction="all", failed=False):
"""Get vectors that connect at this node.
Direction can be "incoming", "outgoing" or "all" (default).
Failed can be True, False or all
"""
# check direction
if direction not in ["all", "incoming", "outgoing"]:
... | [
"def",
"vectors",
"(",
"self",
",",
"direction",
"=",
"\"all\"",
",",
"failed",
"=",
"False",
")",
":",
"if",
"direction",
"not",
"in",
"[",
"\"all\"",
",",
"\"incoming\"",
",",
"\"outgoing\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"{} is not a valid vecto... | Get vectors that connect at this node.
Direction can be "incoming", "outgoing" or "all" (default).
Failed can be True, False or all | [
"Get",
"vectors",
"that",
"connect",
"at",
"this",
"node",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L655-L703 | train |
berkeley-cocosci/Wallace | wallace/models.py | Node.transmissions | def transmissions(self, direction="outgoing", status="all", failed=False):
"""Get transmissions sent to or from this node.
Direction can be "all", "incoming" or "outgoing" (default).
Status can be "all" (default), "pending", or "received".
failed can be True, False or "all"
"""
... | python | def transmissions(self, direction="outgoing", status="all", failed=False):
"""Get transmissions sent to or from this node.
Direction can be "all", "incoming" or "outgoing" (default).
Status can be "all" (default), "pending", or "received".
failed can be True, False or "all"
"""
... | [
"def",
"transmissions",
"(",
"self",
",",
"direction",
"=",
"\"outgoing\"",
",",
"status",
"=",
"\"all\"",
",",
"failed",
"=",
"False",
")",
":",
"if",
"direction",
"not",
"in",
"[",
"\"incoming\"",
",",
"\"outgoing\"",
",",
"\"all\"",
"]",
":",
"raise",
... | Get transmissions sent to or from this node.
Direction can be "all", "incoming" or "outgoing" (default).
Status can be "all" (default), "pending", or "received".
failed can be True, False or "all" | [
"Get",
"transmissions",
"sent",
"to",
"or",
"from",
"this",
"node",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L915-L973 | train |
berkeley-cocosci/Wallace | wallace/models.py | Node.receive | def receive(self, what=None):
"""Receive some transmissions.
Received transmissions are marked as received, then their infos are
passed to update().
"what" can be:
1. None (the default) in which case all pending transmissions are
received.
2. a s... | python | def receive(self, what=None):
"""Receive some transmissions.
Received transmissions are marked as received, then their infos are
passed to update().
"what" can be:
1. None (the default) in which case all pending transmissions are
received.
2. a s... | [
"def",
"receive",
"(",
"self",
",",
"what",
"=",
"None",
")",
":",
"if",
"self",
".",
"failed",
":",
"raise",
"ValueError",
"(",
"\"{} cannot receive as it has failed.\"",
".",
"format",
"(",
"self",
")",
")",
"received_transmissions",
"=",
"[",
"]",
"if",
... | Receive some transmissions.
Received transmissions are marked as received, then their infos are
passed to update().
"what" can be:
1. None (the default) in which case all pending transmissions are
received.
2. a specific transmission.
Will raise... | [
"Receive",
"some",
"transmissions",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L1186-L1229 | train |
berkeley-cocosci/Wallace | wallace/models.py | Node.replicate | def replicate(self, info_in):
"""Replicate an info."""
# check self is not failed
if self.failed:
raise ValueError("{} cannot replicate as it has failed."
.format(self))
from transformations import Replication
info_out = type(info_in)(ori... | python | def replicate(self, info_in):
"""Replicate an info."""
# check self is not failed
if self.failed:
raise ValueError("{} cannot replicate as it has failed."
.format(self))
from transformations import Replication
info_out = type(info_in)(ori... | [
"def",
"replicate",
"(",
"self",
",",
"info_in",
")",
":",
"if",
"self",
".",
"failed",
":",
"raise",
"ValueError",
"(",
"\"{} cannot replicate as it has failed.\"",
".",
"format",
"(",
"self",
")",
")",
"from",
"transformations",
"import",
"Replication",
"info_... | Replicate an info. | [
"Replicate",
"an",
"info",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L1241-L1250 | train |
berkeley-cocosci/Wallace | wallace/models.py | Node.mutate | def mutate(self, info_in):
"""Replicate an info + mutation.
To mutate an info, that info must have a method called
``_mutated_contents``.
"""
# check self is not failed
if self.failed:
raise ValueError("{} cannot mutate as it has failed.".format(self))
... | python | def mutate(self, info_in):
"""Replicate an info + mutation.
To mutate an info, that info must have a method called
``_mutated_contents``.
"""
# check self is not failed
if self.failed:
raise ValueError("{} cannot mutate as it has failed.".format(self))
... | [
"def",
"mutate",
"(",
"self",
",",
"info_in",
")",
":",
"if",
"self",
".",
"failed",
":",
"raise",
"ValueError",
"(",
"\"{} cannot mutate as it has failed.\"",
".",
"format",
"(",
"self",
")",
")",
"from",
"transformations",
"import",
"Mutation",
"info_out",
"... | Replicate an info + mutation.
To mutate an info, that info must have a method called
``_mutated_contents``. | [
"Replicate",
"an",
"info",
"+",
"mutation",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L1252-L1266 | train |
berkeley-cocosci/Wallace | wallace/models.py | Vector.transmissions | def transmissions(self, status="all"):
"""Get transmissions sent along this Vector.
Status can be "all" (the default), "pending", or "received".
"""
if status not in ["all", "pending", "received"]:
raise(ValueError("You cannot get {} transmissions."
... | python | def transmissions(self, status="all"):
"""Get transmissions sent along this Vector.
Status can be "all" (the default), "pending", or "received".
"""
if status not in ["all", "pending", "received"]:
raise(ValueError("You cannot get {} transmissions."
... | [
"def",
"transmissions",
"(",
"self",
",",
"status",
"=",
"\"all\"",
")",
":",
"if",
"status",
"not",
"in",
"[",
"\"all\"",
",",
"\"pending\"",
",",
"\"received\"",
"]",
":",
"raise",
"(",
"ValueError",
"(",
"\"You cannot get {} transmissions.\"",
".",
"format"... | Get transmissions sent along this Vector.
Status can be "all" (the default), "pending", or "received". | [
"Get",
"transmissions",
"sent",
"along",
"this",
"Vector",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/models.py#L1358-L1380 | train |
Ceasar/twosheds | twosheds/shell.py | Shell.serve_forever | def serve_forever(self, banner=None):
"""Interact with the user.
:param banner: (optional) the banner to print before the first
interaction. Defaults to ``None``.
"""
if hasattr(readline, "read_history_file"):
try:
readline.read_history... | python | def serve_forever(self, banner=None):
"""Interact with the user.
:param banner: (optional) the banner to print before the first
interaction. Defaults to ``None``.
"""
if hasattr(readline, "read_history_file"):
try:
readline.read_history... | [
"def",
"serve_forever",
"(",
"self",
",",
"banner",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"readline",
",",
"\"read_history_file\"",
")",
":",
"try",
":",
"readline",
".",
"read_history_file",
"(",
"self",
".",
"histfile",
")",
"except",
"IOError",
"... | Interact with the user.
:param banner: (optional) the banner to print before the first
interaction. Defaults to ``None``. | [
"Interact",
"with",
"the",
"user",
"."
] | 55b0a207e3a06b85e9a9567069b3822a651501a7 | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/shell.py#L74-L86 | train |
Ceasar/twosheds | twosheds/completer.py | Completer.complete | def complete(self, word, state):
"""Return the next possible completion for ``word``.
This is called successively with ``state == 0, 1, 2, ...`` until it
returns ``None``.
The completion should begin with ``word``.
:param word: the word to complete
:param state: an int... | python | def complete(self, word, state):
"""Return the next possible completion for ``word``.
This is called successively with ``state == 0, 1, 2, ...`` until it
returns ``None``.
The completion should begin with ``word``.
:param word: the word to complete
:param state: an int... | [
"def",
"complete",
"(",
"self",
",",
"word",
",",
"state",
")",
":",
"try",
":",
"import",
"rl",
"rl",
".",
"completion",
".",
"suppress_append",
"=",
"True",
"except",
"ImportError",
":",
"pass",
"word",
"=",
"transform",
"(",
"word",
",",
"self",
"."... | Return the next possible completion for ``word``.
This is called successively with ``state == 0, 1, 2, ...`` until it
returns ``None``.
The completion should begin with ``word``.
:param word: the word to complete
:param state: an int, used to iterate over the choices | [
"Return",
"the",
"next",
"possible",
"completion",
"for",
"word",
"."
] | 55b0a207e3a06b85e9a9567069b3822a651501a7 | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/completer.py#L97-L125 | train |
Ceasar/twosheds | twosheds/completer.py | Completer.exclude_matches | def exclude_matches(self, matches):
"""Filter any matches that match an exclude pattern.
:param matches: a list of possible completions
"""
for match in matches:
for exclude_pattern in self.exclude_patterns:
if re.match(exclude_pattern, match) is not None:
... | python | def exclude_matches(self, matches):
"""Filter any matches that match an exclude pattern.
:param matches: a list of possible completions
"""
for match in matches:
for exclude_pattern in self.exclude_patterns:
if re.match(exclude_pattern, match) is not None:
... | [
"def",
"exclude_matches",
"(",
"self",
",",
"matches",
")",
":",
"for",
"match",
"in",
"matches",
":",
"for",
"exclude_pattern",
"in",
"self",
".",
"exclude_patterns",
":",
"if",
"re",
".",
"match",
"(",
"exclude_pattern",
",",
"match",
")",
"is",
"not",
... | Filter any matches that match an exclude pattern.
:param matches: a list of possible completions | [
"Filter",
"any",
"matches",
"that",
"match",
"an",
"exclude",
"pattern",
"."
] | 55b0a207e3a06b85e9a9567069b3822a651501a7 | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/completer.py#L127-L137 | train |
Ceasar/twosheds | twosheds/completer.py | Completer.gen_filename_completions | def gen_filename_completions(self, word, filenames):
"""Generate a sequence of filenames that match ``word``.
:param word: the word to complete
"""
if not word:
return filenames
else:
trie = pygtrie.CharTrie()
for filename in filenames:
... | python | def gen_filename_completions(self, word, filenames):
"""Generate a sequence of filenames that match ``word``.
:param word: the word to complete
"""
if not word:
return filenames
else:
trie = pygtrie.CharTrie()
for filename in filenames:
... | [
"def",
"gen_filename_completions",
"(",
"self",
",",
"word",
",",
"filenames",
")",
":",
"if",
"not",
"word",
":",
"return",
"filenames",
"else",
":",
"trie",
"=",
"pygtrie",
".",
"CharTrie",
"(",
")",
"for",
"filename",
"in",
"filenames",
":",
"trie",
"... | Generate a sequence of filenames that match ``word``.
:param word: the word to complete | [
"Generate",
"a",
"sequence",
"of",
"filenames",
"that",
"match",
"word",
"."
] | 55b0a207e3a06b85e9a9567069b3822a651501a7 | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/completer.py#L142-L153 | train |
Ceasar/twosheds | twosheds/completer.py | Completer.gen_matches | def gen_matches(self, word):
"""Generate a sequence of possible completions for ``word``.
:param word: the word to complete
"""
if word.startswith("$"):
for match in self.gen_variable_completions(word, os.environ):
yield match
else:
head,... | python | def gen_matches(self, word):
"""Generate a sequence of possible completions for ``word``.
:param word: the word to complete
"""
if word.startswith("$"):
for match in self.gen_variable_completions(word, os.environ):
yield match
else:
head,... | [
"def",
"gen_matches",
"(",
"self",
",",
"word",
")",
":",
"if",
"word",
".",
"startswith",
"(",
"\"$\"",
")",
":",
"for",
"match",
"in",
"self",
".",
"gen_variable_completions",
"(",
"word",
",",
"os",
".",
"environ",
")",
":",
"yield",
"match",
"else"... | Generate a sequence of possible completions for ``word``.
:param word: the word to complete | [
"Generate",
"a",
"sequence",
"of",
"possible",
"completions",
"for",
"word",
"."
] | 55b0a207e3a06b85e9a9567069b3822a651501a7 | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/completer.py#L155-L172 | train |
Ceasar/twosheds | twosheds/completer.py | Completer.gen_variable_completions | def gen_variable_completions(self, word, env):
"""Generate a sequence of possible variable completions for ``word``.
:param word: the word to complete
:param env: the environment
"""
# ignore the first character, which is a dollar sign
var = word[1:]
for k in env... | python | def gen_variable_completions(self, word, env):
"""Generate a sequence of possible variable completions for ``word``.
:param word: the word to complete
:param env: the environment
"""
# ignore the first character, which is a dollar sign
var = word[1:]
for k in env... | [
"def",
"gen_variable_completions",
"(",
"self",
",",
"word",
",",
"env",
")",
":",
"var",
"=",
"word",
"[",
"1",
":",
"]",
"for",
"k",
"in",
"env",
":",
"if",
"k",
".",
"startswith",
"(",
"var",
")",
":",
"yield",
"\"$\"",
"+",
"k"
] | Generate a sequence of possible variable completions for ``word``.
:param word: the word to complete
:param env: the environment | [
"Generate",
"a",
"sequence",
"of",
"possible",
"variable",
"completions",
"for",
"word",
"."
] | 55b0a207e3a06b85e9a9567069b3822a651501a7 | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/completer.py#L174-L184 | train |
Ceasar/twosheds | twosheds/completer.py | Completer.inflect | def inflect(self, filename):
"""Inflect a filename to indicate its type.
If the file is a directory, the suffix "/" is appended, otherwise
a space is appended.
:param filename: the name of the file to inflect
"""
suffix = ("/" if os.path.isdir(filename) else " ")
... | python | def inflect(self, filename):
"""Inflect a filename to indicate its type.
If the file is a directory, the suffix "/" is appended, otherwise
a space is appended.
:param filename: the name of the file to inflect
"""
suffix = ("/" if os.path.isdir(filename) else " ")
... | [
"def",
"inflect",
"(",
"self",
",",
"filename",
")",
":",
"suffix",
"=",
"(",
"\"/\"",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"filename",
")",
"else",
"\" \"",
")",
"return",
"self",
".",
"_escape",
"(",
"filename",
")",
"+",
"suffix"
] | Inflect a filename to indicate its type.
If the file is a directory, the suffix "/" is appended, otherwise
a space is appended.
:param filename: the name of the file to inflect | [
"Inflect",
"a",
"filename",
"to",
"indicate",
"its",
"type",
"."
] | 55b0a207e3a06b85e9a9567069b3822a651501a7 | https://github.com/Ceasar/twosheds/blob/55b0a207e3a06b85e9a9567069b3822a651501a7/twosheds/completer.py#L202-L211 | train |
berkeley-cocosci/Wallace | wallace/nodes.py | Environment.state | def state(self, time=None):
"""The most recently-created info of type State at the specfied time.
If time is None then it returns the most recent state as of now.
"""
if time is None:
return max(self.infos(type=State), key=attrgetter('creation_time'))
else:
... | python | def state(self, time=None):
"""The most recently-created info of type State at the specfied time.
If time is None then it returns the most recent state as of now.
"""
if time is None:
return max(self.infos(type=State), key=attrgetter('creation_time'))
else:
... | [
"def",
"state",
"(",
"self",
",",
"time",
"=",
"None",
")",
":",
"if",
"time",
"is",
"None",
":",
"return",
"max",
"(",
"self",
".",
"infos",
"(",
"type",
"=",
"State",
")",
",",
"key",
"=",
"attrgetter",
"(",
"'creation_time'",
")",
")",
"else",
... | The most recently-created info of type State at the specfied time.
If time is None then it returns the most recent state as of now. | [
"The",
"most",
"recently",
"-",
"created",
"info",
"of",
"type",
"State",
"at",
"the",
"specfied",
"time",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/nodes.py#L96-L106 | train |
projectshift/shift-boiler | boiler/feature/sentry.py | sentry_feature | def sentry_feature(app):
"""
Sentry feature
Adds basic integration with Sentry via the raven library
"""
# get keys
sentry_public_key = app.config.get('SENTRY_PUBLIC_KEY')
sentry_project_id = app.config.get('SENTRY_PROJECT_ID')
if not sentry_public_key or not sentry_project_id:
... | python | def sentry_feature(app):
"""
Sentry feature
Adds basic integration with Sentry via the raven library
"""
# get keys
sentry_public_key = app.config.get('SENTRY_PUBLIC_KEY')
sentry_project_id = app.config.get('SENTRY_PROJECT_ID')
if not sentry_public_key or not sentry_project_id:
... | [
"def",
"sentry_feature",
"(",
"app",
")",
":",
"sentry_public_key",
"=",
"app",
".",
"config",
".",
"get",
"(",
"'SENTRY_PUBLIC_KEY'",
")",
"sentry_project_id",
"=",
"app",
".",
"config",
".",
"get",
"(",
"'SENTRY_PROJECT_ID'",
")",
"if",
"not",
"sentry_public... | Sentry feature
Adds basic integration with Sentry via the raven library | [
"Sentry",
"feature",
"Adds",
"basic",
"integration",
"with",
"Sentry",
"via",
"the",
"raven",
"library"
] | 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/feature/sentry.py#L6-L23 | train |
20c/pluginmgr | pluginmgr/config.py | ConfigPluginManager.new_plugin | def new_plugin(self, config, *args, **kwargs):
"""
instantiate a plugin
creates the object, stores it in _instance
"""
typ = None
obj = None
# if type is defined, create a new instance
if 'type' in config:
typ = config['type']
# singl... | python | def new_plugin(self, config, *args, **kwargs):
"""
instantiate a plugin
creates the object, stores it in _instance
"""
typ = None
obj = None
# if type is defined, create a new instance
if 'type' in config:
typ = config['type']
# singl... | [
"def",
"new_plugin",
"(",
"self",
",",
"config",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"typ",
"=",
"None",
"obj",
"=",
"None",
"if",
"'type'",
"in",
"config",
":",
"typ",
"=",
"config",
"[",
"'type'",
"]",
"elif",
"isinstance",
"(",
"con... | instantiate a plugin
creates the object, stores it in _instance | [
"instantiate",
"a",
"plugin",
"creates",
"the",
"object",
"stores",
"it",
"in",
"_instance"
] | ea19edab6d145f539641c304745acd4ab2c67eb7 | https://github.com/20c/pluginmgr/blob/ea19edab6d145f539641c304745acd4ab2c67eb7/pluginmgr/config.py#L47-L73 | train |
adaptive-learning/proso-apps | proso_models/views.py | to_practice_counts | def to_practice_counts(request):
"""
Get number of items available to practice.
filters: -- use this or body
json as in BODY
language:
language of the items
BODY
json in following format:
{
"#identifier": [] -- custom identifier (str) and filt... | python | def to_practice_counts(request):
"""
Get number of items available to practice.
filters: -- use this or body
json as in BODY
language:
language of the items
BODY
json in following format:
{
"#identifier": [] -- custom identifier (str) and filt... | [
"def",
"to_practice_counts",
"(",
"request",
")",
":",
"data",
"=",
"None",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"[",
"\"filter... | Get number of items available to practice.
filters: -- use this or body
json as in BODY
language:
language of the items
BODY
json in following format:
{
"#identifier": [] -- custom identifier (str) and filter
...
} | [
"Get",
"number",
"of",
"items",
"available",
"to",
"practice",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/views.py#L89-L124 | train |
adaptive-learning/proso-apps | proso_models/views.py | answer | def answer(request):
"""
Save the answer.
GET parameters:
html:
turn on the HTML version of the API
BODY
json in following format:
{
"answer": #answer, -- for one answer
"answers": [#answer, #answer, #answer ...] -- for multiple ans... | python | def answer(request):
"""
Save the answer.
GET parameters:
html:
turn on the HTML version of the API
BODY
json in following format:
{
"answer": #answer, -- for one answer
"answers": [#answer, #answer, #answer ...] -- for multiple ans... | [
"def",
"answer",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render",
"(",
"request",
",",
"'models_answer.html'",
",",
"{",
"}",
",",
"help_text",
"=",
"answer",
".",
"__doc__",
")",
"elif",
"request",
".",
... | Save the answer.
GET parameters:
html:
turn on the HTML version of the API
BODY
json in following format:
{
"answer": #answer, -- for one answer
"answers": [#answer, #answer, #answer ...] -- for multiple answers
}
answer = {
... | [
"Save",
"the",
"answer",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/views.py#L245-L277 | train |
adaptive-learning/proso-apps | proso_models/views.py | user_stats | def user_stats(request):
"""
Get user statistics for selected groups of items
time:
time in format '%Y-%m-%d_%H:%M:%S' used for practicing
user:
identifier of the user (only for stuff users)
username:
username of user (only for users with public profile)
filters: ... | python | def user_stats(request):
"""
Get user statistics for selected groups of items
time:
time in format '%Y-%m-%d_%H:%M:%S' used for practicing
user:
identifier of the user (only for stuff users)
username:
username of user (only for users with public profile)
filters: ... | [
"def",
"user_stats",
"(",
"request",
")",
":",
"timer",
"(",
"'user_stats'",
")",
"response",
"=",
"{",
"}",
"data",
"=",
"None",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
"... | Get user statistics for selected groups of items
time:
time in format '%Y-%m-%d_%H:%M:%S' used for practicing
user:
identifier of the user (only for stuff users)
username:
username of user (only for users with public profile)
filters: -- use this or body
json as i... | [
"Get",
"user",
"statistics",
"for",
"selected",
"groups",
"of",
"items"
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/views.py#L282-L347 | train |
Kortemme-Lab/klab | klab/rosetta/input_files.py | LoopsFile.add | def add(self, start, end, cut_point = None, skip_rate = None, extend_loop = None):
'''Add a new loop definition.'''
self.data.append(self.parse_loop_line(['LOOP', start, end, cut_point, skip_rate, extend_loop]))
assert(start <= end) | python | def add(self, start, end, cut_point = None, skip_rate = None, extend_loop = None):
'''Add a new loop definition.'''
self.data.append(self.parse_loop_line(['LOOP', start, end, cut_point, skip_rate, extend_loop]))
assert(start <= end) | [
"def",
"add",
"(",
"self",
",",
"start",
",",
"end",
",",
"cut_point",
"=",
"None",
",",
"skip_rate",
"=",
"None",
",",
"extend_loop",
"=",
"None",
")",
":",
"self",
".",
"data",
".",
"append",
"(",
"self",
".",
"parse_loop_line",
"(",
"[",
"'LOOP'",... | Add a new loop definition. | [
"Add",
"a",
"new",
"loop",
"definition",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/rosetta/input_files.py#L123-L126 | train |
berkeley-cocosci/Wallace | wallace/experiments.py | Experiment.log | def log(self, text, key="?????", force=False):
"""Print a string to the logs."""
if force or self.verbose:
print ">>>> {} {}".format(key, text)
sys.stdout.flush() | python | def log(self, text, key="?????", force=False):
"""Print a string to the logs."""
if force or self.verbose:
print ">>>> {} {}".format(key, text)
sys.stdout.flush() | [
"def",
"log",
"(",
"self",
",",
"text",
",",
"key",
"=",
"\"?????\"",
",",
"force",
"=",
"False",
")",
":",
"if",
"force",
"or",
"self",
".",
"verbose",
":",
"print",
"\">>>> {} {}\"",
".",
"format",
"(",
"key",
",",
"text",
")",
"sys",
".",
"stdou... | Print a string to the logs. | [
"Print",
"a",
"string",
"to",
"the",
"logs",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/experiments.py#L230-L234 | train |
Kortemme-Lab/klab | klab/view_commit_log.py | input_yes_no | def input_yes_no(msg=''):
"""
Simple helper function
"""
print '\n'+msg
while(True):
i=raw_input('Input yes or no: ')
i=i.lower()
if i=='y' or i=='yes':
return True
elif i=='n' or i=='no':
return False
else:
print 'ERROR: Ba... | python | def input_yes_no(msg=''):
"""
Simple helper function
"""
print '\n'+msg
while(True):
i=raw_input('Input yes or no: ')
i=i.lower()
if i=='y' or i=='yes':
return True
elif i=='n' or i=='no':
return False
else:
print 'ERROR: Ba... | [
"def",
"input_yes_no",
"(",
"msg",
"=",
"''",
")",
":",
"print",
"'\\n'",
"+",
"msg",
"while",
"(",
"True",
")",
":",
"i",
"=",
"raw_input",
"(",
"'Input yes or no: '",
")",
"i",
"=",
"i",
".",
"lower",
"(",
")",
"if",
"i",
"==",
"'y'",
"or",
"i"... | Simple helper function | [
"Simple",
"helper",
"function"
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/view_commit_log.py#L120-L133 | train |
inveniosoftware/invenio-pidrelations | invenio_pidrelations/utils.py | resolve_relation_type_config | def resolve_relation_type_config(value):
"""Resolve the relation type to config object.
Resolve relation type from string (e.g.: serialization) or int (db value)
to the full config object.
"""
relation_types = current_app.config['PIDRELATIONS_RELATION_TYPES']
if isinstance(value, six.string_ty... | python | def resolve_relation_type_config(value):
"""Resolve the relation type to config object.
Resolve relation type from string (e.g.: serialization) or int (db value)
to the full config object.
"""
relation_types = current_app.config['PIDRELATIONS_RELATION_TYPES']
if isinstance(value, six.string_ty... | [
"def",
"resolve_relation_type_config",
"(",
"value",
")",
":",
"relation_types",
"=",
"current_app",
".",
"config",
"[",
"'PIDRELATIONS_RELATION_TYPES'",
"]",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"try",
":",
"obj",
"=",
... | Resolve the relation type to config object.
Resolve relation type from string (e.g.: serialization) or int (db value)
to the full config object. | [
"Resolve",
"the",
"relation",
"type",
"to",
"config",
"object",
"."
] | a49f3725cf595b663c5b04814280b231f88bc333 | https://github.com/inveniosoftware/invenio-pidrelations/blob/a49f3725cf595b663c5b04814280b231f88bc333/invenio_pidrelations/utils.py#L48-L73 | train |
Kortemme-Lab/klab | klab/bio/alignment.py | match_RCSB_pdb_chains | def match_RCSB_pdb_chains(pdb_id1, pdb_id2, cut_off = 60.0, allow_multiple_matches = False, multiple_match_error_margin = 3.0, use_seqres_sequences_if_possible = True, strict = True):
'''A convenience function for match_pdb_chains. The required arguments are two PDB IDs from the RCSB.'''
try:
stage = pd... | python | def match_RCSB_pdb_chains(pdb_id1, pdb_id2, cut_off = 60.0, allow_multiple_matches = False, multiple_match_error_margin = 3.0, use_seqres_sequences_if_possible = True, strict = True):
'''A convenience function for match_pdb_chains. The required arguments are two PDB IDs from the RCSB.'''
try:
stage = pd... | [
"def",
"match_RCSB_pdb_chains",
"(",
"pdb_id1",
",",
"pdb_id2",
",",
"cut_off",
"=",
"60.0",
",",
"allow_multiple_matches",
"=",
"False",
",",
"multiple_match_error_margin",
"=",
"3.0",
",",
"use_seqres_sequences_if_possible",
"=",
"True",
",",
"strict",
"=",
"True"... | A convenience function for match_pdb_chains. The required arguments are two PDB IDs from the RCSB. | [
"A",
"convenience",
"function",
"for",
"match_pdb_chains",
".",
"The",
"required",
"arguments",
"are",
"two",
"PDB",
"IDs",
"from",
"the",
"RCSB",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/alignment.py#L139-L149 | train |
uogbuji/versa | tools/py/pipeline/main.py | create_resource | def create_resource(output_model, rtype, unique, links, existing_ids=None, id_helper=None):
'''
General-purpose routine to create a new resource in the output model, based on data provided
output_model - Versa connection to model to be updated
rtype - Type IRI for the new resource, set wit... | python | def create_resource(output_model, rtype, unique, links, existing_ids=None, id_helper=None):
'''
General-purpose routine to create a new resource in the output model, based on data provided
output_model - Versa connection to model to be updated
rtype - Type IRI for the new resource, set wit... | [
"def",
"create_resource",
"(",
"output_model",
",",
"rtype",
",",
"unique",
",",
"links",
",",
"existing_ids",
"=",
"None",
",",
"id_helper",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"id_helper",
",",
"str",
")",
":",
"idg",
"=",
"idgen",
"(",
"... | General-purpose routine to create a new resource in the output model, based on data provided
output_model - Versa connection to model to be updated
rtype - Type IRI for the new resource, set with Versa type
unique - list of key/value pairs for determining a unique hash for the new res... | [
"General",
"-",
"purpose",
"routine",
"to",
"create",
"a",
"new",
"resource",
"in",
"the",
"output",
"model",
"based",
"on",
"data",
"provided"
] | f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/pipeline/main.py#L104-L133 | train |
brunato/lograptor | lograptor/core.py | LogRaptor._read_apps | def _read_apps(self):
"""
Read the configuration of applications returning a dictionary
:return: A dictionary with application names as keys and configuration \
object as values.
"""
apps = {}
for cfgfile in glob.iglob(os.path.join(self.confdir, '*.conf')):
... | python | def _read_apps(self):
"""
Read the configuration of applications returning a dictionary
:return: A dictionary with application names as keys and configuration \
object as values.
"""
apps = {}
for cfgfile in glob.iglob(os.path.join(self.confdir, '*.conf')):
... | [
"def",
"_read_apps",
"(",
"self",
")",
":",
"apps",
"=",
"{",
"}",
"for",
"cfgfile",
"in",
"glob",
".",
"iglob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"confdir",
",",
"'*.conf'",
")",
")",
":",
"name",
"=",
"os",
".",
"path",
"... | Read the configuration of applications returning a dictionary
:return: A dictionary with application names as keys and configuration \
object as values. | [
"Read",
"the",
"configuration",
"of",
"applications",
"returning",
"a",
"dictionary"
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L122-L142 | train |
brunato/lograptor | lograptor/core.py | LogRaptor.patterns | def patterns(self):
"""
A tuple with re.RegexObject objects created from regex pattern arguments.
"""
# No explicit argument for patterns ==> consider the first source argument as pattern.
if not self.args.patterns and not self.args.pattern_files:
try:
... | python | def patterns(self):
"""
A tuple with re.RegexObject objects created from regex pattern arguments.
"""
# No explicit argument for patterns ==> consider the first source argument as pattern.
if not self.args.patterns and not self.args.pattern_files:
try:
... | [
"def",
"patterns",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"args",
".",
"patterns",
"and",
"not",
"self",
".",
"args",
".",
"pattern_files",
":",
"try",
":",
"self",
".",
"args",
".",
"patterns",
".",
"append",
"(",
"self",
".",
"args",
".... | A tuple with re.RegexObject objects created from regex pattern arguments. | [
"A",
"tuple",
"with",
"re",
".",
"RegexObject",
"objects",
"created",
"from",
"regex",
"pattern",
"arguments",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L233-L263 | train |
brunato/lograptor | lograptor/core.py | LogRaptor.files | def files(self):
"""
A list of input sources. Each item can be a file path, a glob path or URL.
"""
# If no files but a recursion option ==> use the current directory
if not self.args.files and self.recursive:
return ['.']
else:
return self.args.fi... | python | def files(self):
"""
A list of input sources. Each item can be a file path, a glob path or URL.
"""
# If no files but a recursion option ==> use the current directory
if not self.args.files and self.recursive:
return ['.']
else:
return self.args.fi... | [
"def",
"files",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"args",
".",
"files",
"and",
"self",
".",
"recursive",
":",
"return",
"[",
"'.'",
"]",
"else",
":",
"return",
"self",
".",
"args",
".",
"files"
] | A list of input sources. Each item can be a file path, a glob path or URL. | [
"A",
"list",
"of",
"input",
"sources",
".",
"Each",
"item",
"can",
"be",
"a",
"file",
"path",
"a",
"glob",
"path",
"or",
"URL",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L266-L274 | train |
brunato/lograptor | lograptor/core.py | LogRaptor.apps | def apps(self):
"""
Dictionary with loaded applications.
"""
logger.debug("initialize applications ...")
enabled = None
apps = self.args.apps or self._config_apps.keys()
unknown = set(apps) - set(self._config_apps.keys())
if unknown:
raise LogR... | python | def apps(self):
"""
Dictionary with loaded applications.
"""
logger.debug("initialize applications ...")
enabled = None
apps = self.args.apps or self._config_apps.keys()
unknown = set(apps) - set(self._config_apps.keys())
if unknown:
raise LogR... | [
"def",
"apps",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"initialize applications ...\"",
")",
"enabled",
"=",
"None",
"apps",
"=",
"self",
".",
"args",
".",
"apps",
"or",
"self",
".",
"_config_apps",
".",
"keys",
"(",
")",
"unknown",
"=",
... | Dictionary with loaded applications. | [
"Dictionary",
"with",
"loaded",
"applications",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L350-L364 | train |
brunato/lograptor | lograptor/core.py | LogRaptor.apptags | def apptags(self):
"""
Map from log app-name to an application.
"""
logger.debug("populate tags map ...")
apps = self._apps.keys()
unknown = set(apps)
unknown.difference_update(self._config_apps.keys())
if unknown:
raise ValueError("unknown app... | python | def apptags(self):
"""
Map from log app-name to an application.
"""
logger.debug("populate tags map ...")
apps = self._apps.keys()
unknown = set(apps)
unknown.difference_update(self._config_apps.keys())
if unknown:
raise ValueError("unknown app... | [
"def",
"apptags",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"populate tags map ...\"",
")",
"apps",
"=",
"self",
".",
"_apps",
".",
"keys",
"(",
")",
"unknown",
"=",
"set",
"(",
"apps",
")",
"unknown",
".",
"difference_update",
"(",
"self",
... | Map from log app-name to an application. | [
"Map",
"from",
"log",
"app",
"-",
"name",
"to",
"an",
"application",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L367-L388 | train |
brunato/lograptor | lograptor/core.py | LogRaptor.create_dispatcher | def create_dispatcher(self):
"""
Return a dispatcher for configured channels.
"""
before_context = max(self.args.before_context, self.args.context)
after_context = max(self.args.after_context, self.args.context)
if self.args.files_with_match is not None or self.args.coun... | python | def create_dispatcher(self):
"""
Return a dispatcher for configured channels.
"""
before_context = max(self.args.before_context, self.args.context)
after_context = max(self.args.after_context, self.args.context)
if self.args.files_with_match is not None or self.args.coun... | [
"def",
"create_dispatcher",
"(",
"self",
")",
":",
"before_context",
"=",
"max",
"(",
"self",
".",
"args",
".",
"before_context",
",",
"self",
".",
"args",
".",
"context",
")",
"after_context",
"=",
"max",
"(",
"self",
".",
"args",
".",
"after_context",
... | Return a dispatcher for configured channels. | [
"Return",
"a",
"dispatcher",
"for",
"configured",
"channels",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L562-L578 | train |
brunato/lograptor | lograptor/core.py | LogRaptor.get_config | def get_config(self):
"""
Return a formatted text with main configuration parameters.
"""
# Create a dummy report object if necessary
channels = [sect.rsplit('_')[0] for sect in self.config.sections(suffix='_channel')]
channels.sort()
disabled_apps = [app for app ... | python | def get_config(self):
"""
Return a formatted text with main configuration parameters.
"""
# Create a dummy report object if necessary
channels = [sect.rsplit('_')[0] for sect in self.config.sections(suffix='_channel')]
channels.sort()
disabled_apps = [app for app ... | [
"def",
"get_config",
"(",
"self",
")",
":",
"channels",
"=",
"[",
"sect",
".",
"rsplit",
"(",
"'_'",
")",
"[",
"0",
"]",
"for",
"sect",
"in",
"self",
".",
"config",
".",
"sections",
"(",
"suffix",
"=",
"'_channel'",
")",
"]",
"channels",
".",
"sort... | Return a formatted text with main configuration parameters. | [
"Return",
"a",
"formatted",
"text",
"with",
"main",
"configuration",
"parameters",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L600-L620 | train |
brunato/lograptor | lograptor/core.py | LogRaptor.get_run_summary | def get_run_summary(self, run_stats):
"""
Produce a text summary from run statistics.
:param run_stats: A dictionary containing run stats
:return: Formatted multiline string
"""
run_stats = run_stats.copy()
run_stats['files'] = len(run_stats['files'])
sum... | python | def get_run_summary(self, run_stats):
"""
Produce a text summary from run statistics.
:param run_stats: A dictionary containing run stats
:return: Formatted multiline string
"""
run_stats = run_stats.copy()
run_stats['files'] = len(run_stats['files'])
sum... | [
"def",
"get_run_summary",
"(",
"self",
",",
"run_stats",
")",
":",
"run_stats",
"=",
"run_stats",
".",
"copy",
"(",
")",
"run_stats",
"[",
"'files'",
"]",
"=",
"len",
"(",
"run_stats",
"[",
"'files'",
"]",
")",
"summary",
"=",
"[",
"u'\\n--- %s run summary... | Produce a text summary from run statistics.
:param run_stats: A dictionary containing run stats
:return: Formatted multiline string | [
"Produce",
"a",
"text",
"summary",
"from",
"run",
"statistics",
"."
] | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L622-L647 | train |
peergradeio/flask-mongo-profiler | flask_mongo_profiler/helpers.py | add_template_dirs | def add_template_dirs(app):
"""Add flask_mongo_profiler's template directories.
Parameters
----------
app : flask.Flask
"""
template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app.jinja_loader = jinja2.ChoiceLoader(
[app.jinja_loader, jinja2.FileSys... | python | def add_template_dirs(app):
"""Add flask_mongo_profiler's template directories.
Parameters
----------
app : flask.Flask
"""
template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app.jinja_loader = jinja2.ChoiceLoader(
[app.jinja_loader, jinja2.FileSys... | [
"def",
"add_template_dirs",
"(",
"app",
")",
":",
"template_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"'templates'",
")",
"app",
".",
"... | Add flask_mongo_profiler's template directories.
Parameters
----------
app : flask.Flask | [
"Add",
"flask_mongo_profiler",
"s",
"template",
"directories",
"."
] | a267eeb49fea07c9a24fb370bd9d7a90ed313ccf | https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/helpers.py#L7-L18 | train |
berkeley-cocosci/Wallace | wallace/command_line.py | setup | def setup():
"""Walk the user though the Wallace setup."""
# Create the Wallace config file if it does not already exist.
config_name = ".wallaceconfig"
config_path = os.path.join(os.path.expanduser("~"), config_name)
if os.path.isfile(config_path):
log("Wallace config file already exists."... | python | def setup():
"""Walk the user though the Wallace setup."""
# Create the Wallace config file if it does not already exist.
config_name = ".wallaceconfig"
config_path = os.path.join(os.path.expanduser("~"), config_name)
if os.path.isfile(config_path):
log("Wallace config file already exists."... | [
"def",
"setup",
"(",
")",
":",
"config_name",
"=",
"\".wallaceconfig\"",
"config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
",",
"config_name",
")",
"if",
"os",
".",
"path",
".",
"isfile",
... | Walk the user though the Wallace setup. | [
"Walk",
"the",
"user",
"though",
"the",
"Wallace",
"setup",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L66-L80 | train |
berkeley-cocosci/Wallace | wallace/command_line.py | summary | def summary(app):
"""Print a summary of a deployed app's status."""
r = requests.get('https://{}.herokuapp.com/summary'.format(app))
summary = r.json()['summary']
click.echo("\nstatus \t| count")
click.echo("----------------")
for s in summary:
click.echo("{}\t| {}".format(s[0], s[1]))
... | python | def summary(app):
"""Print a summary of a deployed app's status."""
r = requests.get('https://{}.herokuapp.com/summary'.format(app))
summary = r.json()['summary']
click.echo("\nstatus \t| count")
click.echo("----------------")
for s in summary:
click.echo("{}\t| {}".format(s[0], s[1]))
... | [
"def",
"summary",
"(",
"app",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"'https://{}.herokuapp.com/summary'",
".",
"format",
"(",
"app",
")",
")",
"summary",
"=",
"r",
".",
"json",
"(",
")",
"[",
"'summary'",
"]",
"click",
".",
"echo",
"(",
"\... | Print a summary of a deployed app's status. | [
"Print",
"a",
"summary",
"of",
"a",
"deployed",
"app",
"s",
"status",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L224-L235 | train |
berkeley-cocosci/Wallace | wallace/command_line.py | scale_up_dynos | def scale_up_dynos(id):
"""Scale up the Heroku dynos."""
# Load psiTurk configuration.
config = PsiturkConfig()
config.load_config()
dyno_type = config.get('Server Parameters', 'dyno_type')
num_dynos_web = config.get('Server Parameters', 'num_dynos_web')
num_dynos_worker = config.get('Serve... | python | def scale_up_dynos(id):
"""Scale up the Heroku dynos."""
# Load psiTurk configuration.
config = PsiturkConfig()
config.load_config()
dyno_type = config.get('Server Parameters', 'dyno_type')
num_dynos_web = config.get('Server Parameters', 'num_dynos_web')
num_dynos_worker = config.get('Serve... | [
"def",
"scale_up_dynos",
"(",
"id",
")",
":",
"config",
"=",
"PsiturkConfig",
"(",
")",
"config",
".",
"load_config",
"(",
")",
"dyno_type",
"=",
"config",
".",
"get",
"(",
"'Server Parameters'",
",",
"'dyno_type'",
")",
"num_dynos_web",
"=",
"config",
".",
... | Scale up the Heroku dynos. | [
"Scale",
"up",
"the",
"Heroku",
"dynos",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L321-L344 | train |
berkeley-cocosci/Wallace | wallace/command_line.py | deploy | def deploy(verbose, app):
"""Deploy app using Heroku to MTurk."""
# Load psiTurk configuration.
config = PsiturkConfig()
config.load_config()
# Set the mode.
config.set("Experiment Configuration", "mode", "deploy")
config.set("Server Parameters", "logfile", "-")
# Ensure that psiTurk i... | python | def deploy(verbose, app):
"""Deploy app using Heroku to MTurk."""
# Load psiTurk configuration.
config = PsiturkConfig()
config.load_config()
# Set the mode.
config.set("Experiment Configuration", "mode", "deploy")
config.set("Server Parameters", "logfile", "-")
# Ensure that psiTurk i... | [
"def",
"deploy",
"(",
"verbose",
",",
"app",
")",
":",
"config",
"=",
"PsiturkConfig",
"(",
")",
"config",
".",
"load_config",
"(",
")",
"config",
".",
"set",
"(",
"\"Experiment Configuration\"",
",",
"\"mode\"",
",",
"\"deploy\"",
")",
"config",
".",
"set... | Deploy app using Heroku to MTurk. | [
"Deploy",
"app",
"using",
"Heroku",
"to",
"MTurk",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L513-L527 | train |
berkeley-cocosci/Wallace | wallace/command_line.py | qualify | def qualify(qualification, value, worker):
"""Assign a qualification to a worker."""
# create connection to AWS
from boto.mturk.connection import MTurkConnection
config = PsiturkConfig()
config.load_config()
aws_access_key_id = config.get('AWS Access', 'aws_access_key_id')
aws_secret_access_... | python | def qualify(qualification, value, worker):
"""Assign a qualification to a worker."""
# create connection to AWS
from boto.mturk.connection import MTurkConnection
config = PsiturkConfig()
config.load_config()
aws_access_key_id = config.get('AWS Access', 'aws_access_key_id')
aws_secret_access_... | [
"def",
"qualify",
"(",
"qualification",
",",
"value",
",",
"worker",
")",
":",
"from",
"boto",
".",
"mturk",
".",
"connection",
"import",
"MTurkConnection",
"config",
"=",
"PsiturkConfig",
"(",
")",
"config",
".",
"load_config",
"(",
")",
"aws_access_key_id",
... | Assign a qualification to a worker. | [
"Assign",
"a",
"qualification",
"to",
"a",
"worker",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L534-L593 | train |
berkeley-cocosci/Wallace | wallace/command_line.py | dump_database | def dump_database(id):
"""Backup the Postgres database locally."""
log("Generating a backup of the database on Heroku...")
dump_filename = "data.dump"
data_directory = "data"
dump_dir = os.path.join(data_directory, id)
if not os.path.exists(dump_dir):
os.makedirs(dump_dir)
subproce... | python | def dump_database(id):
"""Backup the Postgres database locally."""
log("Generating a backup of the database on Heroku...")
dump_filename = "data.dump"
data_directory = "data"
dump_dir = os.path.join(data_directory, id)
if not os.path.exists(dump_dir):
os.makedirs(dump_dir)
subproce... | [
"def",
"dump_database",
"(",
"id",
")",
":",
"log",
"(",
"\"Generating a backup of the database on Heroku...\"",
")",
"dump_filename",
"=",
"\"data.dump\"",
"data_directory",
"=",
"\"data\"",
"dump_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_directory",
",... | Backup the Postgres database locally. | [
"Backup",
"the",
"Postgres",
"database",
"locally",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L596-L619 | train |
berkeley-cocosci/Wallace | wallace/command_line.py | backup | def backup(app):
"""Dump the database."""
dump_path = dump_database(app)
config = PsiturkConfig()
config.load_config()
conn = boto.connect_s3(
config.get('AWS Access', 'aws_access_key_id'),
config.get('AWS Access', 'aws_secret_access_key'),
)
bucket = conn.create_bucket(
... | python | def backup(app):
"""Dump the database."""
dump_path = dump_database(app)
config = PsiturkConfig()
config.load_config()
conn = boto.connect_s3(
config.get('AWS Access', 'aws_access_key_id'),
config.get('AWS Access', 'aws_secret_access_key'),
)
bucket = conn.create_bucket(
... | [
"def",
"backup",
"(",
"app",
")",
":",
"dump_path",
"=",
"dump_database",
"(",
"app",
")",
"config",
"=",
"PsiturkConfig",
"(",
")",
"config",
".",
"load_config",
"(",
")",
"conn",
"=",
"boto",
".",
"connect_s3",
"(",
"config",
".",
"get",
"(",
"'AWS A... | Dump the database. | [
"Dump",
"the",
"database",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L622-L645 | train |
berkeley-cocosci/Wallace | wallace/command_line.py | create | def create(example):
"""Create a copy of the given example."""
try:
this_dir = os.path.dirname(os.path.realpath(__file__))
example_dir = os.path.join(this_dir, os.pardir, "examples", example)
shutil.copytree(example_dir, os.path.join(os.getcwd(), example))
log("Example created.",... | python | def create(example):
"""Create a copy of the given example."""
try:
this_dir = os.path.dirname(os.path.realpath(__file__))
example_dir = os.path.join(this_dir, os.pardir, "examples", example)
shutil.copytree(example_dir, os.path.join(os.getcwd(), example))
log("Example created.",... | [
"def",
"create",
"(",
"example",
")",
":",
"try",
":",
"this_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"example_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"this_dir",
",",... | Create a copy of the given example. | [
"Create",
"a",
"copy",
"of",
"the",
"given",
"example",
"."
] | 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L815-L825 | train |
brunato/lograptor | lograptor/timedate.py | get_datetime_interval | def get_datetime_interval(timestamp, diff, offset=0):
"""
Returns datetime interval from timestamp backward in the past,
computed using the milliseconds difference passed as argument.
The final datetime is corrected with an optional offset.
"""
fin_datetime = datetime.datetime.fromtimestamp(time... | python | def get_datetime_interval(timestamp, diff, offset=0):
"""
Returns datetime interval from timestamp backward in the past,
computed using the milliseconds difference passed as argument.
The final datetime is corrected with an optional offset.
"""
fin_datetime = datetime.datetime.fromtimestamp(time... | [
"def",
"get_datetime_interval",
"(",
"timestamp",
",",
"diff",
",",
"offset",
"=",
"0",
")",
":",
"fin_datetime",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
"+",
"offset",
")",
"ini_datetime",
"=",
"datetime",
".",
"datetime",
... | Returns datetime interval from timestamp backward in the past,
computed using the milliseconds difference passed as argument.
The final datetime is corrected with an optional offset. | [
"Returns",
"datetime",
"interval",
"from",
"timestamp",
"backward",
"in",
"the",
"past",
"computed",
"using",
"the",
"milliseconds",
"difference",
"passed",
"as",
"argument",
".",
"The",
"final",
"datetime",
"is",
"corrected",
"with",
"an",
"optional",
"offset",
... | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/timedate.py#L84-L92 | train |
brunato/lograptor | lograptor/timedate.py | strftimegen | def strftimegen(start_dt, end_dt):
"""
Return a generator function for datetime format strings.
The generator produce a day-by-day sequence starting from the first datetime
to the second datetime argument.
"""
if start_dt > end_dt:
raise ValueError("the start datetime is after the end da... | python | def strftimegen(start_dt, end_dt):
"""
Return a generator function for datetime format strings.
The generator produce a day-by-day sequence starting from the first datetime
to the second datetime argument.
"""
if start_dt > end_dt:
raise ValueError("the start datetime is after the end da... | [
"def",
"strftimegen",
"(",
"start_dt",
",",
"end_dt",
")",
":",
"if",
"start_dt",
">",
"end_dt",
":",
"raise",
"ValueError",
"(",
"\"the start datetime is after the end datetime: (%r,%r)\"",
"%",
"(",
"start_dt",
",",
"end_dt",
")",
")",
"def",
"iterftime",
"(",
... | Return a generator function for datetime format strings.
The generator produce a day-by-day sequence starting from the first datetime
to the second datetime argument. | [
"Return",
"a",
"generator",
"function",
"for",
"datetime",
"format",
"strings",
".",
"The",
"generator",
"produce",
"a",
"day",
"-",
"by",
"-",
"day",
"sequence",
"starting",
"from",
"the",
"first",
"datetime",
"to",
"the",
"second",
"datetime",
"argument",
... | b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/timedate.py#L181-L203 | train |
Kortemme-Lab/klab | klab/bio/fragments/generate_fragments.py | setup_jobs | def setup_jobs(outpath, options, input_files):
''' This function sets up the jobs by creating the necessary input files as expected.
- outpath is where the output is to be stored.
- options is the optparse options object.
- input_files is a list of paths to input files.
'''
jo... | python | def setup_jobs(outpath, options, input_files):
''' This function sets up the jobs by creating the necessary input files as expected.
- outpath is where the output is to be stored.
- options is the optparse options object.
- input_files is a list of paths to input files.
'''
jo... | [
"def",
"setup_jobs",
"(",
"outpath",
",",
"options",
",",
"input_files",
")",
":",
"job_inputs",
"=",
"None",
"reverse_mapping",
"=",
"None",
"fasta_file_contents",
"=",
"{",
"}",
"for",
"input_file",
"in",
"input_files",
":",
"assert",
"(",
"not",
"(",
"fas... | This function sets up the jobs by creating the necessary input files as expected.
- outpath is where the output is to be stored.
- options is the optparse options object.
- input_files is a list of paths to input files. | [
"This",
"function",
"sets",
"up",
"the",
"jobs",
"by",
"creating",
"the",
"necessary",
"input",
"files",
"as",
"expected",
".",
"-",
"outpath",
"is",
"where",
"the",
"output",
"is",
"to",
"be",
"stored",
".",
"-",
"options",
"is",
"the",
"optparse",
"opt... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/fragments/generate_fragments.py#L460-L520 | train |
Kortemme-Lab/klab | klab/bio/fragments/generate_fragments.py | reformat | def reformat(found_sequences):
'''Truncate the FASTA headers so that the first field is a 4-character ID.'''
for (pdb_id, chain, file_name), sequence in sorted(found_sequences.iteritems()):
header = sequence[0]
assert(header[0] == '>')
tokens = header.split('|')
tokens[0] = token... | python | def reformat(found_sequences):
'''Truncate the FASTA headers so that the first field is a 4-character ID.'''
for (pdb_id, chain, file_name), sequence in sorted(found_sequences.iteritems()):
header = sequence[0]
assert(header[0] == '>')
tokens = header.split('|')
tokens[0] = token... | [
"def",
"reformat",
"(",
"found_sequences",
")",
":",
"for",
"(",
"pdb_id",
",",
"chain",
",",
"file_name",
")",
",",
"sequence",
"in",
"sorted",
"(",
"found_sequences",
".",
"iteritems",
"(",
")",
")",
":",
"header",
"=",
"sequence",
"[",
"0",
"]",
"as... | Truncate the FASTA headers so that the first field is a 4-character ID. | [
"Truncate",
"the",
"FASTA",
"headers",
"so",
"that",
"the",
"first",
"field",
"is",
"a",
"4",
"-",
"character",
"ID",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/fragments/generate_fragments.py#L723-L731 | train |
Kortemme-Lab/klab | klab/bio/fragments/generate_fragments.py | search_configuration_files | def search_configuration_files(findstr, replacestr = None):
'''This function could be used to find and replace paths in the configuration files.
At present, it only finds phrases.'''
F = open(configurationFilesLocation, "r")
lines = F.readlines()
F.close()
allerrors = {}
alloutput = {}
... | python | def search_configuration_files(findstr, replacestr = None):
'''This function could be used to find and replace paths in the configuration files.
At present, it only finds phrases.'''
F = open(configurationFilesLocation, "r")
lines = F.readlines()
F.close()
allerrors = {}
alloutput = {}
... | [
"def",
"search_configuration_files",
"(",
"findstr",
",",
"replacestr",
"=",
"None",
")",
":",
"F",
"=",
"open",
"(",
"configurationFilesLocation",
",",
"\"r\"",
")",
"lines",
"=",
"F",
".",
"readlines",
"(",
")",
"F",
".",
"close",
"(",
")",
"allerrors",
... | This function could be used to find and replace paths in the configuration files.
At present, it only finds phrases. | [
"This",
"function",
"could",
"be",
"used",
"to",
"find",
"and",
"replace",
"paths",
"in",
"the",
"configuration",
"files",
".",
"At",
"present",
"it",
"only",
"finds",
"phrases",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/fragments/generate_fragments.py#L776-L804 | train |
ronhanson/python-tbx | tbx/network.py | get_local_ip_address | def get_local_ip_address(target):
"""
Get the local ip address to access one specific target.
"""
ip_adr = ''
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((target, 8000))
ip_adr = s.getsockname()[0]
s.close()
except:
pass
return... | python | def get_local_ip_address(target):
"""
Get the local ip address to access one specific target.
"""
ip_adr = ''
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((target, 8000))
ip_adr = s.getsockname()[0]
s.close()
except:
pass
return... | [
"def",
"get_local_ip_address",
"(",
"target",
")",
":",
"ip_adr",
"=",
"''",
"try",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"s",
".",
"connect",
"(",
"(",
"target",
",",
"8000",
")... | Get the local ip address to access one specific target. | [
"Get",
"the",
"local",
"ip",
"address",
"to",
"access",
"one",
"specific",
"target",
"."
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/network.py#L24-L37 | train |
ronhanson/python-tbx | tbx/network.py | SocketClient.connect | def connect(self):
"""
Connect socket to server
"""
try:
self.sock.connect((self.host, self.port))
return self.sock
except socket.error as ex:
logging.error('Exception while connecting socket on %s:%s - Error %s' % (self.host, self.port, ex))
... | python | def connect(self):
"""
Connect socket to server
"""
try:
self.sock.connect((self.host, self.port))
return self.sock
except socket.error as ex:
logging.error('Exception while connecting socket on %s:%s - Error %s' % (self.host, self.port, ex))
... | [
"def",
"connect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
")",
"return",
"self",
".",
"sock",
"except",
"socket",
".",
"error",
"as",
"ex",
":",
"loggin... | Connect socket to server | [
"Connect",
"socket",
"to",
"server"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/network.py#L97-L109 | train |
ronhanson/python-tbx | tbx/network.py | SocketClient.send_by_packet | def send_by_packet(self, data):
"""
Send data by packet on socket
"""
total_sent = 0
while total_sent < PACKET_SIZE:
sent = self.sock.send(data[total_sent:])
if sent == 0:
raise RuntimeError("socket connection broken")
total_sen... | python | def send_by_packet(self, data):
"""
Send data by packet on socket
"""
total_sent = 0
while total_sent < PACKET_SIZE:
sent = self.sock.send(data[total_sent:])
if sent == 0:
raise RuntimeError("socket connection broken")
total_sen... | [
"def",
"send_by_packet",
"(",
"self",
",",
"data",
")",
":",
"total_sent",
"=",
"0",
"while",
"total_sent",
"<",
"PACKET_SIZE",
":",
"sent",
"=",
"self",
".",
"sock",
".",
"send",
"(",
"data",
"[",
"total_sent",
":",
"]",
")",
"if",
"sent",
"==",
"0"... | Send data by packet on socket | [
"Send",
"data",
"by",
"packet",
"on",
"socket"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/network.py#L111-L121 | train |
ronhanson/python-tbx | tbx/network.py | SocketClient.receive | def receive(self, siz):
"""
Receive a known length of bytes from a socket
"""
result = bytearray()
data = 'x'
while len(data) > 0:
data = self.sock.recv(siz - len(result))
result += data
if len(result) == siz:
return res... | python | def receive(self, siz):
"""
Receive a known length of bytes from a socket
"""
result = bytearray()
data = 'x'
while len(data) > 0:
data = self.sock.recv(siz - len(result))
result += data
if len(result) == siz:
return res... | [
"def",
"receive",
"(",
"self",
",",
"siz",
")",
":",
"result",
"=",
"bytearray",
"(",
")",
"data",
"=",
"'x'",
"while",
"len",
"(",
"data",
")",
">",
"0",
":",
"data",
"=",
"self",
".",
"sock",
".",
"recv",
"(",
"siz",
"-",
"len",
"(",
"result"... | Receive a known length of bytes from a socket | [
"Receive",
"a",
"known",
"length",
"of",
"bytes",
"from",
"a",
"socket"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/network.py#L136-L149 | train |
assamite/creamas | creamas/mp.py | spawn_container | def spawn_container(addr, env_cls=Environment,
mgr_cls=EnvManager, set_seed=True, *args, **kwargs):
"""Spawn a new environment in a given address as a coroutine.
Arguments and keyword arguments are passed down to the created environment
at initialization time.
If `setproctitle <htt... | python | def spawn_container(addr, env_cls=Environment,
mgr_cls=EnvManager, set_seed=True, *args, **kwargs):
"""Spawn a new environment in a given address as a coroutine.
Arguments and keyword arguments are passed down to the created environment
at initialization time.
If `setproctitle <htt... | [
"def",
"spawn_container",
"(",
"addr",
",",
"env_cls",
"=",
"Environment",
",",
"mgr_cls",
"=",
"EnvManager",
",",
"set_seed",
"=",
"True",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"import",
"setproctitle",
"as",
"spt",
"title",
"=",
... | Spawn a new environment in a given address as a coroutine.
Arguments and keyword arguments are passed down to the created environment
at initialization time.
If `setproctitle <https://pypi.python.org/pypi/setproctitle>`_ is
installed, this function renames the title of the process to start with
'c... | [
"Spawn",
"a",
"new",
"environment",
"in",
"a",
"given",
"address",
"as",
"a",
"coroutine",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L886-L915 | train |
assamite/creamas | creamas/mp.py | _set_random_seeds | def _set_random_seeds():
"""Set new random seeds for the process.
"""
try:
import numpy as np
np.random.seed()
except:
pass
try:
import scipy as sp
sp.random.seed()
except:
pass
import random
random.seed() | python | def _set_random_seeds():
"""Set new random seeds for the process.
"""
try:
import numpy as np
np.random.seed()
except:
pass
try:
import scipy as sp
sp.random.seed()
except:
pass
import random
random.seed() | [
"def",
"_set_random_seeds",
"(",
")",
":",
"try",
":",
"import",
"numpy",
"as",
"np",
"np",
".",
"random",
".",
"seed",
"(",
")",
"except",
":",
"pass",
"try",
":",
"import",
"scipy",
"as",
"sp",
"sp",
".",
"random",
".",
"seed",
"(",
")",
"except"... | Set new random seeds for the process. | [
"Set",
"new",
"random",
"seeds",
"for",
"the",
"process",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L1007-L1023 | train |
assamite/creamas | creamas/mp.py | EnvManager.report | async def report(self, msg, timeout=5):
"""Report message to the host manager.
"""
try:
host_manager = await self.env.connect(self.host_manager,
timeout=timeout)
except:
raise ConnectionError("Could not reach host ... | python | async def report(self, msg, timeout=5):
"""Report message to the host manager.
"""
try:
host_manager = await self.env.connect(self.host_manager,
timeout=timeout)
except:
raise ConnectionError("Could not reach host ... | [
"async",
"def",
"report",
"(",
"self",
",",
"msg",
",",
"timeout",
"=",
"5",
")",
":",
"try",
":",
"host_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"self",
".",
"host_manager",
",",
"timeout",
"=",
"timeout",
")",
"except",
":",... | Report message to the host manager. | [
"Report",
"message",
"to",
"the",
"host",
"manager",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L77-L87 | train |
assamite/creamas | creamas/mp.py | EnvManager.get_agents | def get_agents(self, addr=True, agent_cls=None, as_coro=False):
"""Get agents from the managed environment.
This is a managing function for the
:py:meth:`~creamas.environment.Environment.get_agents`. Returned
agent list excludes the environment's manager agent (this agent) by
de... | python | def get_agents(self, addr=True, agent_cls=None, as_coro=False):
"""Get agents from the managed environment.
This is a managing function for the
:py:meth:`~creamas.environment.Environment.get_agents`. Returned
agent list excludes the environment's manager agent (this agent) by
de... | [
"def",
"get_agents",
"(",
"self",
",",
"addr",
"=",
"True",
",",
"agent_cls",
"=",
"None",
",",
"as_coro",
"=",
"False",
")",
":",
"return",
"self",
".",
"env",
".",
"get_agents",
"(",
"addr",
"=",
"addr",
",",
"agent_cls",
"=",
"agent_cls",
")"
] | Get agents from the managed environment.
This is a managing function for the
:py:meth:`~creamas.environment.Environment.get_agents`. Returned
agent list excludes the environment's manager agent (this agent) by
design. | [
"Get",
"agents",
"from",
"the",
"managed",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L96-L104 | train |
assamite/creamas | creamas/mp.py | EnvManager.get_artifacts | async def get_artifacts(self):
"""Get all artifacts from the host environment.
:returns: All the artifacts in the environment.
"""
host_manager = await self.env.connect(self._host_manager,
timeout=TIMEOUT)
artifacts = await host_mana... | python | async def get_artifacts(self):
"""Get all artifacts from the host environment.
:returns: All the artifacts in the environment.
"""
host_manager = await self.env.connect(self._host_manager,
timeout=TIMEOUT)
artifacts = await host_mana... | [
"async",
"def",
"get_artifacts",
"(",
"self",
")",
":",
"host_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"self",
".",
"_host_manager",
",",
"timeout",
"=",
"TIMEOUT",
")",
"artifacts",
"=",
"await",
"host_manager",
".",
"get_artifacts",... | Get all artifacts from the host environment.
:returns: All the artifacts in the environment. | [
"Get",
"all",
"artifacts",
"from",
"the",
"host",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L135-L143 | train |
assamite/creamas | creamas/mp.py | MultiEnvManager.spawn | async def spawn(self, agent_cls, *args, addr=None, **kwargs):
"""Spawn an agent to the environment.
This is a managing function for
:meth:`~creamas.mp.MultiEnvironment.spawn`.
.. note::
Since :class:`aiomas.rpc.Proxy` objects do not seem to handle
(re)serializa... | python | async def spawn(self, agent_cls, *args, addr=None, **kwargs):
"""Spawn an agent to the environment.
This is a managing function for
:meth:`~creamas.mp.MultiEnvironment.spawn`.
.. note::
Since :class:`aiomas.rpc.Proxy` objects do not seem to handle
(re)serializa... | [
"async",
"def",
"spawn",
"(",
"self",
",",
"agent_cls",
",",
"*",
"args",
",",
"addr",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"_",
",",
"addr",
"=",
"await",
"self",
".",
"menv",
".",
"spawn",
"(",
"agent_cls",
",",
"*",
"args",
",",
"addr",... | Spawn an agent to the environment.
This is a managing function for
:meth:`~creamas.mp.MultiEnvironment.spawn`.
.. note::
Since :class:`aiomas.rpc.Proxy` objects do not seem to handle
(re)serialization, only the address of the spawned agent is
returned. | [
"Spawn",
"an",
"agent",
"to",
"the",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L218-L231 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.