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/pdb.py | PDB.get_rosetta_sequence_to_atom_json_map | def get_rosetta_sequence_to_atom_json_map(self):
'''Returns the mapping from Rosetta residue IDs to PDB ATOM residue IDs in JSON format.'''
import json
if not self.rosetta_to_atom_sequence_maps and self.rosetta_sequences:
raise Exception('The PDB to Rosetta mapping has not been determined. Please call construct_pdb_to_rosetta_residue_map first.')
d = {}
for c, sm in self.rosetta_to_atom_sequence_maps.iteritems():
for k, v in sm.map.iteritems():
d[k] = v
#d[c] = sm.map
return json.dumps(d, indent = 4, sort_keys = True) | python | def get_rosetta_sequence_to_atom_json_map(self):
'''Returns the mapping from Rosetta residue IDs to PDB ATOM residue IDs in JSON format.'''
import json
if not self.rosetta_to_atom_sequence_maps and self.rosetta_sequences:
raise Exception('The PDB to Rosetta mapping has not been determined. Please call construct_pdb_to_rosetta_residue_map first.')
d = {}
for c, sm in self.rosetta_to_atom_sequence_maps.iteritems():
for k, v in sm.map.iteritems():
d[k] = v
#d[c] = sm.map
return json.dumps(d, indent = 4, sort_keys = True) | [
"def",
"get_rosetta_sequence_to_atom_json_map",
"(",
"self",
")",
":",
"import",
"json",
"if",
"not",
"self",
".",
"rosetta_to_atom_sequence_maps",
"and",
"self",
".",
"rosetta_sequences",
":",
"raise",
"Exception",
"(",
"'The PDB to Rosetta mapping has not been determined. Please call construct_pdb_to_rosetta_residue_map first.'",
")",
"d",
"=",
"{",
"}",
"for",
"c",
",",
"sm",
"in",
"self",
".",
"rosetta_to_atom_sequence_maps",
".",
"iteritems",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"sm",
".",
"map",
".",
"iteritems",
"(",
")",
":",
"d",
"[",
"k",
"]",
"=",
"v",
"#d[c] = sm.map",
"return",
"json",
".",
"dumps",
"(",
"d",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")"
]
| Returns the mapping from Rosetta residue IDs to PDB ATOM residue IDs in JSON format. | [
"Returns",
"the",
"mapping",
"from",
"Rosetta",
"residue",
"IDs",
"to",
"PDB",
"ATOM",
"residue",
"IDs",
"in",
"JSON",
"format",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L1755-L1766 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.assert_wildtype_matches | def assert_wildtype_matches(self, mutation):
'''Check that the wildtype of the Mutation object matches the PDB sequence.'''
readwt = self.getAminoAcid(self.getAtomLine(mutation.Chain, mutation.ResidueID))
assert(mutation.WildTypeAA == residue_type_3to1_map[readwt]) | python | def assert_wildtype_matches(self, mutation):
'''Check that the wildtype of the Mutation object matches the PDB sequence.'''
readwt = self.getAminoAcid(self.getAtomLine(mutation.Chain, mutation.ResidueID))
assert(mutation.WildTypeAA == residue_type_3to1_map[readwt]) | [
"def",
"assert_wildtype_matches",
"(",
"self",
",",
"mutation",
")",
":",
"readwt",
"=",
"self",
".",
"getAminoAcid",
"(",
"self",
".",
"getAtomLine",
"(",
"mutation",
".",
"Chain",
",",
"mutation",
".",
"ResidueID",
")",
")",
"assert",
"(",
"mutation",
".",
"WildTypeAA",
"==",
"residue_type_3to1_map",
"[",
"readwt",
"]",
")"
]
| Check that the wildtype of the Mutation object matches the PDB sequence. | [
"Check",
"that",
"the",
"wildtype",
"of",
"the",
"Mutation",
"object",
"matches",
"the",
"PDB",
"sequence",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L1788-L1791 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.get_B_factors | def get_B_factors(self, force = False):
'''This reads in all ATOM lines and compute the mean and standard deviation of each
residue's B-factors. It returns a table of the mean and standard deviation per
residue as well as the mean and standard deviation over all residues with each
residue having equal weighting.
Whether the atom is occupied or not is not taken into account.'''
# Read in the list of bfactors for each ATOM line.
if (not self.bfactors) or (force == True):
bfactors = {}
old_chain_residue_id = None
for line in self.lines:
if line[0:4] == "ATOM":
chain_residue_id = line[21:27]
if chain_residue_id != old_chain_residue_id:
bfactors[chain_residue_id] = []
old_chain_residue_id = chain_residue_id
bfactors[chain_residue_id].append(float(line[60:66]))
# Compute the mean and standard deviation for the list of B-factors of each residue
B_factor_per_residue = {}
mean_per_residue = []
for chain_residue_id, bfactor_list in bfactors.iteritems():
mean, stddev, variance = get_mean_and_standard_deviation(bfactor_list)
B_factor_per_residue[chain_residue_id] = dict(mean = mean, stddev = stddev)
mean_per_residue.append(mean)
total_average, total_standard_deviation, variance = get_mean_and_standard_deviation(mean_per_residue)
self.bfactors = dict(
Overall = dict(mean = total_average, stddev = total_standard_deviation),
PerResidue = B_factor_per_residue,
)
return self.bfactors | python | def get_B_factors(self, force = False):
'''This reads in all ATOM lines and compute the mean and standard deviation of each
residue's B-factors. It returns a table of the mean and standard deviation per
residue as well as the mean and standard deviation over all residues with each
residue having equal weighting.
Whether the atom is occupied or not is not taken into account.'''
# Read in the list of bfactors for each ATOM line.
if (not self.bfactors) or (force == True):
bfactors = {}
old_chain_residue_id = None
for line in self.lines:
if line[0:4] == "ATOM":
chain_residue_id = line[21:27]
if chain_residue_id != old_chain_residue_id:
bfactors[chain_residue_id] = []
old_chain_residue_id = chain_residue_id
bfactors[chain_residue_id].append(float(line[60:66]))
# Compute the mean and standard deviation for the list of B-factors of each residue
B_factor_per_residue = {}
mean_per_residue = []
for chain_residue_id, bfactor_list in bfactors.iteritems():
mean, stddev, variance = get_mean_and_standard_deviation(bfactor_list)
B_factor_per_residue[chain_residue_id] = dict(mean = mean, stddev = stddev)
mean_per_residue.append(mean)
total_average, total_standard_deviation, variance = get_mean_and_standard_deviation(mean_per_residue)
self.bfactors = dict(
Overall = dict(mean = total_average, stddev = total_standard_deviation),
PerResidue = B_factor_per_residue,
)
return self.bfactors | [
"def",
"get_B_factors",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"# Read in the list of bfactors for each ATOM line.",
"if",
"(",
"not",
"self",
".",
"bfactors",
")",
"or",
"(",
"force",
"==",
"True",
")",
":",
"bfactors",
"=",
"{",
"}",
"old_chain_residue_id",
"=",
"None",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"if",
"line",
"[",
"0",
":",
"4",
"]",
"==",
"\"ATOM\"",
":",
"chain_residue_id",
"=",
"line",
"[",
"21",
":",
"27",
"]",
"if",
"chain_residue_id",
"!=",
"old_chain_residue_id",
":",
"bfactors",
"[",
"chain_residue_id",
"]",
"=",
"[",
"]",
"old_chain_residue_id",
"=",
"chain_residue_id",
"bfactors",
"[",
"chain_residue_id",
"]",
".",
"append",
"(",
"float",
"(",
"line",
"[",
"60",
":",
"66",
"]",
")",
")",
"# Compute the mean and standard deviation for the list of B-factors of each residue",
"B_factor_per_residue",
"=",
"{",
"}",
"mean_per_residue",
"=",
"[",
"]",
"for",
"chain_residue_id",
",",
"bfactor_list",
"in",
"bfactors",
".",
"iteritems",
"(",
")",
":",
"mean",
",",
"stddev",
",",
"variance",
"=",
"get_mean_and_standard_deviation",
"(",
"bfactor_list",
")",
"B_factor_per_residue",
"[",
"chain_residue_id",
"]",
"=",
"dict",
"(",
"mean",
"=",
"mean",
",",
"stddev",
"=",
"stddev",
")",
"mean_per_residue",
".",
"append",
"(",
"mean",
")",
"total_average",
",",
"total_standard_deviation",
",",
"variance",
"=",
"get_mean_and_standard_deviation",
"(",
"mean_per_residue",
")",
"self",
".",
"bfactors",
"=",
"dict",
"(",
"Overall",
"=",
"dict",
"(",
"mean",
"=",
"total_average",
",",
"stddev",
"=",
"total_standard_deviation",
")",
",",
"PerResidue",
"=",
"B_factor_per_residue",
",",
")",
"return",
"self",
".",
"bfactors"
]
| This reads in all ATOM lines and compute the mean and standard deviation of each
residue's B-factors. It returns a table of the mean and standard deviation per
residue as well as the mean and standard deviation over all residues with each
residue having equal weighting.
Whether the atom is occupied or not is not taken into account. | [
"This",
"reads",
"in",
"all",
"ATOM",
"lines",
"and",
"compute",
"the",
"mean",
"and",
"standard",
"deviation",
"of",
"each",
"residue",
"s",
"B",
"-",
"factors",
".",
"It",
"returns",
"a",
"table",
"of",
"the",
"mean",
"and",
"standard",
"deviation",
"per",
"residue",
"as",
"well",
"as",
"the",
"mean",
"and",
"standard",
"deviation",
"over",
"all",
"residues",
"with",
"each",
"residue",
"having",
"equal",
"weighting",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2071-L2104 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.validate_mutations | def validate_mutations(self, mutations):
'''This function has been refactored to use the SimpleMutation class.
The parameter is a list of Mutation objects. The function has no return value but raises a PDBValidationException
if the wildtype in the Mutation m does not match the residue type corresponding to residue m.ResidueID in the PDB file.
'''
# Chain, ResidueID, WildTypeAA, MutantAA
resID2AA = self.get_residue_id_to_type_map()
badmutations = []
for m in mutations:
wildtype = resID2AA.get(PDB.ChainResidueID2String(m.Chain, m.ResidueID), "")
if m.WildTypeAA != wildtype:
badmutations.append(m)
if badmutations:
raise PDBValidationException("The mutation(s) %s could not be matched against the PDB %s." % (", ".join(map(str, badmutations)), self.pdb_id)) | python | def validate_mutations(self, mutations):
'''This function has been refactored to use the SimpleMutation class.
The parameter is a list of Mutation objects. The function has no return value but raises a PDBValidationException
if the wildtype in the Mutation m does not match the residue type corresponding to residue m.ResidueID in the PDB file.
'''
# Chain, ResidueID, WildTypeAA, MutantAA
resID2AA = self.get_residue_id_to_type_map()
badmutations = []
for m in mutations:
wildtype = resID2AA.get(PDB.ChainResidueID2String(m.Chain, m.ResidueID), "")
if m.WildTypeAA != wildtype:
badmutations.append(m)
if badmutations:
raise PDBValidationException("The mutation(s) %s could not be matched against the PDB %s." % (", ".join(map(str, badmutations)), self.pdb_id)) | [
"def",
"validate_mutations",
"(",
"self",
",",
"mutations",
")",
":",
"# Chain, ResidueID, WildTypeAA, MutantAA",
"resID2AA",
"=",
"self",
".",
"get_residue_id_to_type_map",
"(",
")",
"badmutations",
"=",
"[",
"]",
"for",
"m",
"in",
"mutations",
":",
"wildtype",
"=",
"resID2AA",
".",
"get",
"(",
"PDB",
".",
"ChainResidueID2String",
"(",
"m",
".",
"Chain",
",",
"m",
".",
"ResidueID",
")",
",",
"\"\"",
")",
"if",
"m",
".",
"WildTypeAA",
"!=",
"wildtype",
":",
"badmutations",
".",
"append",
"(",
"m",
")",
"if",
"badmutations",
":",
"raise",
"PDBValidationException",
"(",
"\"The mutation(s) %s could not be matched against the PDB %s.\"",
"%",
"(",
"\", \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"badmutations",
")",
")",
",",
"self",
".",
"pdb_id",
")",
")"
]
| This function has been refactored to use the SimpleMutation class.
The parameter is a list of Mutation objects. The function has no return value but raises a PDBValidationException
if the wildtype in the Mutation m does not match the residue type corresponding to residue m.ResidueID in the PDB file. | [
"This",
"function",
"has",
"been",
"refactored",
"to",
"use",
"the",
"SimpleMutation",
"class",
".",
"The",
"parameter",
"is",
"a",
"list",
"of",
"Mutation",
"objects",
".",
"The",
"function",
"has",
"no",
"return",
"value",
"but",
"raises",
"a",
"PDBValidationException",
"if",
"the",
"wildtype",
"in",
"the",
"Mutation",
"m",
"does",
"not",
"match",
"the",
"residue",
"type",
"corresponding",
"to",
"residue",
"m",
".",
"ResidueID",
"in",
"the",
"PDB",
"file",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2252-L2265 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.fix_chain_id | def fix_chain_id(self):
"""fill in missing chain identifier"""
for i in xrange(len(self.lines)):
line = self.lines[i]
if line.startswith("ATOM") and line[21] == ' ':
self.lines[i] = line[:21] + 'A' + line[22:] | python | def fix_chain_id(self):
"""fill in missing chain identifier"""
for i in xrange(len(self.lines)):
line = self.lines[i]
if line.startswith("ATOM") and line[21] == ' ':
self.lines[i] = line[:21] + 'A' + line[22:] | [
"def",
"fix_chain_id",
"(",
"self",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"lines",
")",
")",
":",
"line",
"=",
"self",
".",
"lines",
"[",
"i",
"]",
"if",
"line",
".",
"startswith",
"(",
"\"ATOM\"",
")",
"and",
"line",
"[",
"21",
"]",
"==",
"' '",
":",
"self",
".",
"lines",
"[",
"i",
"]",
"=",
"line",
"[",
":",
"21",
"]",
"+",
"'A'",
"+",
"line",
"[",
"22",
":",
"]"
]
| fill in missing chain identifier | [
"fill",
"in",
"missing",
"chain",
"identifier"
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2308-L2314 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.getAtomLine | def getAtomLine(self, chain, resid):
'''This function assumes that all lines are ATOM or HETATM lines.
resid should have the proper PDB format i.e. an integer left-padded
to length 4 followed by the insertion code which may be a blank space.'''
for line in self.lines:
fieldtype = line[0:6].strip()
assert(fieldtype == "ATOM" or fieldtype == "HETATM")
if line[21:22] == chain and resid == line[22:27]:
return line
raise Exception("Could not find the ATOM/HETATM line corresponding to chain '%(chain)s' and residue '%(resid)s'." % vars()) | python | def getAtomLine(self, chain, resid):
'''This function assumes that all lines are ATOM or HETATM lines.
resid should have the proper PDB format i.e. an integer left-padded
to length 4 followed by the insertion code which may be a blank space.'''
for line in self.lines:
fieldtype = line[0:6].strip()
assert(fieldtype == "ATOM" or fieldtype == "HETATM")
if line[21:22] == chain and resid == line[22:27]:
return line
raise Exception("Could not find the ATOM/HETATM line corresponding to chain '%(chain)s' and residue '%(resid)s'." % vars()) | [
"def",
"getAtomLine",
"(",
"self",
",",
"chain",
",",
"resid",
")",
":",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"fieldtype",
"=",
"line",
"[",
"0",
":",
"6",
"]",
".",
"strip",
"(",
")",
"assert",
"(",
"fieldtype",
"==",
"\"ATOM\"",
"or",
"fieldtype",
"==",
"\"HETATM\"",
")",
"if",
"line",
"[",
"21",
":",
"22",
"]",
"==",
"chain",
"and",
"resid",
"==",
"line",
"[",
"22",
":",
"27",
"]",
":",
"return",
"line",
"raise",
"Exception",
"(",
"\"Could not find the ATOM/HETATM line corresponding to chain '%(chain)s' and residue '%(resid)s'.\"",
"%",
"vars",
"(",
")",
")"
]
| This function assumes that all lines are ATOM or HETATM lines.
resid should have the proper PDB format i.e. an integer left-padded
to length 4 followed by the insertion code which may be a blank space. | [
"This",
"function",
"assumes",
"that",
"all",
"lines",
"are",
"ATOM",
"or",
"HETATM",
"lines",
".",
"resid",
"should",
"have",
"the",
"proper",
"PDB",
"format",
"i",
".",
"e",
".",
"an",
"integer",
"left",
"-",
"padded",
"to",
"length",
"4",
"followed",
"by",
"the",
"insertion",
"code",
"which",
"may",
"be",
"a",
"blank",
"space",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2329-L2338 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.getAtomLinesForResidueInRosettaStructure | def getAtomLinesForResidueInRosettaStructure(self, resid):
'''We assume a Rosetta-generated structure where residues are uniquely identified by number.'''
lines = [line for line in self.lines if line[0:4] == "ATOM" and resid == int(line[22:27])]
if not lines:
#print('Failed searching for residue %d.' % resid)
#print("".join([line for line in self.lines if line[0:4] == "ATOM"]))
raise Exception("Could not find the ATOM/HETATM line corresponding to residue '%(resid)s'." % vars())
return lines | python | def getAtomLinesForResidueInRosettaStructure(self, resid):
'''We assume a Rosetta-generated structure where residues are uniquely identified by number.'''
lines = [line for line in self.lines if line[0:4] == "ATOM" and resid == int(line[22:27])]
if not lines:
#print('Failed searching for residue %d.' % resid)
#print("".join([line for line in self.lines if line[0:4] == "ATOM"]))
raise Exception("Could not find the ATOM/HETATM line corresponding to residue '%(resid)s'." % vars())
return lines | [
"def",
"getAtomLinesForResidueInRosettaStructure",
"(",
"self",
",",
"resid",
")",
":",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"self",
".",
"lines",
"if",
"line",
"[",
"0",
":",
"4",
"]",
"==",
"\"ATOM\"",
"and",
"resid",
"==",
"int",
"(",
"line",
"[",
"22",
":",
"27",
"]",
")",
"]",
"if",
"not",
"lines",
":",
"#print('Failed searching for residue %d.' % resid)",
"#print(\"\".join([line for line in self.lines if line[0:4] == \"ATOM\"]))",
"raise",
"Exception",
"(",
"\"Could not find the ATOM/HETATM line corresponding to residue '%(resid)s'.\"",
"%",
"vars",
"(",
")",
")",
"return",
"lines"
]
| We assume a Rosetta-generated structure where residues are uniquely identified by number. | [
"We",
"assume",
"a",
"Rosetta",
"-",
"generated",
"structure",
"where",
"residues",
"are",
"uniquely",
"identified",
"by",
"number",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2340-L2347 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.stripForDDG | def stripForDDG(self, chains = True, keepHETATM = False, numberOfModels = None, raise_exception = True):
'''Strips a PDB to ATOM lines. If keepHETATM is True then also retain HETATM lines.
By default all PDB chains are kept. The chains parameter should be True or a list.
In the latter case, only those chains in the list are kept.
Unoccupied ATOM lines are discarded.
This function also builds maps from PDB numbering to Rosetta numbering and vice versa.
'''
if raise_exception:
raise Exception('This code is deprecated.')
from Bio.PDB import PDBParser
resmap = {}
iresmap = {}
newlines = []
residx = 0
oldres = None
model_number = 1
for line in self.lines:
fieldtype = line[0:6].strip()
if fieldtype == "ENDMDL":
model_number += 1
if numberOfModels and (model_number > numberOfModels):
break
if not numberOfModels:
raise Exception("The logic here does not handle multiple models yet.")
if (fieldtype == "ATOM" or (fieldtype == "HETATM" and keepHETATM)) and (float(line[54:60]) != 0):
chain = line[21:22]
if (chains == True) or (chain in chains):
resid = line[21:27] # Chain, residue sequence number, insertion code
iCode = line[26:27]
if resid != oldres:
residx += 1
newnumbering = "%s%4.i " % (chain, residx)
assert(len(newnumbering) == 6)
id = fieldtype + "-" + resid
resmap[id] = residx
iresmap[residx] = id
oldres = resid
oldlength = len(line)
# Add the original line back including the chain [21] and inserting a blank for the insertion code
line = "%s%4.i %s" % (line[0:22], resmap[fieldtype + "-" + resid], line[27:])
assert(len(line) == oldlength)
newlines.append(line)
self.lines = newlines
self.ddGresmap = resmap
self.ddGiresmap = iresmap
# Sanity check against a known library
tmpfile = "/tmp/ddgtemp.pdb"
self.lines = self.lines or ["\n"] # necessary to avoid a crash in the Bio Python module
F = open(tmpfile,'w')
F.write(string.join(self.lines, "\n"))
F.close()
parser=PDBParser()
structure=parser.get_structure('tmp', tmpfile)
os.remove(tmpfile)
count = 0
for residue in structure.get_residues():
count += 1
assert(count == residx)
assert(len(resmap) == len(iresmap)) | python | def stripForDDG(self, chains = True, keepHETATM = False, numberOfModels = None, raise_exception = True):
'''Strips a PDB to ATOM lines. If keepHETATM is True then also retain HETATM lines.
By default all PDB chains are kept. The chains parameter should be True or a list.
In the latter case, only those chains in the list are kept.
Unoccupied ATOM lines are discarded.
This function also builds maps from PDB numbering to Rosetta numbering and vice versa.
'''
if raise_exception:
raise Exception('This code is deprecated.')
from Bio.PDB import PDBParser
resmap = {}
iresmap = {}
newlines = []
residx = 0
oldres = None
model_number = 1
for line in self.lines:
fieldtype = line[0:6].strip()
if fieldtype == "ENDMDL":
model_number += 1
if numberOfModels and (model_number > numberOfModels):
break
if not numberOfModels:
raise Exception("The logic here does not handle multiple models yet.")
if (fieldtype == "ATOM" or (fieldtype == "HETATM" and keepHETATM)) and (float(line[54:60]) != 0):
chain = line[21:22]
if (chains == True) or (chain in chains):
resid = line[21:27] # Chain, residue sequence number, insertion code
iCode = line[26:27]
if resid != oldres:
residx += 1
newnumbering = "%s%4.i " % (chain, residx)
assert(len(newnumbering) == 6)
id = fieldtype + "-" + resid
resmap[id] = residx
iresmap[residx] = id
oldres = resid
oldlength = len(line)
# Add the original line back including the chain [21] and inserting a blank for the insertion code
line = "%s%4.i %s" % (line[0:22], resmap[fieldtype + "-" + resid], line[27:])
assert(len(line) == oldlength)
newlines.append(line)
self.lines = newlines
self.ddGresmap = resmap
self.ddGiresmap = iresmap
# Sanity check against a known library
tmpfile = "/tmp/ddgtemp.pdb"
self.lines = self.lines or ["\n"] # necessary to avoid a crash in the Bio Python module
F = open(tmpfile,'w')
F.write(string.join(self.lines, "\n"))
F.close()
parser=PDBParser()
structure=parser.get_structure('tmp', tmpfile)
os.remove(tmpfile)
count = 0
for residue in structure.get_residues():
count += 1
assert(count == residx)
assert(len(resmap) == len(iresmap)) | [
"def",
"stripForDDG",
"(",
"self",
",",
"chains",
"=",
"True",
",",
"keepHETATM",
"=",
"False",
",",
"numberOfModels",
"=",
"None",
",",
"raise_exception",
"=",
"True",
")",
":",
"if",
"raise_exception",
":",
"raise",
"Exception",
"(",
"'This code is deprecated.'",
")",
"from",
"Bio",
".",
"PDB",
"import",
"PDBParser",
"resmap",
"=",
"{",
"}",
"iresmap",
"=",
"{",
"}",
"newlines",
"=",
"[",
"]",
"residx",
"=",
"0",
"oldres",
"=",
"None",
"model_number",
"=",
"1",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"fieldtype",
"=",
"line",
"[",
"0",
":",
"6",
"]",
".",
"strip",
"(",
")",
"if",
"fieldtype",
"==",
"\"ENDMDL\"",
":",
"model_number",
"+=",
"1",
"if",
"numberOfModels",
"and",
"(",
"model_number",
">",
"numberOfModels",
")",
":",
"break",
"if",
"not",
"numberOfModels",
":",
"raise",
"Exception",
"(",
"\"The logic here does not handle multiple models yet.\"",
")",
"if",
"(",
"fieldtype",
"==",
"\"ATOM\"",
"or",
"(",
"fieldtype",
"==",
"\"HETATM\"",
"and",
"keepHETATM",
")",
")",
"and",
"(",
"float",
"(",
"line",
"[",
"54",
":",
"60",
"]",
")",
"!=",
"0",
")",
":",
"chain",
"=",
"line",
"[",
"21",
":",
"22",
"]",
"if",
"(",
"chains",
"==",
"True",
")",
"or",
"(",
"chain",
"in",
"chains",
")",
":",
"resid",
"=",
"line",
"[",
"21",
":",
"27",
"]",
"# Chain, residue sequence number, insertion code",
"iCode",
"=",
"line",
"[",
"26",
":",
"27",
"]",
"if",
"resid",
"!=",
"oldres",
":",
"residx",
"+=",
"1",
"newnumbering",
"=",
"\"%s%4.i \"",
"%",
"(",
"chain",
",",
"residx",
")",
"assert",
"(",
"len",
"(",
"newnumbering",
")",
"==",
"6",
")",
"id",
"=",
"fieldtype",
"+",
"\"-\"",
"+",
"resid",
"resmap",
"[",
"id",
"]",
"=",
"residx",
"iresmap",
"[",
"residx",
"]",
"=",
"id",
"oldres",
"=",
"resid",
"oldlength",
"=",
"len",
"(",
"line",
")",
"# Add the original line back including the chain [21] and inserting a blank for the insertion code",
"line",
"=",
"\"%s%4.i %s\"",
"%",
"(",
"line",
"[",
"0",
":",
"22",
"]",
",",
"resmap",
"[",
"fieldtype",
"+",
"\"-\"",
"+",
"resid",
"]",
",",
"line",
"[",
"27",
":",
"]",
")",
"assert",
"(",
"len",
"(",
"line",
")",
"==",
"oldlength",
")",
"newlines",
".",
"append",
"(",
"line",
")",
"self",
".",
"lines",
"=",
"newlines",
"self",
".",
"ddGresmap",
"=",
"resmap",
"self",
".",
"ddGiresmap",
"=",
"iresmap",
"# Sanity check against a known library",
"tmpfile",
"=",
"\"/tmp/ddgtemp.pdb\"",
"self",
".",
"lines",
"=",
"self",
".",
"lines",
"or",
"[",
"\"\\n\"",
"]",
"# necessary to avoid a crash in the Bio Python module",
"F",
"=",
"open",
"(",
"tmpfile",
",",
"'w'",
")",
"F",
".",
"write",
"(",
"string",
".",
"join",
"(",
"self",
".",
"lines",
",",
"\"\\n\"",
")",
")",
"F",
".",
"close",
"(",
")",
"parser",
"=",
"PDBParser",
"(",
")",
"structure",
"=",
"parser",
".",
"get_structure",
"(",
"'tmp'",
",",
"tmpfile",
")",
"os",
".",
"remove",
"(",
"tmpfile",
")",
"count",
"=",
"0",
"for",
"residue",
"in",
"structure",
".",
"get_residues",
"(",
")",
":",
"count",
"+=",
"1",
"assert",
"(",
"count",
"==",
"residx",
")",
"assert",
"(",
"len",
"(",
"resmap",
")",
"==",
"len",
"(",
"iresmap",
")",
")"
]
| Strips a PDB to ATOM lines. If keepHETATM is True then also retain HETATM lines.
By default all PDB chains are kept. The chains parameter should be True or a list.
In the latter case, only those chains in the list are kept.
Unoccupied ATOM lines are discarded.
This function also builds maps from PDB numbering to Rosetta numbering and vice versa. | [
"Strips",
"a",
"PDB",
"to",
"ATOM",
"lines",
".",
"If",
"keepHETATM",
"is",
"True",
"then",
"also",
"retain",
"HETATM",
"lines",
".",
"By",
"default",
"all",
"PDB",
"chains",
"are",
"kept",
".",
"The",
"chains",
"parameter",
"should",
"be",
"True",
"or",
"a",
"list",
".",
"In",
"the",
"latter",
"case",
"only",
"those",
"chains",
"in",
"the",
"list",
"are",
"kept",
".",
"Unoccupied",
"ATOM",
"lines",
"are",
"discarded",
".",
"This",
"function",
"also",
"builds",
"maps",
"from",
"PDB",
"numbering",
"to",
"Rosetta",
"numbering",
"and",
"vice",
"versa",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2372-L2432 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.CheckForPresenceOf | def CheckForPresenceOf(self, reslist):
'''This checks whether residues in reslist exist in the ATOM lines.
It returns a list of the residues in reslist which did exist.'''
if type(reslist) == type(""):
reslist = [reslist]
foundRes = {}
for line in self.lines:
resname = line[17:20]
if line[0:4] == "ATOM":
if resname in reslist:
foundRes[resname] = True
return foundRes.keys() | python | def CheckForPresenceOf(self, reslist):
'''This checks whether residues in reslist exist in the ATOM lines.
It returns a list of the residues in reslist which did exist.'''
if type(reslist) == type(""):
reslist = [reslist]
foundRes = {}
for line in self.lines:
resname = line[17:20]
if line[0:4] == "ATOM":
if resname in reslist:
foundRes[resname] = True
return foundRes.keys() | [
"def",
"CheckForPresenceOf",
"(",
"self",
",",
"reslist",
")",
":",
"if",
"type",
"(",
"reslist",
")",
"==",
"type",
"(",
"\"\"",
")",
":",
"reslist",
"=",
"[",
"reslist",
"]",
"foundRes",
"=",
"{",
"}",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"resname",
"=",
"line",
"[",
"17",
":",
"20",
"]",
"if",
"line",
"[",
"0",
":",
"4",
"]",
"==",
"\"ATOM\"",
":",
"if",
"resname",
"in",
"reslist",
":",
"foundRes",
"[",
"resname",
"]",
"=",
"True",
"return",
"foundRes",
".",
"keys",
"(",
")"
]
| This checks whether residues in reslist exist in the ATOM lines.
It returns a list of the residues in reslist which did exist. | [
"This",
"checks",
"whether",
"residues",
"in",
"reslist",
"exist",
"in",
"the",
"ATOM",
"lines",
".",
"It",
"returns",
"a",
"list",
"of",
"the",
"residues",
"in",
"reslist",
"which",
"did",
"exist",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2475-L2488 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.fix_residue_numbering | def fix_residue_numbering(self):
"""this function renumbers the res ids in order to avoid strange behaviour of Rosetta"""
resid_list = self.aa_resids()
resid_set = set(resid_list)
resid_lst1 = list(resid_set)
resid_lst1.sort()
map_res_id = {}
x = 1
old_chain = resid_lst1[0][0]
for resid in resid_lst1:
map_res_id[resid] = resid[0] + '%4.i' % x
if resid[0] == old_chain:
x+=1
else:
x = 1
old_chain = resid[0]
atomlines = []
for line in self.lines:
if line[0:4] == "ATOM" and line[21:26] in resid_set and line[26] == ' ':
lst = [char for char in line]
#lst.remove('\n')
lst[21:26] = map_res_id[line[21:26]]
atomlines.append( string.join(lst,'') )
#print string.join(lst,'')
else:
atomlines.append(line)
self.lines = atomlines
return map_res_id | python | def fix_residue_numbering(self):
"""this function renumbers the res ids in order to avoid strange behaviour of Rosetta"""
resid_list = self.aa_resids()
resid_set = set(resid_list)
resid_lst1 = list(resid_set)
resid_lst1.sort()
map_res_id = {}
x = 1
old_chain = resid_lst1[0][0]
for resid in resid_lst1:
map_res_id[resid] = resid[0] + '%4.i' % x
if resid[0] == old_chain:
x+=1
else:
x = 1
old_chain = resid[0]
atomlines = []
for line in self.lines:
if line[0:4] == "ATOM" and line[21:26] in resid_set and line[26] == ' ':
lst = [char for char in line]
#lst.remove('\n')
lst[21:26] = map_res_id[line[21:26]]
atomlines.append( string.join(lst,'') )
#print string.join(lst,'')
else:
atomlines.append(line)
self.lines = atomlines
return map_res_id | [
"def",
"fix_residue_numbering",
"(",
"self",
")",
":",
"resid_list",
"=",
"self",
".",
"aa_resids",
"(",
")",
"resid_set",
"=",
"set",
"(",
"resid_list",
")",
"resid_lst1",
"=",
"list",
"(",
"resid_set",
")",
"resid_lst1",
".",
"sort",
"(",
")",
"map_res_id",
"=",
"{",
"}",
"x",
"=",
"1",
"old_chain",
"=",
"resid_lst1",
"[",
"0",
"]",
"[",
"0",
"]",
"for",
"resid",
"in",
"resid_lst1",
":",
"map_res_id",
"[",
"resid",
"]",
"=",
"resid",
"[",
"0",
"]",
"+",
"'%4.i'",
"%",
"x",
"if",
"resid",
"[",
"0",
"]",
"==",
"old_chain",
":",
"x",
"+=",
"1",
"else",
":",
"x",
"=",
"1",
"old_chain",
"=",
"resid",
"[",
"0",
"]",
"atomlines",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"if",
"line",
"[",
"0",
":",
"4",
"]",
"==",
"\"ATOM\"",
"and",
"line",
"[",
"21",
":",
"26",
"]",
"in",
"resid_set",
"and",
"line",
"[",
"26",
"]",
"==",
"' '",
":",
"lst",
"=",
"[",
"char",
"for",
"char",
"in",
"line",
"]",
"#lst.remove('\\n')",
"lst",
"[",
"21",
":",
"26",
"]",
"=",
"map_res_id",
"[",
"line",
"[",
"21",
":",
"26",
"]",
"]",
"atomlines",
".",
"append",
"(",
"string",
".",
"join",
"(",
"lst",
",",
"''",
")",
")",
"#print string.join(lst,'')",
"else",
":",
"atomlines",
".",
"append",
"(",
"line",
")",
"self",
".",
"lines",
"=",
"atomlines",
"return",
"map_res_id"
]
| this function renumbers the res ids in order to avoid strange behaviour of Rosetta | [
"this",
"function",
"renumbers",
"the",
"res",
"ids",
"in",
"order",
"to",
"avoid",
"strange",
"behaviour",
"of",
"Rosetta"
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2542-L2573 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.neighbors2 | def neighbors2(self, distance, chain_residue, atom = None, resid_list = None):
#atom = " CA "
'''this one is more precise since it uses the chain identifier also'''
if atom == None: # consider all atoms
lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types]
else: # consider only given atoms
lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types and line[12:16] == atom]
shash = spatialhash.SpatialHash(distance)
for line in lines:
pos = (float(line[30:38]), float(line[38:46]), float(line[46:54]))
shash.insert(pos, line[21:26])
neighbor_list = []
for line in lines:
resid = line[21:26]
if resid == chain_residue:
pos = (float(line[30:38]), float(line[38:46]), float(line[46:54]))
for data in shash.nearby(pos, distance):
if data[1] not in neighbor_list:
neighbor_list.append(data[1])
neighbor_list.sort()
return neighbor_list | python | def neighbors2(self, distance, chain_residue, atom = None, resid_list = None):
#atom = " CA "
'''this one is more precise since it uses the chain identifier also'''
if atom == None: # consider all atoms
lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types]
else: # consider only given atoms
lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types and line[12:16] == atom]
shash = spatialhash.SpatialHash(distance)
for line in lines:
pos = (float(line[30:38]), float(line[38:46]), float(line[46:54]))
shash.insert(pos, line[21:26])
neighbor_list = []
for line in lines:
resid = line[21:26]
if resid == chain_residue:
pos = (float(line[30:38]), float(line[38:46]), float(line[46:54]))
for data in shash.nearby(pos, distance):
if data[1] not in neighbor_list:
neighbor_list.append(data[1])
neighbor_list.sort()
return neighbor_list | [
"def",
"neighbors2",
"(",
"self",
",",
"distance",
",",
"chain_residue",
",",
"atom",
"=",
"None",
",",
"resid_list",
"=",
"None",
")",
":",
"#atom = \" CA \"",
"if",
"atom",
"==",
"None",
":",
"# consider all atoms",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"self",
".",
"atomlines",
"(",
"resid_list",
")",
"if",
"line",
"[",
"17",
":",
"20",
"]",
"in",
"allowed_PDB_residues_types",
"]",
"else",
":",
"# consider only given atoms",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"self",
".",
"atomlines",
"(",
"resid_list",
")",
"if",
"line",
"[",
"17",
":",
"20",
"]",
"in",
"allowed_PDB_residues_types",
"and",
"line",
"[",
"12",
":",
"16",
"]",
"==",
"atom",
"]",
"shash",
"=",
"spatialhash",
".",
"SpatialHash",
"(",
"distance",
")",
"for",
"line",
"in",
"lines",
":",
"pos",
"=",
"(",
"float",
"(",
"line",
"[",
"30",
":",
"38",
"]",
")",
",",
"float",
"(",
"line",
"[",
"38",
":",
"46",
"]",
")",
",",
"float",
"(",
"line",
"[",
"46",
":",
"54",
"]",
")",
")",
"shash",
".",
"insert",
"(",
"pos",
",",
"line",
"[",
"21",
":",
"26",
"]",
")",
"neighbor_list",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"resid",
"=",
"line",
"[",
"21",
":",
"26",
"]",
"if",
"resid",
"==",
"chain_residue",
":",
"pos",
"=",
"(",
"float",
"(",
"line",
"[",
"30",
":",
"38",
"]",
")",
",",
"float",
"(",
"line",
"[",
"38",
":",
"46",
"]",
")",
",",
"float",
"(",
"line",
"[",
"46",
":",
"54",
"]",
")",
")",
"for",
"data",
"in",
"shash",
".",
"nearby",
"(",
"pos",
",",
"distance",
")",
":",
"if",
"data",
"[",
"1",
"]",
"not",
"in",
"neighbor_list",
":",
"neighbor_list",
".",
"append",
"(",
"data",
"[",
"1",
"]",
")",
"neighbor_list",
".",
"sort",
"(",
")",
"return",
"neighbor_list"
]
| this one is more precise since it uses the chain identifier also | [
"this",
"one",
"is",
"more",
"precise",
"since",
"it",
"uses",
"the",
"chain",
"identifier",
"also"
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2634-L2660 | train |
Kortemme-Lab/klab | klab/bio/pdb.py | PDB.extract_xyz_matrix_from_chain | def extract_xyz_matrix_from_chain(self, chain_id, atoms_of_interest = []):
'''Create a pandas coordinates dataframe from the lines in the specified chain.'''
chains = [l[21] for l in self.structure_lines if len(l) > 21]
chain_lines = [l for l in self.structure_lines if len(l) > 21 and l[21] == chain_id]
return PDB.extract_xyz_matrix_from_pdb(chain_lines, atoms_of_interest = atoms_of_interest, include_all_columns = True) | python | def extract_xyz_matrix_from_chain(self, chain_id, atoms_of_interest = []):
'''Create a pandas coordinates dataframe from the lines in the specified chain.'''
chains = [l[21] for l in self.structure_lines if len(l) > 21]
chain_lines = [l for l in self.structure_lines if len(l) > 21 and l[21] == chain_id]
return PDB.extract_xyz_matrix_from_pdb(chain_lines, atoms_of_interest = atoms_of_interest, include_all_columns = True) | [
"def",
"extract_xyz_matrix_from_chain",
"(",
"self",
",",
"chain_id",
",",
"atoms_of_interest",
"=",
"[",
"]",
")",
":",
"chains",
"=",
"[",
"l",
"[",
"21",
"]",
"for",
"l",
"in",
"self",
".",
"structure_lines",
"if",
"len",
"(",
"l",
")",
">",
"21",
"]",
"chain_lines",
"=",
"[",
"l",
"for",
"l",
"in",
"self",
".",
"structure_lines",
"if",
"len",
"(",
"l",
")",
">",
"21",
"and",
"l",
"[",
"21",
"]",
"==",
"chain_id",
"]",
"return",
"PDB",
".",
"extract_xyz_matrix_from_pdb",
"(",
"chain_lines",
",",
"atoms_of_interest",
"=",
"atoms_of_interest",
",",
"include_all_columns",
"=",
"True",
")"
]
| Create a pandas coordinates dataframe from the lines in the specified chain. | [
"Create",
"a",
"pandas",
"coordinates",
"dataframe",
"from",
"the",
"lines",
"in",
"the",
"specified",
"chain",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L2998-L3002 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | create_token_file | def create_token_file(username=id_generator(), password=id_generator()):
'''
Store the admins password for further retrieve
'''
cozy_ds_uid = helpers.get_uid('cozy-data-system')
if not os.path.isfile(LOGIN_FILENAME):
with open(LOGIN_FILENAME, 'w+') as token_file:
token_file.write("{0}\n{1}".format(username, password))
helpers.file_rights(LOGIN_FILENAME, mode=0400, uid=cozy_ds_uid, gid=0) | python | def create_token_file(username=id_generator(), password=id_generator()):
'''
Store the admins password for further retrieve
'''
cozy_ds_uid = helpers.get_uid('cozy-data-system')
if not os.path.isfile(LOGIN_FILENAME):
with open(LOGIN_FILENAME, 'w+') as token_file:
token_file.write("{0}\n{1}".format(username, password))
helpers.file_rights(LOGIN_FILENAME, mode=0400, uid=cozy_ds_uid, gid=0) | [
"def",
"create_token_file",
"(",
"username",
"=",
"id_generator",
"(",
")",
",",
"password",
"=",
"id_generator",
"(",
")",
")",
":",
"cozy_ds_uid",
"=",
"helpers",
".",
"get_uid",
"(",
"'cozy-data-system'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"LOGIN_FILENAME",
")",
":",
"with",
"open",
"(",
"LOGIN_FILENAME",
",",
"'w+'",
")",
"as",
"token_file",
":",
"token_file",
".",
"write",
"(",
"\"{0}\\n{1}\"",
".",
"format",
"(",
"username",
",",
"password",
")",
")",
"helpers",
".",
"file_rights",
"(",
"LOGIN_FILENAME",
",",
"mode",
"=",
"0400",
",",
"uid",
"=",
"cozy_ds_uid",
",",
"gid",
"=",
"0",
")"
]
| Store the admins password for further retrieve | [
"Store",
"the",
"admins",
"password",
"for",
"further",
"retrieve"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L37-L47 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | get_admin | def get_admin():
'''
Return the actual admin from token file
'''
if os.path.isfile(LOGIN_FILENAME):
with open(LOGIN_FILENAME, 'r') as token_file:
old_login, old_password = token_file.read().splitlines()[:2]
return old_login, old_password
else:
return None, None | python | def get_admin():
'''
Return the actual admin from token file
'''
if os.path.isfile(LOGIN_FILENAME):
with open(LOGIN_FILENAME, 'r') as token_file:
old_login, old_password = token_file.read().splitlines()[:2]
return old_login, old_password
else:
return None, None | [
"def",
"get_admin",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"LOGIN_FILENAME",
")",
":",
"with",
"open",
"(",
"LOGIN_FILENAME",
",",
"'r'",
")",
"as",
"token_file",
":",
"old_login",
",",
"old_password",
"=",
"token_file",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"[",
":",
"2",
"]",
"return",
"old_login",
",",
"old_password",
"else",
":",
"return",
"None",
",",
"None"
]
| Return the actual admin from token file | [
"Return",
"the",
"actual",
"admin",
"from",
"token",
"file"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L50-L59 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | curl_couchdb | def curl_couchdb(url, method='GET', base_url=BASE_URL, data=None):
'''
Launch a curl on CouchDB instance
'''
(username, password) = get_admin()
if username is None:
auth = None
else:
auth = (username, password)
if method == 'PUT':
req = requests.put('{}{}'.format(base_url, url), auth=auth, data=data)
elif method == 'DELETE':
req = requests.delete('{}{}'.format(base_url, url), auth=auth)
else:
req = requests.get('{}{}'.format(base_url, url), auth=auth)
if req.status_code not in [200, 201]:
raise HTTPError('{}: {}'.format(req.status_code, req.text))
return req | python | def curl_couchdb(url, method='GET', base_url=BASE_URL, data=None):
'''
Launch a curl on CouchDB instance
'''
(username, password) = get_admin()
if username is None:
auth = None
else:
auth = (username, password)
if method == 'PUT':
req = requests.put('{}{}'.format(base_url, url), auth=auth, data=data)
elif method == 'DELETE':
req = requests.delete('{}{}'.format(base_url, url), auth=auth)
else:
req = requests.get('{}{}'.format(base_url, url), auth=auth)
if req.status_code not in [200, 201]:
raise HTTPError('{}: {}'.format(req.status_code, req.text))
return req | [
"def",
"curl_couchdb",
"(",
"url",
",",
"method",
"=",
"'GET'",
",",
"base_url",
"=",
"BASE_URL",
",",
"data",
"=",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"get_admin",
"(",
")",
"if",
"username",
"is",
"None",
":",
"auth",
"=",
"None",
"else",
":",
"auth",
"=",
"(",
"username",
",",
"password",
")",
"if",
"method",
"==",
"'PUT'",
":",
"req",
"=",
"requests",
".",
"put",
"(",
"'{}{}'",
".",
"format",
"(",
"base_url",
",",
"url",
")",
",",
"auth",
"=",
"auth",
",",
"data",
"=",
"data",
")",
"elif",
"method",
"==",
"'DELETE'",
":",
"req",
"=",
"requests",
".",
"delete",
"(",
"'{}{}'",
".",
"format",
"(",
"base_url",
",",
"url",
")",
",",
"auth",
"=",
"auth",
")",
"else",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"'{}{}'",
".",
"format",
"(",
"base_url",
",",
"url",
")",
",",
"auth",
"=",
"auth",
")",
"if",
"req",
".",
"status_code",
"not",
"in",
"[",
"200",
",",
"201",
"]",
":",
"raise",
"HTTPError",
"(",
"'{}: {}'",
".",
"format",
"(",
"req",
".",
"status_code",
",",
"req",
".",
"text",
")",
")",
"return",
"req"
]
| Launch a curl on CouchDB instance | [
"Launch",
"a",
"curl",
"on",
"CouchDB",
"instance"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L62-L81 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | get_couchdb_admins | def get_couchdb_admins():
'''
Return the actual CouchDB admins
'''
user_list = []
req = curl_couchdb('/_config/admins/')
for user in req.json().keys():
user_list.append(user)
return user_list | python | def get_couchdb_admins():
'''
Return the actual CouchDB admins
'''
user_list = []
req = curl_couchdb('/_config/admins/')
for user in req.json().keys():
user_list.append(user)
return user_list | [
"def",
"get_couchdb_admins",
"(",
")",
":",
"user_list",
"=",
"[",
"]",
"req",
"=",
"curl_couchdb",
"(",
"'/_config/admins/'",
")",
"for",
"user",
"in",
"req",
".",
"json",
"(",
")",
".",
"keys",
"(",
")",
":",
"user_list",
".",
"append",
"(",
"user",
")",
"return",
"user_list"
]
| Return the actual CouchDB admins | [
"Return",
"the",
"actual",
"CouchDB",
"admins"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L84-L94 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | create_couchdb_admin | def create_couchdb_admin(username, password):
'''
Create a CouchDB user
'''
curl_couchdb('/_config/admins/{}'.format(username),
method='PUT',
data='"{}"'.format(password)) | python | def create_couchdb_admin(username, password):
'''
Create a CouchDB user
'''
curl_couchdb('/_config/admins/{}'.format(username),
method='PUT',
data='"{}"'.format(password)) | [
"def",
"create_couchdb_admin",
"(",
"username",
",",
"password",
")",
":",
"curl_couchdb",
"(",
"'/_config/admins/{}'",
".",
"format",
"(",
"username",
")",
",",
"method",
"=",
"'PUT'",
",",
"data",
"=",
"'\"{}\"'",
".",
"format",
"(",
"password",
")",
")"
]
| Create a CouchDB user | [
"Create",
"a",
"CouchDB",
"user"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L97-L103 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | is_cozy_registered | def is_cozy_registered():
'''
Check if a Cozy is registered
'''
req = curl_couchdb('/cozy/_design/user/_view/all')
users = req.json()['rows']
if len(users) > 0:
return True
else:
return False | python | def is_cozy_registered():
'''
Check if a Cozy is registered
'''
req = curl_couchdb('/cozy/_design/user/_view/all')
users = req.json()['rows']
if len(users) > 0:
return True
else:
return False | [
"def",
"is_cozy_registered",
"(",
")",
":",
"req",
"=",
"curl_couchdb",
"(",
"'/cozy/_design/user/_view/all'",
")",
"users",
"=",
"req",
".",
"json",
"(",
")",
"[",
"'rows'",
"]",
"if",
"len",
"(",
"users",
")",
">",
"0",
":",
"return",
"True",
"else",
":",
"return",
"False"
]
| Check if a Cozy is registered | [
"Check",
"if",
"a",
"Cozy",
"is",
"registered"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L114-L124 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | unregister_cozy | def unregister_cozy():
'''
Unregister a cozy
'''
req = curl_couchdb('/cozy/_design/user/_view/all')
users = req.json()['rows']
if len(users) > 0:
user = users[0]['value']
user_id = user['_id']
user_rev = user['_rev']
print 'Delete cozy user: {}'.format(user_id)
req = curl_couchdb('/cozy/{}?rev={}'.format(user_id, user_rev),
method='DELETE')
return req.json()
else:
print 'Cozy not registered'
return None | python | def unregister_cozy():
'''
Unregister a cozy
'''
req = curl_couchdb('/cozy/_design/user/_view/all')
users = req.json()['rows']
if len(users) > 0:
user = users[0]['value']
user_id = user['_id']
user_rev = user['_rev']
print 'Delete cozy user: {}'.format(user_id)
req = curl_couchdb('/cozy/{}?rev={}'.format(user_id, user_rev),
method='DELETE')
return req.json()
else:
print 'Cozy not registered'
return None | [
"def",
"unregister_cozy",
"(",
")",
":",
"req",
"=",
"curl_couchdb",
"(",
"'/cozy/_design/user/_view/all'",
")",
"users",
"=",
"req",
".",
"json",
"(",
")",
"[",
"'rows'",
"]",
"if",
"len",
"(",
"users",
")",
">",
"0",
":",
"user",
"=",
"users",
"[",
"0",
"]",
"[",
"'value'",
"]",
"user_id",
"=",
"user",
"[",
"'_id'",
"]",
"user_rev",
"=",
"user",
"[",
"'_rev'",
"]",
"print",
"'Delete cozy user: {}'",
".",
"format",
"(",
"user_id",
")",
"req",
"=",
"curl_couchdb",
"(",
"'/cozy/{}?rev={}'",
".",
"format",
"(",
"user_id",
",",
"user_rev",
")",
",",
"method",
"=",
"'DELETE'",
")",
"return",
"req",
".",
"json",
"(",
")",
"else",
":",
"print",
"'Cozy not registered'",
"return",
"None"
]
| Unregister a cozy | [
"Unregister",
"a",
"cozy"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L127-L146 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | delete_all_couchdb_admins | def delete_all_couchdb_admins():
'''
Delete all CouchDB users
'''
# Get current cozy token
username = get_admin()[0]
# Get CouchDB admin list
admins = get_couchdb_admins()
# Delete all admin user excluding current
for admin in admins:
if admin == username:
print "Delete {} later...".format(admin)
else:
print "Delete {}".format(admin)
delete_couchdb_admin(admin)
# Delete current CouchDB admin
admin = username
print "Delete {}".format(admin)
delete_couchdb_admin(admin) | python | def delete_all_couchdb_admins():
'''
Delete all CouchDB users
'''
# Get current cozy token
username = get_admin()[0]
# Get CouchDB admin list
admins = get_couchdb_admins()
# Delete all admin user excluding current
for admin in admins:
if admin == username:
print "Delete {} later...".format(admin)
else:
print "Delete {}".format(admin)
delete_couchdb_admin(admin)
# Delete current CouchDB admin
admin = username
print "Delete {}".format(admin)
delete_couchdb_admin(admin) | [
"def",
"delete_all_couchdb_admins",
"(",
")",
":",
"# Get current cozy token",
"username",
"=",
"get_admin",
"(",
")",
"[",
"0",
"]",
"# Get CouchDB admin list",
"admins",
"=",
"get_couchdb_admins",
"(",
")",
"# Delete all admin user excluding current",
"for",
"admin",
"in",
"admins",
":",
"if",
"admin",
"==",
"username",
":",
"print",
"\"Delete {} later...\"",
".",
"format",
"(",
"admin",
")",
"else",
":",
"print",
"\"Delete {}\"",
".",
"format",
"(",
"admin",
")",
"delete_couchdb_admin",
"(",
"admin",
")",
"# Delete current CouchDB admin",
"admin",
"=",
"username",
"print",
"\"Delete {}\"",
".",
"format",
"(",
"admin",
")",
"delete_couchdb_admin",
"(",
"admin",
")"
]
| Delete all CouchDB users | [
"Delete",
"all",
"CouchDB",
"users"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L159-L179 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | delete_token | def delete_token():
'''
Delete current token, file & CouchDB admin user
'''
username = get_admin()[0]
admins = get_couchdb_admins()
# Delete current admin if exist
if username in admins:
print 'I delete {} CouchDB user'.format(username)
delete_couchdb_admin(username)
# Delete token file if exist
if os.path.isfile(LOGIN_FILENAME):
print 'I delete {} token file'.format(LOGIN_FILENAME)
os.remove(LOGIN_FILENAME) | python | def delete_token():
'''
Delete current token, file & CouchDB admin user
'''
username = get_admin()[0]
admins = get_couchdb_admins()
# Delete current admin if exist
if username in admins:
print 'I delete {} CouchDB user'.format(username)
delete_couchdb_admin(username)
# Delete token file if exist
if os.path.isfile(LOGIN_FILENAME):
print 'I delete {} token file'.format(LOGIN_FILENAME)
os.remove(LOGIN_FILENAME) | [
"def",
"delete_token",
"(",
")",
":",
"username",
"=",
"get_admin",
"(",
")",
"[",
"0",
"]",
"admins",
"=",
"get_couchdb_admins",
"(",
")",
"# Delete current admin if exist",
"if",
"username",
"in",
"admins",
":",
"print",
"'I delete {} CouchDB user'",
".",
"format",
"(",
"username",
")",
"delete_couchdb_admin",
"(",
"username",
")",
"# Delete token file if exist",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"LOGIN_FILENAME",
")",
":",
"print",
"'I delete {} token file'",
".",
"format",
"(",
"LOGIN_FILENAME",
")",
"os",
".",
"remove",
"(",
"LOGIN_FILENAME",
")"
]
| Delete current token, file & CouchDB admin user | [
"Delete",
"current",
"token",
"file",
"&",
"CouchDB",
"admin",
"user"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L182-L197 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | create_token | def create_token():
'''
Create token file & create user
'''
username = id_generator()
password = id_generator()
create_couchdb_admin(username, password)
create_token_file(username, password)
return 'Token {} created'.format(username) | python | def create_token():
'''
Create token file & create user
'''
username = id_generator()
password = id_generator()
create_couchdb_admin(username, password)
create_token_file(username, password)
return 'Token {} created'.format(username) | [
"def",
"create_token",
"(",
")",
":",
"username",
"=",
"id_generator",
"(",
")",
"password",
"=",
"id_generator",
"(",
")",
"create_couchdb_admin",
"(",
"username",
",",
"password",
")",
"create_token_file",
"(",
"username",
",",
"password",
")",
"return",
"'Token {} created'",
".",
"format",
"(",
"username",
")"
]
| Create token file & create user | [
"Create",
"token",
"file",
"&",
"create",
"user"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L200-L209 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | ping | def ping():
'''
Ping CozyDB with existing credentials
'''
try:
curl_couchdb('/cozy/')
ping = True
except requests.exceptions.ConnectionError, error:
print error
ping = False
return ping | python | def ping():
'''
Ping CozyDB with existing credentials
'''
try:
curl_couchdb('/cozy/')
ping = True
except requests.exceptions.ConnectionError, error:
print error
ping = False
return ping | [
"def",
"ping",
"(",
")",
":",
"try",
":",
"curl_couchdb",
"(",
"'/cozy/'",
")",
"ping",
"=",
"True",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
",",
"error",
":",
"print",
"error",
"ping",
"=",
"False",
"return",
"ping"
]
| Ping CozyDB with existing credentials | [
"Ping",
"CozyDB",
"with",
"existing",
"credentials"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L220-L230 | train |
cozy/python_cozy_management | cozy_management/couchdb.py | get_cozy_param | def get_cozy_param(param):
'''
Get parameter in Cozy configuration
'''
try:
req = curl_couchdb('/cozy/_design/cozyinstance/_view/all')
rows = req.json()['rows']
if len(rows) == 0:
return None
else:
return rows[0].get('value', {}).get(param, None)
except:
return None | python | def get_cozy_param(param):
'''
Get parameter in Cozy configuration
'''
try:
req = curl_couchdb('/cozy/_design/cozyinstance/_view/all')
rows = req.json()['rows']
if len(rows) == 0:
return None
else:
return rows[0].get('value', {}).get(param, None)
except:
return None | [
"def",
"get_cozy_param",
"(",
"param",
")",
":",
"try",
":",
"req",
"=",
"curl_couchdb",
"(",
"'/cozy/_design/cozyinstance/_view/all'",
")",
"rows",
"=",
"req",
".",
"json",
"(",
")",
"[",
"'rows'",
"]",
"if",
"len",
"(",
"rows",
")",
"==",
"0",
":",
"return",
"None",
"else",
":",
"return",
"rows",
"[",
"0",
"]",
".",
"get",
"(",
"'value'",
",",
"{",
"}",
")",
".",
"get",
"(",
"param",
",",
"None",
")",
"except",
":",
"return",
"None"
]
| Get parameter in Cozy configuration | [
"Get",
"parameter",
"in",
"Cozy",
"configuration"
]
| 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L233-L245 | train |
adaptive-learning/proso-apps | proso/conversion.py | str2type | def str2type(value):
"""
Take a string and convert it to a value of proper type.
.. testsetup::
from proso.coversion import str2type
.. doctest::
>>> print(str2type("[1, 2, 3]")
[1, 2, 3]
"""
if not isinstance(value, str):
return value
try:
return json.loads(value)
except JSONDecodeError:
return value | python | def str2type(value):
"""
Take a string and convert it to a value of proper type.
.. testsetup::
from proso.coversion import str2type
.. doctest::
>>> print(str2type("[1, 2, 3]")
[1, 2, 3]
"""
if not isinstance(value, str):
return value
try:
return json.loads(value)
except JSONDecodeError:
return value | [
"def",
"str2type",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"value",
")",
"except",
"JSONDecodeError",
":",
"return",
"value"
]
| Take a string and convert it to a value of proper type.
.. testsetup::
from proso.coversion import str2type
.. doctest::
>>> print(str2type("[1, 2, 3]")
[1, 2, 3] | [
"Take",
"a",
"string",
"and",
"convert",
"it",
"to",
"a",
"value",
"of",
"proper",
"type",
"."
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/conversion.py#L9-L28 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | OAuth2.get_authorisation_url | def get_authorisation_url(self, reset=False):
""" Initialises the OAuth2 Process by asking the auth server for a login URL.
Once called, the user can login by being redirected to the url returned by
this function.
If there is an error during authorisation, None is returned."""
if reset:
self.auth_url = None
if not self.auth_url:
try:
oauth = OAuth2Session(self.client_id,redirect_uri=self.redirect_url)
self.auth_url,self.state = oauth.authorization_url(self.auth_base_url)
except Exception:
#print("Unexpected error:", sys.exc_info()[0])
#print("Could not get Authorisation Url!")
return None
return self.auth_url | python | def get_authorisation_url(self, reset=False):
""" Initialises the OAuth2 Process by asking the auth server for a login URL.
Once called, the user can login by being redirected to the url returned by
this function.
If there is an error during authorisation, None is returned."""
if reset:
self.auth_url = None
if not self.auth_url:
try:
oauth = OAuth2Session(self.client_id,redirect_uri=self.redirect_url)
self.auth_url,self.state = oauth.authorization_url(self.auth_base_url)
except Exception:
#print("Unexpected error:", sys.exc_info()[0])
#print("Could not get Authorisation Url!")
return None
return self.auth_url | [
"def",
"get_authorisation_url",
"(",
"self",
",",
"reset",
"=",
"False",
")",
":",
"if",
"reset",
":",
"self",
".",
"auth_url",
"=",
"None",
"if",
"not",
"self",
".",
"auth_url",
":",
"try",
":",
"oauth",
"=",
"OAuth2Session",
"(",
"self",
".",
"client_id",
",",
"redirect_uri",
"=",
"self",
".",
"redirect_url",
")",
"self",
".",
"auth_url",
",",
"self",
".",
"state",
"=",
"oauth",
".",
"authorization_url",
"(",
"self",
".",
"auth_base_url",
")",
"except",
"Exception",
":",
"#print(\"Unexpected error:\", sys.exc_info()[0])",
"#print(\"Could not get Authorisation Url!\")",
"return",
"None",
"return",
"self",
".",
"auth_url"
]
| Initialises the OAuth2 Process by asking the auth server for a login URL.
Once called, the user can login by being redirected to the url returned by
this function.
If there is an error during authorisation, None is returned. | [
"Initialises",
"the",
"OAuth2",
"Process",
"by",
"asking",
"the",
"auth",
"server",
"for",
"a",
"login",
"URL",
".",
"Once",
"called",
"the",
"user",
"can",
"login",
"by",
"being",
"redirected",
"to",
"the",
"url",
"returned",
"by",
"this",
"function",
".",
"If",
"there",
"is",
"an",
"error",
"during",
"authorisation",
"None",
"is",
"returned",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L201-L218 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | OAuth2.on_callback | def on_callback(self,auth_resp):
""" Must be called once the authorisation server has responded after
redirecting to the url provided by 'get_authorisation_url' and completing
the login there.
Returns True if a token was successfully retrieved, False otherwise."""
try:
oauth = OAuth2Session(self.client_id,state=self.state,redirect_uri=self.redirect_url)
self.token = oauth.fetch_token(self.token_url,
authorization_response=auth_resp,
client_secret=self.client_secret,
verify=self.verifySSL)
if not self.api_key and self.API_KEY_DEFAULT:
self.get_api_key()
if not self.api_key:
self.API_KEY_DEFAULT = False
except Exception:
#print("Unexpected error:", sys.exc_info()[0])
#print("Could not fetch token from OAuth Callback!")
return False
return True | python | def on_callback(self,auth_resp):
""" Must be called once the authorisation server has responded after
redirecting to the url provided by 'get_authorisation_url' and completing
the login there.
Returns True if a token was successfully retrieved, False otherwise."""
try:
oauth = OAuth2Session(self.client_id,state=self.state,redirect_uri=self.redirect_url)
self.token = oauth.fetch_token(self.token_url,
authorization_response=auth_resp,
client_secret=self.client_secret,
verify=self.verifySSL)
if not self.api_key and self.API_KEY_DEFAULT:
self.get_api_key()
if not self.api_key:
self.API_KEY_DEFAULT = False
except Exception:
#print("Unexpected error:", sys.exc_info()[0])
#print("Could not fetch token from OAuth Callback!")
return False
return True | [
"def",
"on_callback",
"(",
"self",
",",
"auth_resp",
")",
":",
"try",
":",
"oauth",
"=",
"OAuth2Session",
"(",
"self",
".",
"client_id",
",",
"state",
"=",
"self",
".",
"state",
",",
"redirect_uri",
"=",
"self",
".",
"redirect_url",
")",
"self",
".",
"token",
"=",
"oauth",
".",
"fetch_token",
"(",
"self",
".",
"token_url",
",",
"authorization_response",
"=",
"auth_resp",
",",
"client_secret",
"=",
"self",
".",
"client_secret",
",",
"verify",
"=",
"self",
".",
"verifySSL",
")",
"if",
"not",
"self",
".",
"api_key",
"and",
"self",
".",
"API_KEY_DEFAULT",
":",
"self",
".",
"get_api_key",
"(",
")",
"if",
"not",
"self",
".",
"api_key",
":",
"self",
".",
"API_KEY_DEFAULT",
"=",
"False",
"except",
"Exception",
":",
"#print(\"Unexpected error:\", sys.exc_info()[0])",
"#print(\"Could not fetch token from OAuth Callback!\")",
"return",
"False",
"return",
"True"
]
| Must be called once the authorisation server has responded after
redirecting to the url provided by 'get_authorisation_url' and completing
the login there.
Returns True if a token was successfully retrieved, False otherwise. | [
"Must",
"be",
"called",
"once",
"the",
"authorisation",
"server",
"has",
"responded",
"after",
"redirecting",
"to",
"the",
"url",
"provided",
"by",
"get_authorisation_url",
"and",
"completing",
"the",
"login",
"there",
".",
"Returns",
"True",
"if",
"a",
"token",
"was",
"successfully",
"retrieved",
"False",
"otherwise",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L220-L239 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | OAuth2.validate | def validate(self):
""" Confirms the current token is still valid.
Returns True if it is valid, False otherwise. """
try:
resp = self.request().get(self.validate_url, verify=self.verifySSL).json()
except TokenExpiredError:
return False
except AttributeError:
return False
if 'error' in resp:
return False
return True | python | def validate(self):
""" Confirms the current token is still valid.
Returns True if it is valid, False otherwise. """
try:
resp = self.request().get(self.validate_url, verify=self.verifySSL).json()
except TokenExpiredError:
return False
except AttributeError:
return False
if 'error' in resp:
return False
return True | [
"def",
"validate",
"(",
"self",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"request",
"(",
")",
".",
"get",
"(",
"self",
".",
"validate_url",
",",
"verify",
"=",
"self",
".",
"verifySSL",
")",
".",
"json",
"(",
")",
"except",
"TokenExpiredError",
":",
"return",
"False",
"except",
"AttributeError",
":",
"return",
"False",
"if",
"'error'",
"in",
"resp",
":",
"return",
"False",
"return",
"True"
]
| Confirms the current token is still valid.
Returns True if it is valid, False otherwise. | [
"Confirms",
"the",
"current",
"token",
"is",
"still",
"valid",
".",
"Returns",
"True",
"if",
"it",
"is",
"valid",
"False",
"otherwise",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L241-L254 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | OAuth2.refresh_token | def refresh_token(self):
""" Refreshes access token using refresh token. Returns true if successful, false otherwise. """
try:
if self.token:
self.token = self.request().refresh_token(self.refresh_url, self.token['refresh_token'])
return True
except Exception as e:
# TODO: what might go wrong here - handle this error properly
#print("Unexpected error:\t\t", str(e))
#traceback.print_exc()
pass
return False | python | def refresh_token(self):
""" Refreshes access token using refresh token. Returns true if successful, false otherwise. """
try:
if self.token:
self.token = self.request().refresh_token(self.refresh_url, self.token['refresh_token'])
return True
except Exception as e:
# TODO: what might go wrong here - handle this error properly
#print("Unexpected error:\t\t", str(e))
#traceback.print_exc()
pass
return False | [
"def",
"refresh_token",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"token",
":",
"self",
".",
"token",
"=",
"self",
".",
"request",
"(",
")",
".",
"refresh_token",
"(",
"self",
".",
"refresh_url",
",",
"self",
".",
"token",
"[",
"'refresh_token'",
"]",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"# TODO: what might go wrong here - handle this error properly",
"#print(\"Unexpected error:\\t\\t\", str(e))",
"#traceback.print_exc()",
"pass",
"return",
"False"
]
| Refreshes access token using refresh token. Returns true if successful, false otherwise. | [
"Refreshes",
"access",
"token",
"using",
"refresh",
"token",
".",
"Returns",
"true",
"if",
"successful",
"false",
"otherwise",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L256-L268 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | OAuth2.revoke_access | def revoke_access(self):
""" Requests that the currently used token becomes invalid. Call this should a user logout. """
if self.token is None:
return True
#Don't try to revoke if token is invalid anyway, will cause an error response anyway.
if self.validate():
data = {}
data['token'] = self.token['access_token']
self.request().post(self.revoke_url, data=data, json=None,verify=self.verifySSL)
return True | python | def revoke_access(self):
""" Requests that the currently used token becomes invalid. Call this should a user logout. """
if self.token is None:
return True
#Don't try to revoke if token is invalid anyway, will cause an error response anyway.
if self.validate():
data = {}
data['token'] = self.token['access_token']
self.request().post(self.revoke_url, data=data, json=None,verify=self.verifySSL)
return True | [
"def",
"revoke_access",
"(",
"self",
")",
":",
"if",
"self",
".",
"token",
"is",
"None",
":",
"return",
"True",
"#Don't try to revoke if token is invalid anyway, will cause an error response anyway.",
"if",
"self",
".",
"validate",
"(",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"'token'",
"]",
"=",
"self",
".",
"token",
"[",
"'access_token'",
"]",
"self",
".",
"request",
"(",
")",
".",
"post",
"(",
"self",
".",
"revoke_url",
",",
"data",
"=",
"data",
",",
"json",
"=",
"None",
",",
"verify",
"=",
"self",
".",
"verifySSL",
")",
"return",
"True"
]
| Requests that the currently used token becomes invalid. Call this should a user logout. | [
"Requests",
"that",
"the",
"currently",
"used",
"token",
"becomes",
"invalid",
".",
"Call",
"this",
"should",
"a",
"user",
"logout",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L270-L279 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | OAuth2.request | def request(self):
""" Returns an OAuth2 Session to be used to make requests.
Returns None if a token hasn't yet been received."""
headers = {'Accept': 'application/json'}
# Use API Key if possible
if self.api_key:
headers['X-API-KEY'] = self.api_key
return requests,headers
else:
# Try to use OAuth
if self.token:
return OAuth2Session(self.client_id, token=self.token),headers
else:
raise APIError("No API key and no OAuth session available") | python | def request(self):
""" Returns an OAuth2 Session to be used to make requests.
Returns None if a token hasn't yet been received."""
headers = {'Accept': 'application/json'}
# Use API Key if possible
if self.api_key:
headers['X-API-KEY'] = self.api_key
return requests,headers
else:
# Try to use OAuth
if self.token:
return OAuth2Session(self.client_id, token=self.token),headers
else:
raise APIError("No API key and no OAuth session available") | [
"def",
"request",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/json'",
"}",
"# Use API Key if possible",
"if",
"self",
".",
"api_key",
":",
"headers",
"[",
"'X-API-KEY'",
"]",
"=",
"self",
".",
"api_key",
"return",
"requests",
",",
"headers",
"else",
":",
"# Try to use OAuth",
"if",
"self",
".",
"token",
":",
"return",
"OAuth2Session",
"(",
"self",
".",
"client_id",
",",
"token",
"=",
"self",
".",
"token",
")",
",",
"headers",
"else",
":",
"raise",
"APIError",
"(",
"\"No API key and no OAuth session available\"",
")"
]
| Returns an OAuth2 Session to be used to make requests.
Returns None if a token hasn't yet been received. | [
"Returns",
"an",
"OAuth2",
"Session",
"to",
"be",
"used",
"to",
"make",
"requests",
".",
"Returns",
"None",
"if",
"a",
"token",
"hasn",
"t",
"yet",
"been",
"received",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L317-L332 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.to_json | def to_json(self):
"""
Returns a json string containing all relevant data to recreate this pyalveo.Client.
"""
data = dict(self.__dict__)
data.pop('context',None)
data['oauth'] = self.oauth.to_dict()
data['cache'] = self.cache.to_dict()
return json.dumps(data) | python | def to_json(self):
"""
Returns a json string containing all relevant data to recreate this pyalveo.Client.
"""
data = dict(self.__dict__)
data.pop('context',None)
data['oauth'] = self.oauth.to_dict()
data['cache'] = self.cache.to_dict()
return json.dumps(data) | [
"def",
"to_json",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
"self",
".",
"__dict__",
")",
"data",
".",
"pop",
"(",
"'context'",
",",
"None",
")",
"data",
"[",
"'oauth'",
"]",
"=",
"self",
".",
"oauth",
".",
"to_dict",
"(",
")",
"data",
"[",
"'cache'",
"]",
"=",
"self",
".",
"cache",
".",
"to_dict",
"(",
")",
"return",
"json",
".",
"dumps",
"(",
"data",
")"
]
| Returns a json string containing all relevant data to recreate this pyalveo.Client. | [
"Returns",
"a",
"json",
"string",
"containing",
"all",
"relevant",
"data",
"to",
"recreate",
"this",
"pyalveo",
".",
"Client",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L475-L483 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.api_request | def api_request(self, url, data=None, method='GET', raw=False, file=None):
""" Perform an API request to the given URL, optionally
including the specified data
:type url: String
:param url: the URL to which to make the request
:type data: String
:param data: the data to send with the request, if any
:type method: String
:param method: the HTTP request method
:type raw: Boolean
:para raw: if True, return the raw response, otherwise treat as JSON and return the parsed response
:type file: String
:param file: (Optional) full path to file to be uploaded in a POST request
:returns: the response from the server either as a raw response or a Python dictionary
generated by parsing the JSON response
:raises: APIError if the API request is not successful
"""
if method is 'GET':
response = self.oauth.get(url)
elif method is 'POST':
if file is not None:
response = self.oauth.post(url, data=data, file=file)
else:
response = self.oauth.post(url, data=data)
elif method is 'PUT':
response = self.oauth.put(url, data=data)
elif method is 'DELETE':
response = self.oauth.delete(url)
else:
raise APIError("Unknown request method: %s" % (method,))
# check for error responses
if response.status_code >= 400:
raise APIError(response.status_code,
'',
"Error accessing API (url: %s, method: %s)\nData: %s\nMessage: %s" % (url, method, data, response.text))
if raw:
return response.content
else:
return response.json() | python | def api_request(self, url, data=None, method='GET', raw=False, file=None):
""" Perform an API request to the given URL, optionally
including the specified data
:type url: String
:param url: the URL to which to make the request
:type data: String
:param data: the data to send with the request, if any
:type method: String
:param method: the HTTP request method
:type raw: Boolean
:para raw: if True, return the raw response, otherwise treat as JSON and return the parsed response
:type file: String
:param file: (Optional) full path to file to be uploaded in a POST request
:returns: the response from the server either as a raw response or a Python dictionary
generated by parsing the JSON response
:raises: APIError if the API request is not successful
"""
if method is 'GET':
response = self.oauth.get(url)
elif method is 'POST':
if file is not None:
response = self.oauth.post(url, data=data, file=file)
else:
response = self.oauth.post(url, data=data)
elif method is 'PUT':
response = self.oauth.put(url, data=data)
elif method is 'DELETE':
response = self.oauth.delete(url)
else:
raise APIError("Unknown request method: %s" % (method,))
# check for error responses
if response.status_code >= 400:
raise APIError(response.status_code,
'',
"Error accessing API (url: %s, method: %s)\nData: %s\nMessage: %s" % (url, method, data, response.text))
if raw:
return response.content
else:
return response.json() | [
"def",
"api_request",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"raw",
"=",
"False",
",",
"file",
"=",
"None",
")",
":",
"if",
"method",
"is",
"'GET'",
":",
"response",
"=",
"self",
".",
"oauth",
".",
"get",
"(",
"url",
")",
"elif",
"method",
"is",
"'POST'",
":",
"if",
"file",
"is",
"not",
"None",
":",
"response",
"=",
"self",
".",
"oauth",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"file",
"=",
"file",
")",
"else",
":",
"response",
"=",
"self",
".",
"oauth",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
")",
"elif",
"method",
"is",
"'PUT'",
":",
"response",
"=",
"self",
".",
"oauth",
".",
"put",
"(",
"url",
",",
"data",
"=",
"data",
")",
"elif",
"method",
"is",
"'DELETE'",
":",
"response",
"=",
"self",
".",
"oauth",
".",
"delete",
"(",
"url",
")",
"else",
":",
"raise",
"APIError",
"(",
"\"Unknown request method: %s\"",
"%",
"(",
"method",
",",
")",
")",
"# check for error responses",
"if",
"response",
".",
"status_code",
">=",
"400",
":",
"raise",
"APIError",
"(",
"response",
".",
"status_code",
",",
"''",
",",
"\"Error accessing API (url: %s, method: %s)\\nData: %s\\nMessage: %s\"",
"%",
"(",
"url",
",",
"method",
",",
"data",
",",
"response",
".",
"text",
")",
")",
"if",
"raw",
":",
"return",
"response",
".",
"content",
"else",
":",
"return",
"response",
".",
"json",
"(",
")"
]
| Perform an API request to the given URL, optionally
including the specified data
:type url: String
:param url: the URL to which to make the request
:type data: String
:param data: the data to send with the request, if any
:type method: String
:param method: the HTTP request method
:type raw: Boolean
:para raw: if True, return the raw response, otherwise treat as JSON and return the parsed response
:type file: String
:param file: (Optional) full path to file to be uploaded in a POST request
:returns: the response from the server either as a raw response or a Python dictionary
generated by parsing the JSON response
:raises: APIError if the API request is not successful | [
"Perform",
"an",
"API",
"request",
"to",
"the",
"given",
"URL",
"optionally",
"including",
"the",
"specified",
"data"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L572-L619 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_collections | def get_collections(self):
"""Retrieve a list of the collection URLs for all collections
hosted on the server.
:rtype: List
:returns: a List of tuples of (name, url) for each collection
"""
result = self.api_request('/catalog')
# get the collection name from the url
return [(os.path.split(x)[1], x) for x in result['collections']] | python | def get_collections(self):
"""Retrieve a list of the collection URLs for all collections
hosted on the server.
:rtype: List
:returns: a List of tuples of (name, url) for each collection
"""
result = self.api_request('/catalog')
# get the collection name from the url
return [(os.path.split(x)[1], x) for x in result['collections']] | [
"def",
"get_collections",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"'/catalog'",
")",
"# get the collection name from the url",
"return",
"[",
"(",
"os",
".",
"path",
".",
"split",
"(",
"x",
")",
"[",
"1",
"]",
",",
"x",
")",
"for",
"x",
"in",
"result",
"[",
"'collections'",
"]",
"]"
]
| Retrieve a list of the collection URLs for all collections
hosted on the server.
:rtype: List
:returns: a List of tuples of (name, url) for each collection | [
"Retrieve",
"a",
"list",
"of",
"the",
"collection",
"URLs",
"for",
"all",
"collections",
"hosted",
"on",
"the",
"server",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L660-L670 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_item | def get_item(self, item_url, force_download=False):
""" Retrieve the item metadata from the server, as an Item object
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:rtype: Item
:returns: the corresponding metadata, as an Item object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:raises: APIError if the API request is not successful
"""
item_url = str(item_url)
if (self.use_cache and
not force_download and
self.cache.has_item(item_url)):
item_json = self.cache.get_item(item_url)
else:
item_json = self.api_request(item_url, raw=True)
if self.update_cache:
self.cache.add_item(item_url, item_json)
return Item(json.loads(item_json.decode('utf-8')), self) | python | def get_item(self, item_url, force_download=False):
""" Retrieve the item metadata from the server, as an Item object
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:rtype: Item
:returns: the corresponding metadata, as an Item object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:raises: APIError if the API request is not successful
"""
item_url = str(item_url)
if (self.use_cache and
not force_download and
self.cache.has_item(item_url)):
item_json = self.cache.get_item(item_url)
else:
item_json = self.api_request(item_url, raw=True)
if self.update_cache:
self.cache.add_item(item_url, item_json)
return Item(json.loads(item_json.decode('utf-8')), self) | [
"def",
"get_item",
"(",
"self",
",",
"item_url",
",",
"force_download",
"=",
"False",
")",
":",
"item_url",
"=",
"str",
"(",
"item_url",
")",
"if",
"(",
"self",
".",
"use_cache",
"and",
"not",
"force_download",
"and",
"self",
".",
"cache",
".",
"has_item",
"(",
"item_url",
")",
")",
":",
"item_json",
"=",
"self",
".",
"cache",
".",
"get_item",
"(",
"item_url",
")",
"else",
":",
"item_json",
"=",
"self",
".",
"api_request",
"(",
"item_url",
",",
"raw",
"=",
"True",
")",
"if",
"self",
".",
"update_cache",
":",
"self",
".",
"cache",
".",
"add_item",
"(",
"item_url",
",",
"item_json",
")",
"return",
"Item",
"(",
"json",
".",
"loads",
"(",
"item_json",
".",
"decode",
"(",
"'utf-8'",
")",
")",
",",
"self",
")"
]
| Retrieve the item metadata from the server, as an Item object
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:rtype: Item
:returns: the corresponding metadata, as an Item object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:raises: APIError if the API request is not successful | [
"Retrieve",
"the",
"item",
"metadata",
"from",
"the",
"server",
"as",
"an",
"Item",
"object"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L693-L720 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_document | def get_document(self, doc_url, force_download=False):
""" Retrieve the data for the given document from the server
:type doc_url: String or Document
:param doc_url: the URL of the document, or a Document object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the document data
:raises: APIError if the API request is not successful
"""
doc_url = str(doc_url)
if (self.use_cache and
not force_download and
self.cache.has_document(doc_url)):
doc_data = self.cache.get_document(doc_url)
else:
doc_data = self.api_request(doc_url, raw=True)
if self.update_cache:
self.cache.add_document(doc_url, doc_data)
return doc_data | python | def get_document(self, doc_url, force_download=False):
""" Retrieve the data for the given document from the server
:type doc_url: String or Document
:param doc_url: the URL of the document, or a Document object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the document data
:raises: APIError if the API request is not successful
"""
doc_url = str(doc_url)
if (self.use_cache and
not force_download and
self.cache.has_document(doc_url)):
doc_data = self.cache.get_document(doc_url)
else:
doc_data = self.api_request(doc_url, raw=True)
if self.update_cache:
self.cache.add_document(doc_url, doc_data)
return doc_data | [
"def",
"get_document",
"(",
"self",
",",
"doc_url",
",",
"force_download",
"=",
"False",
")",
":",
"doc_url",
"=",
"str",
"(",
"doc_url",
")",
"if",
"(",
"self",
".",
"use_cache",
"and",
"not",
"force_download",
"and",
"self",
".",
"cache",
".",
"has_document",
"(",
"doc_url",
")",
")",
":",
"doc_data",
"=",
"self",
".",
"cache",
".",
"get_document",
"(",
"doc_url",
")",
"else",
":",
"doc_data",
"=",
"self",
".",
"api_request",
"(",
"doc_url",
",",
"raw",
"=",
"True",
")",
"if",
"self",
".",
"update_cache",
":",
"self",
".",
"cache",
".",
"add_document",
"(",
"doc_url",
",",
"doc_data",
")",
"return",
"doc_data"
]
| Retrieve the data for the given document from the server
:type doc_url: String or Document
:param doc_url: the URL of the document, or a Document object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the document data
:raises: APIError if the API request is not successful | [
"Retrieve",
"the",
"data",
"for",
"the",
"given",
"document",
"from",
"the",
"server"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L722-L748 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_primary_text | def get_primary_text(self, item_url, force_download=False):
""" Retrieve the primary text for an item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the item's primary text if it has one, otherwise None
:raises: APIError if the request was not successful
"""
item_url = str(item_url)
metadata = self.get_item(item_url).metadata()
try:
primary_text_url = metadata['alveo:primary_text_url']
except KeyError:
return None
if primary_text_url == 'No primary text found':
return None
if (self.use_cache and
not force_download and
self.cache.has_primary_text(item_url)):
primary_text = self.cache.get_primary_text(item_url)
else:
primary_text = self.api_request(primary_text_url, raw=True)
if self.update_cache:
self.cache.add_primary_text(item_url, primary_text)
return primary_text | python | def get_primary_text(self, item_url, force_download=False):
""" Retrieve the primary text for an item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the item's primary text if it has one, otherwise None
:raises: APIError if the request was not successful
"""
item_url = str(item_url)
metadata = self.get_item(item_url).metadata()
try:
primary_text_url = metadata['alveo:primary_text_url']
except KeyError:
return None
if primary_text_url == 'No primary text found':
return None
if (self.use_cache and
not force_download and
self.cache.has_primary_text(item_url)):
primary_text = self.cache.get_primary_text(item_url)
else:
primary_text = self.api_request(primary_text_url, raw=True)
if self.update_cache:
self.cache.add_primary_text(item_url, primary_text)
return primary_text | [
"def",
"get_primary_text",
"(",
"self",
",",
"item_url",
",",
"force_download",
"=",
"False",
")",
":",
"item_url",
"=",
"str",
"(",
"item_url",
")",
"metadata",
"=",
"self",
".",
"get_item",
"(",
"item_url",
")",
".",
"metadata",
"(",
")",
"try",
":",
"primary_text_url",
"=",
"metadata",
"[",
"'alveo:primary_text_url'",
"]",
"except",
"KeyError",
":",
"return",
"None",
"if",
"primary_text_url",
"==",
"'No primary text found'",
":",
"return",
"None",
"if",
"(",
"self",
".",
"use_cache",
"and",
"not",
"force_download",
"and",
"self",
".",
"cache",
".",
"has_primary_text",
"(",
"item_url",
")",
")",
":",
"primary_text",
"=",
"self",
".",
"cache",
".",
"get_primary_text",
"(",
"item_url",
")",
"else",
":",
"primary_text",
"=",
"self",
".",
"api_request",
"(",
"primary_text_url",
",",
"raw",
"=",
"True",
")",
"if",
"self",
".",
"update_cache",
":",
"self",
".",
"cache",
".",
"add_primary_text",
"(",
"item_url",
",",
"primary_text",
")",
"return",
"primary_text"
]
| Retrieve the primary text for an item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:type force_download: Boolean
:param force_download: True to download from the server
regardless of the cache's contents
:rtype: String
:returns: the item's primary text if it has one, otherwise None
:raises: APIError if the request was not successful | [
"Retrieve",
"the",
"primary",
"text",
"for",
"an",
"item",
"from",
"the",
"server"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L750-L786 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_item_annotations | def get_item_annotations(self, item_url, annotation_type=None, label=None):
""" Retrieve the annotations for an item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:type annotation_type: String
:param annotation_type: return only results with a matching Type field
:type label: String
:param label: return only results with a matching Label field
:rtype: String
:returns: the annotations as a dictionary, if the item has
annotations, otherwise None
The annotation dictionary has keys:
commonProperties - properties common to all annotations
@context - the url of the JSON-LD annotation context definition
alveo:annotations - a list of annotations, each is a dictionary
:raises: APIError if the request was not successful
"""
# get the annotation URL from the item metadata, if not present then there are no annotations
item_url = str(item_url)
metadata = self.get_item(item_url).metadata()
try:
annotation_url = metadata['alveo:annotations_url']
except KeyError:
return None
req_url = annotation_url
if annotation_type is not None:
req_url += '?'
req_url += urlencode((('type', annotation_type),))
if label is not None:
if annotation_type is None:
req_url += '?'
else:
req_url += '&'
req_url += urlencode((('label',label),))
try:
return self.api_request(req_url)
except KeyError:
return None | python | def get_item_annotations(self, item_url, annotation_type=None, label=None):
""" Retrieve the annotations for an item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:type annotation_type: String
:param annotation_type: return only results with a matching Type field
:type label: String
:param label: return only results with a matching Label field
:rtype: String
:returns: the annotations as a dictionary, if the item has
annotations, otherwise None
The annotation dictionary has keys:
commonProperties - properties common to all annotations
@context - the url of the JSON-LD annotation context definition
alveo:annotations - a list of annotations, each is a dictionary
:raises: APIError if the request was not successful
"""
# get the annotation URL from the item metadata, if not present then there are no annotations
item_url = str(item_url)
metadata = self.get_item(item_url).metadata()
try:
annotation_url = metadata['alveo:annotations_url']
except KeyError:
return None
req_url = annotation_url
if annotation_type is not None:
req_url += '?'
req_url += urlencode((('type', annotation_type),))
if label is not None:
if annotation_type is None:
req_url += '?'
else:
req_url += '&'
req_url += urlencode((('label',label),))
try:
return self.api_request(req_url)
except KeyError:
return None | [
"def",
"get_item_annotations",
"(",
"self",
",",
"item_url",
",",
"annotation_type",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"# get the annotation URL from the item metadata, if not present then there are no annotations",
"item_url",
"=",
"str",
"(",
"item_url",
")",
"metadata",
"=",
"self",
".",
"get_item",
"(",
"item_url",
")",
".",
"metadata",
"(",
")",
"try",
":",
"annotation_url",
"=",
"metadata",
"[",
"'alveo:annotations_url'",
"]",
"except",
"KeyError",
":",
"return",
"None",
"req_url",
"=",
"annotation_url",
"if",
"annotation_type",
"is",
"not",
"None",
":",
"req_url",
"+=",
"'?'",
"req_url",
"+=",
"urlencode",
"(",
"(",
"(",
"'type'",
",",
"annotation_type",
")",
",",
")",
")",
"if",
"label",
"is",
"not",
"None",
":",
"if",
"annotation_type",
"is",
"None",
":",
"req_url",
"+=",
"'?'",
"else",
":",
"req_url",
"+=",
"'&'",
"req_url",
"+=",
"urlencode",
"(",
"(",
"(",
"'label'",
",",
"label",
")",
",",
")",
")",
"try",
":",
"return",
"self",
".",
"api_request",
"(",
"req_url",
")",
"except",
"KeyError",
":",
"return",
"None"
]
| Retrieve the annotations for an item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:type annotation_type: String
:param annotation_type: return only results with a matching Type field
:type label: String
:param label: return only results with a matching Label field
:rtype: String
:returns: the annotations as a dictionary, if the item has
annotations, otherwise None
The annotation dictionary has keys:
commonProperties - properties common to all annotations
@context - the url of the JSON-LD annotation context definition
alveo:annotations - a list of annotations, each is a dictionary
:raises: APIError if the request was not successful | [
"Retrieve",
"the",
"annotations",
"for",
"an",
"item",
"from",
"the",
"server"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L788-L834 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_annotation_types | def get_annotation_types(self, item_url):
""" Retrieve the annotation types for the given item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:rtype: List
:returns: a List specifying the annotation types
:raises: APIError if the request was not successful
"""
req_url = item_url + "/annotations/types"
resp = self.api_request(req_url)
return resp['annotation_types'] | python | def get_annotation_types(self, item_url):
""" Retrieve the annotation types for the given item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:rtype: List
:returns: a List specifying the annotation types
:raises: APIError if the request was not successful
"""
req_url = item_url + "/annotations/types"
resp = self.api_request(req_url)
return resp['annotation_types'] | [
"def",
"get_annotation_types",
"(",
"self",
",",
"item_url",
")",
":",
"req_url",
"=",
"item_url",
"+",
"\"/annotations/types\"",
"resp",
"=",
"self",
".",
"api_request",
"(",
"req_url",
")",
"return",
"resp",
"[",
"'annotation_types'",
"]"
]
| Retrieve the annotation types for the given item from the server
:type item_url: String or Item
:param item_url: URL of the item, or an Item object
:rtype: List
:returns: a List specifying the annotation types
:raises: APIError if the request was not successful | [
"Retrieve",
"the",
"annotation",
"types",
"for",
"the",
"given",
"item",
"from",
"the",
"server"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L836-L851 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.add_annotations | def add_annotations(self, item_url, annotations):
"""Add annotations to the given item
:type item_url: String or Item
:param item_url: the URL of the item corresponding to the annotation,
or an Item object
:type annotation: list
:param annotations: the annotations as a list of dictionaries, each with keys '@type', 'label', 'start', 'end' and 'type'
:rtype: String
:returns: the server's success message, if successful
:raises: APIError if the upload was not successful
:raises: Exception if the annotations are malformed (missing a required key)
"""
adict = {'@context': "https://alveo-staging1.intersect.org.au/schema/json-ld"}
for ann in annotations:
# verify that we have the required properties
for key in ('@type', 'label', 'start', 'end', 'type'):
if key not in ann.keys():
raise Exception("required key '%s' not present in annotation" % key)
adict['@graph'] = annotations
resp = self.api_request(str(item_url) + '/annotations', method='POST', data=json.dumps(adict))
return self.__check_success(resp) | python | def add_annotations(self, item_url, annotations):
"""Add annotations to the given item
:type item_url: String or Item
:param item_url: the URL of the item corresponding to the annotation,
or an Item object
:type annotation: list
:param annotations: the annotations as a list of dictionaries, each with keys '@type', 'label', 'start', 'end' and 'type'
:rtype: String
:returns: the server's success message, if successful
:raises: APIError if the upload was not successful
:raises: Exception if the annotations are malformed (missing a required key)
"""
adict = {'@context': "https://alveo-staging1.intersect.org.au/schema/json-ld"}
for ann in annotations:
# verify that we have the required properties
for key in ('@type', 'label', 'start', 'end', 'type'):
if key not in ann.keys():
raise Exception("required key '%s' not present in annotation" % key)
adict['@graph'] = annotations
resp = self.api_request(str(item_url) + '/annotations', method='POST', data=json.dumps(adict))
return self.__check_success(resp) | [
"def",
"add_annotations",
"(",
"self",
",",
"item_url",
",",
"annotations",
")",
":",
"adict",
"=",
"{",
"'@context'",
":",
"\"https://alveo-staging1.intersect.org.au/schema/json-ld\"",
"}",
"for",
"ann",
"in",
"annotations",
":",
"# verify that we have the required properties",
"for",
"key",
"in",
"(",
"'@type'",
",",
"'label'",
",",
"'start'",
",",
"'end'",
",",
"'type'",
")",
":",
"if",
"key",
"not",
"in",
"ann",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"required key '%s' not present in annotation\"",
"%",
"key",
")",
"adict",
"[",
"'@graph'",
"]",
"=",
"annotations",
"resp",
"=",
"self",
".",
"api_request",
"(",
"str",
"(",
"item_url",
")",
"+",
"'/annotations'",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"adict",
")",
")",
"return",
"self",
".",
"__check_success",
"(",
"resp",
")"
]
| Add annotations to the given item
:type item_url: String or Item
:param item_url: the URL of the item corresponding to the annotation,
or an Item object
:type annotation: list
:param annotations: the annotations as a list of dictionaries, each with keys '@type', 'label', 'start', 'end' and 'type'
:rtype: String
:returns: the server's success message, if successful
:raises: APIError if the upload was not successful
:raises: Exception if the annotations are malformed (missing a required key) | [
"Add",
"annotations",
"to",
"the",
"given",
"item"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L853-L878 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.create_collection | def create_collection(self, name, metadata):
""" Create a new collection with the given name
and attach the metadata.
:param name: the collection name, suitable for use in a URL (no spaces)
:type name: String
:param metadata: a dictionary of metadata values to associate with the new collection
:type metadata: Dict
:rtype: String
:returns: a message confirming creation of the collection
:raises: APIError if the request was not successful
"""
payload = {
'collection_metadata': metadata,
'name': name
}
response = self.api_request('/catalog', method='POST', data=json.dumps(payload))
return self.__check_success(response) | python | def create_collection(self, name, metadata):
""" Create a new collection with the given name
and attach the metadata.
:param name: the collection name, suitable for use in a URL (no spaces)
:type name: String
:param metadata: a dictionary of metadata values to associate with the new collection
:type metadata: Dict
:rtype: String
:returns: a message confirming creation of the collection
:raises: APIError if the request was not successful
"""
payload = {
'collection_metadata': metadata,
'name': name
}
response = self.api_request('/catalog', method='POST', data=json.dumps(payload))
return self.__check_success(response) | [
"def",
"create_collection",
"(",
"self",
",",
"name",
",",
"metadata",
")",
":",
"payload",
"=",
"{",
"'collection_metadata'",
":",
"metadata",
",",
"'name'",
":",
"name",
"}",
"response",
"=",
"self",
".",
"api_request",
"(",
"'/catalog'",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
"return",
"self",
".",
"__check_success",
"(",
"response",
")"
]
| Create a new collection with the given name
and attach the metadata.
:param name: the collection name, suitable for use in a URL (no spaces)
:type name: String
:param metadata: a dictionary of metadata values to associate with the new collection
:type metadata: Dict
:rtype: String
:returns: a message confirming creation of the collection
:raises: APIError if the request was not successful | [
"Create",
"a",
"new",
"collection",
"with",
"the",
"given",
"name",
"and",
"attach",
"the",
"metadata",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L895-L918 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.modify_collection_metadata | def modify_collection_metadata(self, collection_uri, metadata, replace=None, name=''):
"""Modify the metadata for the given collection.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param metadata: a dictionary of metadata values to add/modify
:type metadata: Dict
:rtype: String
:returns: a message confirming that the metadata is modified
:raises: APIError if the request was not successful
"""
payload = {
'collection_metadata': metadata,
'name': name
}
if replace is not None:
payload['replace'] = replace
response = self.api_request(collection_uri, method='PUT', data=json.dumps(payload))
return self.__check_success(response) | python | def modify_collection_metadata(self, collection_uri, metadata, replace=None, name=''):
"""Modify the metadata for the given collection.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param metadata: a dictionary of metadata values to add/modify
:type metadata: Dict
:rtype: String
:returns: a message confirming that the metadata is modified
:raises: APIError if the request was not successful
"""
payload = {
'collection_metadata': metadata,
'name': name
}
if replace is not None:
payload['replace'] = replace
response = self.api_request(collection_uri, method='PUT', data=json.dumps(payload))
return self.__check_success(response) | [
"def",
"modify_collection_metadata",
"(",
"self",
",",
"collection_uri",
",",
"metadata",
",",
"replace",
"=",
"None",
",",
"name",
"=",
"''",
")",
":",
"payload",
"=",
"{",
"'collection_metadata'",
":",
"metadata",
",",
"'name'",
":",
"name",
"}",
"if",
"replace",
"is",
"not",
"None",
":",
"payload",
"[",
"'replace'",
"]",
"=",
"replace",
"response",
"=",
"self",
".",
"api_request",
"(",
"collection_uri",
",",
"method",
"=",
"'PUT'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
"return",
"self",
".",
"__check_success",
"(",
"response",
")"
]
| Modify the metadata for the given collection.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param metadata: a dictionary of metadata values to add/modify
:type metadata: Dict
:rtype: String
:returns: a message confirming that the metadata is modified
:raises: APIError if the request was not successful | [
"Modify",
"the",
"metadata",
"for",
"the",
"given",
"collection",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L920-L945 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_items | def get_items(self, collection_uri):
"""Return all items in this collection.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:rtype: List
:returns: a list of the URIs of the items in this collection
"""
cname = os.path.split(collection_uri)[1]
return self.search_metadata("collection_name:%s" % cname) | python | def get_items(self, collection_uri):
"""Return all items in this collection.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:rtype: List
:returns: a list of the URIs of the items in this collection
"""
cname = os.path.split(collection_uri)[1]
return self.search_metadata("collection_name:%s" % cname) | [
"def",
"get_items",
"(",
"self",
",",
"collection_uri",
")",
":",
"cname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"collection_uri",
")",
"[",
"1",
"]",
"return",
"self",
".",
"search_metadata",
"(",
"\"collection_name:%s\"",
"%",
"cname",
")"
]
| Return all items in this collection.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:rtype: List
:returns: a list of the URIs of the items in this collection | [
"Return",
"all",
"items",
"in",
"this",
"collection",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L947-L959 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.add_text_item | def add_text_item(self, collection_uri, name, metadata, text, title=None):
"""Add a new item to a collection containing a single
text document.
The full text of the text document is specified as the text
argument and will be stored with the same name as the
item and a .txt extension.
This is a shorthand for the more general add_item method.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param name: The item name, suitable for use in a URI (no spaces)
:type name: String
:param metadata: a dictionary of metadata values describing the item
:type metadata: Dict
:param text: the full text of the document associated with this item
:type text: String
:param title: document title, defaults to the item name
:type title: String
:rtype String
:returns: the URI of the created item
:raises: APIError if the request was not successful
"""
docname = name + ".txt"
if title is None:
title = name
metadata['dcterms:identifier'] = name
metadata['@type'] = 'ausnc:AusNCObject'
metadata['hcsvlab:display_document'] = {'@id': docname}
metadata['hcsvlab:indexable_document'] = {'@id': docname}
metadata['ausnc:document'] = [{ '@id': 'document1.txt',
'@type': 'foaf:Document',
'dcterms:extent': len(text),
'dcterms:identifier': docname,
'dcterms:title': title,
'dcterms:type': 'Text'}]
meta = {'items': [{'metadata': { '@context': self.context,
'@graph': [metadata]
},
'documents': [{'content': text, 'identifier': docname}]
}]
}
response = self.api_request(collection_uri, method='POST', data=json.dumps(meta))
# this will raise an exception if the request fails
self.__check_success(response)
item_uri = collection_uri + "/" + response['success'][0]
return item_uri | python | def add_text_item(self, collection_uri, name, metadata, text, title=None):
"""Add a new item to a collection containing a single
text document.
The full text of the text document is specified as the text
argument and will be stored with the same name as the
item and a .txt extension.
This is a shorthand for the more general add_item method.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param name: The item name, suitable for use in a URI (no spaces)
:type name: String
:param metadata: a dictionary of metadata values describing the item
:type metadata: Dict
:param text: the full text of the document associated with this item
:type text: String
:param title: document title, defaults to the item name
:type title: String
:rtype String
:returns: the URI of the created item
:raises: APIError if the request was not successful
"""
docname = name + ".txt"
if title is None:
title = name
metadata['dcterms:identifier'] = name
metadata['@type'] = 'ausnc:AusNCObject'
metadata['hcsvlab:display_document'] = {'@id': docname}
metadata['hcsvlab:indexable_document'] = {'@id': docname}
metadata['ausnc:document'] = [{ '@id': 'document1.txt',
'@type': 'foaf:Document',
'dcterms:extent': len(text),
'dcterms:identifier': docname,
'dcterms:title': title,
'dcterms:type': 'Text'}]
meta = {'items': [{'metadata': { '@context': self.context,
'@graph': [metadata]
},
'documents': [{'content': text, 'identifier': docname}]
}]
}
response = self.api_request(collection_uri, method='POST', data=json.dumps(meta))
# this will raise an exception if the request fails
self.__check_success(response)
item_uri = collection_uri + "/" + response['success'][0]
return item_uri | [
"def",
"add_text_item",
"(",
"self",
",",
"collection_uri",
",",
"name",
",",
"metadata",
",",
"text",
",",
"title",
"=",
"None",
")",
":",
"docname",
"=",
"name",
"+",
"\".txt\"",
"if",
"title",
"is",
"None",
":",
"title",
"=",
"name",
"metadata",
"[",
"'dcterms:identifier'",
"]",
"=",
"name",
"metadata",
"[",
"'@type'",
"]",
"=",
"'ausnc:AusNCObject'",
"metadata",
"[",
"'hcsvlab:display_document'",
"]",
"=",
"{",
"'@id'",
":",
"docname",
"}",
"metadata",
"[",
"'hcsvlab:indexable_document'",
"]",
"=",
"{",
"'@id'",
":",
"docname",
"}",
"metadata",
"[",
"'ausnc:document'",
"]",
"=",
"[",
"{",
"'@id'",
":",
"'document1.txt'",
",",
"'@type'",
":",
"'foaf:Document'",
",",
"'dcterms:extent'",
":",
"len",
"(",
"text",
")",
",",
"'dcterms:identifier'",
":",
"docname",
",",
"'dcterms:title'",
":",
"title",
",",
"'dcterms:type'",
":",
"'Text'",
"}",
"]",
"meta",
"=",
"{",
"'items'",
":",
"[",
"{",
"'metadata'",
":",
"{",
"'@context'",
":",
"self",
".",
"context",
",",
"'@graph'",
":",
"[",
"metadata",
"]",
"}",
",",
"'documents'",
":",
"[",
"{",
"'content'",
":",
"text",
",",
"'identifier'",
":",
"docname",
"}",
"]",
"}",
"]",
"}",
"response",
"=",
"self",
".",
"api_request",
"(",
"collection_uri",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"meta",
")",
")",
"# this will raise an exception if the request fails",
"self",
".",
"__check_success",
"(",
"response",
")",
"item_uri",
"=",
"collection_uri",
"+",
"\"/\"",
"+",
"response",
"[",
"'success'",
"]",
"[",
"0",
"]",
"return",
"item_uri"
]
| Add a new item to a collection containing a single
text document.
The full text of the text document is specified as the text
argument and will be stored with the same name as the
item and a .txt extension.
This is a shorthand for the more general add_item method.
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param name: The item name, suitable for use in a URI (no spaces)
:type name: String
:param metadata: a dictionary of metadata values describing the item
:type metadata: Dict
:param text: the full text of the document associated with this item
:type text: String
:param title: document title, defaults to the item name
:type title: String
:rtype String
:returns: the URI of the created item
:raises: APIError if the request was not successful | [
"Add",
"a",
"new",
"item",
"to",
"a",
"collection",
"containing",
"a",
"single",
"text",
"document",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L961-L1023 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.add_item | def add_item(self, collection_uri, name, metadata):
"""Add a new item to a collection
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param name: The item name, suitable for use in a URI (no spaces)
:type name: String
:param metadata: a dictionary of metadata values describing the item
:type metadata: Dict
:rtype String
:returns: the URI of the created item
:raises: APIError if the request was not successful
"""
metadata['dcterms:identifier'] = name
metadata['dc:identifier'] = name # for backward compatability in Alveo SOLR store until bug fix
metadata['@type'] = 'ausnc:AusNCObject'
meta = {'items': [{'metadata': { '@context': self.context,
'@graph': [metadata]
}
}]
}
response = self.api_request(collection_uri, method='POST', data=json.dumps(meta))
# this will raise an exception if the request fails
self.__check_success(response)
item_uri = collection_uri + "/" + response['success'][0]
return item_uri | python | def add_item(self, collection_uri, name, metadata):
"""Add a new item to a collection
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param name: The item name, suitable for use in a URI (no spaces)
:type name: String
:param metadata: a dictionary of metadata values describing the item
:type metadata: Dict
:rtype String
:returns: the URI of the created item
:raises: APIError if the request was not successful
"""
metadata['dcterms:identifier'] = name
metadata['dc:identifier'] = name # for backward compatability in Alveo SOLR store until bug fix
metadata['@type'] = 'ausnc:AusNCObject'
meta = {'items': [{'metadata': { '@context': self.context,
'@graph': [metadata]
}
}]
}
response = self.api_request(collection_uri, method='POST', data=json.dumps(meta))
# this will raise an exception if the request fails
self.__check_success(response)
item_uri = collection_uri + "/" + response['success'][0]
return item_uri | [
"def",
"add_item",
"(",
"self",
",",
"collection_uri",
",",
"name",
",",
"metadata",
")",
":",
"metadata",
"[",
"'dcterms:identifier'",
"]",
"=",
"name",
"metadata",
"[",
"'dc:identifier'",
"]",
"=",
"name",
"# for backward compatability in Alveo SOLR store until bug fix",
"metadata",
"[",
"'@type'",
"]",
"=",
"'ausnc:AusNCObject'",
"meta",
"=",
"{",
"'items'",
":",
"[",
"{",
"'metadata'",
":",
"{",
"'@context'",
":",
"self",
".",
"context",
",",
"'@graph'",
":",
"[",
"metadata",
"]",
"}",
"}",
"]",
"}",
"response",
"=",
"self",
".",
"api_request",
"(",
"collection_uri",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"meta",
")",
")",
"# this will raise an exception if the request fails",
"self",
".",
"__check_success",
"(",
"response",
")",
"item_uri",
"=",
"collection_uri",
"+",
"\"/\"",
"+",
"response",
"[",
"'success'",
"]",
"[",
"0",
"]",
"return",
"item_uri"
]
| Add a new item to a collection
:param collection_uri: The URI that references the collection
:type collection_uri: String
:param name: The item name, suitable for use in a URI (no spaces)
:type name: String
:param metadata: a dictionary of metadata values describing the item
:type metadata: Dict
:rtype String
:returns: the URI of the created item
:raises: APIError if the request was not successful | [
"Add",
"a",
"new",
"item",
"to",
"a",
"collection"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1025-L1061 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.modify_item | def modify_item(self, item_uri, metadata):
"""Modify the metadata on an item
"""
md = json.dumps({'metadata': metadata})
response = self.api_request(item_uri, method='PUT', data=md)
return self.__check_success(response) | python | def modify_item(self, item_uri, metadata):
"""Modify the metadata on an item
"""
md = json.dumps({'metadata': metadata})
response = self.api_request(item_uri, method='PUT', data=md)
return self.__check_success(response) | [
"def",
"modify_item",
"(",
"self",
",",
"item_uri",
",",
"metadata",
")",
":",
"md",
"=",
"json",
".",
"dumps",
"(",
"{",
"'metadata'",
":",
"metadata",
"}",
")",
"response",
"=",
"self",
".",
"api_request",
"(",
"item_uri",
",",
"method",
"=",
"'PUT'",
",",
"data",
"=",
"md",
")",
"return",
"self",
".",
"__check_success",
"(",
"response",
")"
]
| Modify the metadata on an item | [
"Modify",
"the",
"metadata",
"on",
"an",
"item"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1063-L1071 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.delete_item | def delete_item(self, item_uri):
"""Delete an item from a collection
:param item_uri: the URI that references the item
:type item_uri: String
:rtype: String
:returns: a message confirming that the metadata is modified
:raises: APIError if the request was not successful
"""
response = self.api_request(item_uri, method='DELETE')
return self.__check_success(response) | python | def delete_item(self, item_uri):
"""Delete an item from a collection
:param item_uri: the URI that references the item
:type item_uri: String
:rtype: String
:returns: a message confirming that the metadata is modified
:raises: APIError if the request was not successful
"""
response = self.api_request(item_uri, method='DELETE')
return self.__check_success(response) | [
"def",
"delete_item",
"(",
"self",
",",
"item_uri",
")",
":",
"response",
"=",
"self",
".",
"api_request",
"(",
"item_uri",
",",
"method",
"=",
"'DELETE'",
")",
"return",
"self",
".",
"__check_success",
"(",
"response",
")"
]
| Delete an item from a collection
:param item_uri: the URI that references the item
:type item_uri: String
:rtype: String
:returns: a message confirming that the metadata is modified
:raises: APIError if the request was not successful | [
"Delete",
"an",
"item",
"from",
"a",
"collection"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1073-L1086 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.add_document | def add_document(self, item_uri, name, metadata,
content=None, docurl=None, file=None,
displaydoc=False, preferName=False,
contrib_id=None):
"""Add a document to an existing item
:param item_uri: the URI that references the item
:type item_uri: String
:param name: The document name
:type name: String
:param metadata: a dictionary of metadata values describing the document
:type metadata: Dict
:param content: optional content of the document
:type content: byte array
:param docurl: optional url referencing the document
:type docurl: String
:param file: optional full path to file to be uploaded
:type file: String
:param displaydoc: if True, make this the display document for the item
:type displaydoc: Boolean
:param preferName: if True, given document name will be the document id rather than
filename. Useful if you want to upload under a different filename.
:type preferName: Boolean
:param contrib_id: if present, add this document to this contribution as well as
associating it with the item
:type contrib_id: Integer
:rtype: String
:returns: The URL of the newly created document
"""
if not preferName and file is not None:
docid = os.path.basename(file)
else:
docid = name
docmeta = {"metadata": {"@context": self.context,
"@type": "foaf:Document",
"dcterms:identifier": docid,
}
}
# add in metadata we are passed
docmeta["metadata"].update(metadata)
if contrib_id:
docmeta['contribution_id'] = contrib_id
if content is not None:
docmeta['document_content'] = content
elif docurl is not None:
docmeta["metadata"]["dcterms:source"] = { "@id": docurl }
elif file is not None:
# we only pass the metadata part of the dictionary
docmeta = docmeta['metadata']
else:
raise Exception("One of content, docurl or file must be specified in add_document")
if file is not None:
result = self.api_request(item_uri, method='POST', data={'metadata': json.dumps(docmeta)}, file=file)
else:
result = self.api_request(item_uri, method='POST', data=json.dumps(docmeta))
self.__check_success(result)
if displaydoc:
itemmeta = {"http://alveo.edu.org/vocabulary/display_document": docid}
self.modify_item(item_uri, itemmeta)
doc_uri = item_uri + "/document/" + name
return doc_uri | python | def add_document(self, item_uri, name, metadata,
content=None, docurl=None, file=None,
displaydoc=False, preferName=False,
contrib_id=None):
"""Add a document to an existing item
:param item_uri: the URI that references the item
:type item_uri: String
:param name: The document name
:type name: String
:param metadata: a dictionary of metadata values describing the document
:type metadata: Dict
:param content: optional content of the document
:type content: byte array
:param docurl: optional url referencing the document
:type docurl: String
:param file: optional full path to file to be uploaded
:type file: String
:param displaydoc: if True, make this the display document for the item
:type displaydoc: Boolean
:param preferName: if True, given document name will be the document id rather than
filename. Useful if you want to upload under a different filename.
:type preferName: Boolean
:param contrib_id: if present, add this document to this contribution as well as
associating it with the item
:type contrib_id: Integer
:rtype: String
:returns: The URL of the newly created document
"""
if not preferName and file is not None:
docid = os.path.basename(file)
else:
docid = name
docmeta = {"metadata": {"@context": self.context,
"@type": "foaf:Document",
"dcterms:identifier": docid,
}
}
# add in metadata we are passed
docmeta["metadata"].update(metadata)
if contrib_id:
docmeta['contribution_id'] = contrib_id
if content is not None:
docmeta['document_content'] = content
elif docurl is not None:
docmeta["metadata"]["dcterms:source"] = { "@id": docurl }
elif file is not None:
# we only pass the metadata part of the dictionary
docmeta = docmeta['metadata']
else:
raise Exception("One of content, docurl or file must be specified in add_document")
if file is not None:
result = self.api_request(item_uri, method='POST', data={'metadata': json.dumps(docmeta)}, file=file)
else:
result = self.api_request(item_uri, method='POST', data=json.dumps(docmeta))
self.__check_success(result)
if displaydoc:
itemmeta = {"http://alveo.edu.org/vocabulary/display_document": docid}
self.modify_item(item_uri, itemmeta)
doc_uri = item_uri + "/document/" + name
return doc_uri | [
"def",
"add_document",
"(",
"self",
",",
"item_uri",
",",
"name",
",",
"metadata",
",",
"content",
"=",
"None",
",",
"docurl",
"=",
"None",
",",
"file",
"=",
"None",
",",
"displaydoc",
"=",
"False",
",",
"preferName",
"=",
"False",
",",
"contrib_id",
"=",
"None",
")",
":",
"if",
"not",
"preferName",
"and",
"file",
"is",
"not",
"None",
":",
"docid",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file",
")",
"else",
":",
"docid",
"=",
"name",
"docmeta",
"=",
"{",
"\"metadata\"",
":",
"{",
"\"@context\"",
":",
"self",
".",
"context",
",",
"\"@type\"",
":",
"\"foaf:Document\"",
",",
"\"dcterms:identifier\"",
":",
"docid",
",",
"}",
"}",
"# add in metadata we are passed",
"docmeta",
"[",
"\"metadata\"",
"]",
".",
"update",
"(",
"metadata",
")",
"if",
"contrib_id",
":",
"docmeta",
"[",
"'contribution_id'",
"]",
"=",
"contrib_id",
"if",
"content",
"is",
"not",
"None",
":",
"docmeta",
"[",
"'document_content'",
"]",
"=",
"content",
"elif",
"docurl",
"is",
"not",
"None",
":",
"docmeta",
"[",
"\"metadata\"",
"]",
"[",
"\"dcterms:source\"",
"]",
"=",
"{",
"\"@id\"",
":",
"docurl",
"}",
"elif",
"file",
"is",
"not",
"None",
":",
"# we only pass the metadata part of the dictionary",
"docmeta",
"=",
"docmeta",
"[",
"'metadata'",
"]",
"else",
":",
"raise",
"Exception",
"(",
"\"One of content, docurl or file must be specified in add_document\"",
")",
"if",
"file",
"is",
"not",
"None",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"item_uri",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"{",
"'metadata'",
":",
"json",
".",
"dumps",
"(",
"docmeta",
")",
"}",
",",
"file",
"=",
"file",
")",
"else",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"item_uri",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"docmeta",
")",
")",
"self",
".",
"__check_success",
"(",
"result",
")",
"if",
"displaydoc",
":",
"itemmeta",
"=",
"{",
"\"http://alveo.edu.org/vocabulary/display_document\"",
":",
"docid",
"}",
"self",
".",
"modify_item",
"(",
"item_uri",
",",
"itemmeta",
")",
"doc_uri",
"=",
"item_uri",
"+",
"\"/document/\"",
"+",
"name",
"return",
"doc_uri"
]
| Add a document to an existing item
:param item_uri: the URI that references the item
:type item_uri: String
:param name: The document name
:type name: String
:param metadata: a dictionary of metadata values describing the document
:type metadata: Dict
:param content: optional content of the document
:type content: byte array
:param docurl: optional url referencing the document
:type docurl: String
:param file: optional full path to file to be uploaded
:type file: String
:param displaydoc: if True, make this the display document for the item
:type displaydoc: Boolean
:param preferName: if True, given document name will be the document id rather than
filename. Useful if you want to upload under a different filename.
:type preferName: Boolean
:param contrib_id: if present, add this document to this contribution as well as
associating it with the item
:type contrib_id: Integer
:rtype: String
:returns: The URL of the newly created document | [
"Add",
"a",
"document",
"to",
"an",
"existing",
"item"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1088-L1167 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.delete_document | def delete_document(self, doc_uri):
"""Delete a document from an item
:param doc_uri: the URI that references the document
:type doc_uri: String
:rtype: String
:returns: a message confirming that the document was deleted
:raises: APIError if the request was not successful
"""
result = self.api_request(doc_uri, method='DELETE')
return self.__check_success(result) | python | def delete_document(self, doc_uri):
"""Delete a document from an item
:param doc_uri: the URI that references the document
:type doc_uri: String
:rtype: String
:returns: a message confirming that the document was deleted
:raises: APIError if the request was not successful
"""
result = self.api_request(doc_uri, method='DELETE')
return self.__check_success(result) | [
"def",
"delete_document",
"(",
"self",
",",
"doc_uri",
")",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"doc_uri",
",",
"method",
"=",
"'DELETE'",
")",
"return",
"self",
".",
"__check_success",
"(",
"result",
")"
]
| Delete a document from an item
:param doc_uri: the URI that references the document
:type doc_uri: String
:rtype: String
:returns: a message confirming that the document was deleted
:raises: APIError if the request was not successful | [
"Delete",
"a",
"document",
"from",
"an",
"item"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1169-L1182 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.__check_success | def __check_success(resp):
""" Check a JSON server response to see if it was successful
:type resp: Dictionary (parsed JSON from response)
:param resp: the response string
:rtype: String
:returns: the success message, if it exists
:raises: APIError if the success message is not present
"""
if "success" not in resp.keys():
try:
raise APIError('200', 'Operation Failed', resp["error"])
except KeyError:
raise APIError('200', 'Operation Failed', str(resp))
return resp["success"] | python | def __check_success(resp):
""" Check a JSON server response to see if it was successful
:type resp: Dictionary (parsed JSON from response)
:param resp: the response string
:rtype: String
:returns: the success message, if it exists
:raises: APIError if the success message is not present
"""
if "success" not in resp.keys():
try:
raise APIError('200', 'Operation Failed', resp["error"])
except KeyError:
raise APIError('200', 'Operation Failed', str(resp))
return resp["success"] | [
"def",
"__check_success",
"(",
"resp",
")",
":",
"if",
"\"success\"",
"not",
"in",
"resp",
".",
"keys",
"(",
")",
":",
"try",
":",
"raise",
"APIError",
"(",
"'200'",
",",
"'Operation Failed'",
",",
"resp",
"[",
"\"error\"",
"]",
")",
"except",
"KeyError",
":",
"raise",
"APIError",
"(",
"'200'",
",",
"'Operation Failed'",
",",
"str",
"(",
"resp",
")",
")",
"return",
"resp",
"[",
"\"success\"",
"]"
]
| Check a JSON server response to see if it was successful
:type resp: Dictionary (parsed JSON from response)
:param resp: the response string
:rtype: String
:returns: the success message, if it exists
:raises: APIError if the success message is not present | [
"Check",
"a",
"JSON",
"server",
"response",
"to",
"see",
"if",
"it",
"was",
"successful"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1185-L1204 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.download_items | def download_items(self, items, file_path, file_format='zip'):
""" Retrieve a file from the server containing the metadata
and documents for the speficied items
:type items: List or ItemGroup
:param items: List of the the URLs of the items to download,
or an ItemGroup object
:type file_path: String
:param file_path: the path to which to save the file
:type file_format: String
:param file_format: the file format to request from the server: specify
either 'zip' or 'warc'
:rtype: String
:returns: the file path
:raises: APIError if the API request is not successful
"""
download_url = '/catalog/download_items'
download_url += '?' + urlencode((('format', file_format),))
item_data = {'items': list(items)}
data = self.api_request(download_url, method='POST', data=json.dumps(item_data), raw=True)
with open(file_path, 'w') as f:
f.write(data)
return file_path | python | def download_items(self, items, file_path, file_format='zip'):
""" Retrieve a file from the server containing the metadata
and documents for the speficied items
:type items: List or ItemGroup
:param items: List of the the URLs of the items to download,
or an ItemGroup object
:type file_path: String
:param file_path: the path to which to save the file
:type file_format: String
:param file_format: the file format to request from the server: specify
either 'zip' or 'warc'
:rtype: String
:returns: the file path
:raises: APIError if the API request is not successful
"""
download_url = '/catalog/download_items'
download_url += '?' + urlencode((('format', file_format),))
item_data = {'items': list(items)}
data = self.api_request(download_url, method='POST', data=json.dumps(item_data), raw=True)
with open(file_path, 'w') as f:
f.write(data)
return file_path | [
"def",
"download_items",
"(",
"self",
",",
"items",
",",
"file_path",
",",
"file_format",
"=",
"'zip'",
")",
":",
"download_url",
"=",
"'/catalog/download_items'",
"download_url",
"+=",
"'?'",
"+",
"urlencode",
"(",
"(",
"(",
"'format'",
",",
"file_format",
")",
",",
")",
")",
"item_data",
"=",
"{",
"'items'",
":",
"list",
"(",
"items",
")",
"}",
"data",
"=",
"self",
".",
"api_request",
"(",
"download_url",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"item_data",
")",
",",
"raw",
"=",
"True",
")",
"with",
"open",
"(",
"file_path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"data",
")",
"return",
"file_path"
]
| Retrieve a file from the server containing the metadata
and documents for the speficied items
:type items: List or ItemGroup
:param items: List of the the URLs of the items to download,
or an ItemGroup object
:type file_path: String
:param file_path: the path to which to save the file
:type file_format: String
:param file_format: the file format to request from the server: specify
either 'zip' or 'warc'
:rtype: String
:returns: the file path
:raises: APIError if the API request is not successful | [
"Retrieve",
"a",
"file",
"from",
"the",
"server",
"containing",
"the",
"metadata",
"and",
"documents",
"for",
"the",
"speficied",
"items"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1206-L1235 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.search_metadata | def search_metadata(self, query):
""" Submit a search query to the server and retrieve the results
:type query: String
:param query: the search query
:rtype: ItemGroup
:returns: the search results
:raises: APIError if the API request is not successful
"""
query_url = ('/catalog/search?' +
urlencode((('metadata', query),)))
resp = self.api_request(query_url)
return ItemGroup(resp['items'], self) | python | def search_metadata(self, query):
""" Submit a search query to the server and retrieve the results
:type query: String
:param query: the search query
:rtype: ItemGroup
:returns: the search results
:raises: APIError if the API request is not successful
"""
query_url = ('/catalog/search?' +
urlencode((('metadata', query),)))
resp = self.api_request(query_url)
return ItemGroup(resp['items'], self) | [
"def",
"search_metadata",
"(",
"self",
",",
"query",
")",
":",
"query_url",
"=",
"(",
"'/catalog/search?'",
"+",
"urlencode",
"(",
"(",
"(",
"'metadata'",
",",
"query",
")",
",",
")",
")",
")",
"resp",
"=",
"self",
".",
"api_request",
"(",
"query_url",
")",
"return",
"ItemGroup",
"(",
"resp",
"[",
"'items'",
"]",
",",
"self",
")"
]
| Submit a search query to the server and retrieve the results
:type query: String
:param query: the search query
:rtype: ItemGroup
:returns: the search results
:raises: APIError if the API request is not successful | [
"Submit",
"a",
"search",
"query",
"to",
"the",
"server",
"and",
"retrieve",
"the",
"results"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1237-L1254 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.add_to_item_list | def add_to_item_list(self, item_urls, item_list_url):
""" Instruct the server to add the given items to the specified
Item List
:type item_urls: List or ItemGroup
:param item_urls: List of URLs for the items to add,
or an ItemGroup object
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:rtype: String
:returns: the server success message, if successful
:raises: APIError if the request was not successful
"""
item_list_url = str(item_list_url)
name = self.get_item_list(item_list_url).name()
return self.add_to_item_list_by_name(item_urls, name) | python | def add_to_item_list(self, item_urls, item_list_url):
""" Instruct the server to add the given items to the specified
Item List
:type item_urls: List or ItemGroup
:param item_urls: List of URLs for the items to add,
or an ItemGroup object
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:rtype: String
:returns: the server success message, if successful
:raises: APIError if the request was not successful
"""
item_list_url = str(item_list_url)
name = self.get_item_list(item_list_url).name()
return self.add_to_item_list_by_name(item_urls, name) | [
"def",
"add_to_item_list",
"(",
"self",
",",
"item_urls",
",",
"item_list_url",
")",
":",
"item_list_url",
"=",
"str",
"(",
"item_list_url",
")",
"name",
"=",
"self",
".",
"get_item_list",
"(",
"item_list_url",
")",
".",
"name",
"(",
")",
"return",
"self",
".",
"add_to_item_list_by_name",
"(",
"item_urls",
",",
"name",
")"
]
| Instruct the server to add the given items to the specified
Item List
:type item_urls: List or ItemGroup
:param item_urls: List of URLs for the items to add,
or an ItemGroup object
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:rtype: String
:returns: the server success message, if successful
:raises: APIError if the request was not successful | [
"Instruct",
"the",
"server",
"to",
"add",
"the",
"given",
"items",
"to",
"the",
"specified",
"Item",
"List"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1295-L1315 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.rename_item_list | def rename_item_list(self, item_list_url, new_name):
""" Rename an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:type new_name: String
:param new_name: the new name to give the Item List
:rtype: ItemList
:returns: the item list, if successful
:raises: APIError if the request was not successful
"""
data = json.dumps({'name': new_name})
resp = self.api_request(str(item_list_url), data, method="PUT")
try:
return ItemList(resp['items'], self, item_list_url, resp['name'])
except KeyError:
try:
raise APIError('200', 'Rename operation failed', resp['error'])
except KeyError:
raise APIError('200', 'Rename operation failed', resp) | python | def rename_item_list(self, item_list_url, new_name):
""" Rename an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:type new_name: String
:param new_name: the new name to give the Item List
:rtype: ItemList
:returns: the item list, if successful
:raises: APIError if the request was not successful
"""
data = json.dumps({'name': new_name})
resp = self.api_request(str(item_list_url), data, method="PUT")
try:
return ItemList(resp['items'], self, item_list_url, resp['name'])
except KeyError:
try:
raise APIError('200', 'Rename operation failed', resp['error'])
except KeyError:
raise APIError('200', 'Rename operation failed', resp) | [
"def",
"rename_item_list",
"(",
"self",
",",
"item_list_url",
",",
"new_name",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'name'",
":",
"new_name",
"}",
")",
"resp",
"=",
"self",
".",
"api_request",
"(",
"str",
"(",
"item_list_url",
")",
",",
"data",
",",
"method",
"=",
"\"PUT\"",
")",
"try",
":",
"return",
"ItemList",
"(",
"resp",
"[",
"'items'",
"]",
",",
"self",
",",
"item_list_url",
",",
"resp",
"[",
"'name'",
"]",
")",
"except",
"KeyError",
":",
"try",
":",
"raise",
"APIError",
"(",
"'200'",
",",
"'Rename operation failed'",
",",
"resp",
"[",
"'error'",
"]",
")",
"except",
"KeyError",
":",
"raise",
"APIError",
"(",
"'200'",
",",
"'Rename operation failed'",
",",
"resp",
")"
]
| Rename an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:type new_name: String
:param new_name: the new name to give the Item List
:rtype: ItemList
:returns: the item list, if successful
:raises: APIError if the request was not successful | [
"Rename",
"an",
"Item",
"List",
"on",
"the",
"server"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1341-L1366 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.delete_item_list | def delete_item_list(self, item_list_url):
""" Delete an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:rtype: Boolean
:returns: True if the item list was deleted
:raises: APIError if the request was not successful
"""
try:
resp = self.api_request(str(item_list_url), method="DELETE")
# all good if it says success
if 'success' in resp:
return True
else:
raise APIError('200', 'Operation Failed', 'Delete operation failed')
except APIError as e:
if e.http_status_code == 302:
return True
else:
raise e | python | def delete_item_list(self, item_list_url):
""" Delete an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:rtype: Boolean
:returns: True if the item list was deleted
:raises: APIError if the request was not successful
"""
try:
resp = self.api_request(str(item_list_url), method="DELETE")
# all good if it says success
if 'success' in resp:
return True
else:
raise APIError('200', 'Operation Failed', 'Delete operation failed')
except APIError as e:
if e.http_status_code == 302:
return True
else:
raise e | [
"def",
"delete_item_list",
"(",
"self",
",",
"item_list_url",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"api_request",
"(",
"str",
"(",
"item_list_url",
")",
",",
"method",
"=",
"\"DELETE\"",
")",
"# all good if it says success",
"if",
"'success'",
"in",
"resp",
":",
"return",
"True",
"else",
":",
"raise",
"APIError",
"(",
"'200'",
",",
"'Operation Failed'",
",",
"'Delete operation failed'",
")",
"except",
"APIError",
"as",
"e",
":",
"if",
"e",
".",
"http_status_code",
"==",
"302",
":",
"return",
"True",
"else",
":",
"raise",
"e"
]
| Delete an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:rtype: Boolean
:returns: True if the item list was deleted
:raises: APIError if the request was not successful | [
"Delete",
"an",
"Item",
"List",
"on",
"the",
"server"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1368-L1393 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_speakers | def get_speakers(self, collection_name):
"""Get a list of speaker URLs for this collection
:type collection_name: String
:param collection_name: the name of the collection to search
:rtype: List
:returns: a list of URLs for the speakers associated with
the given collection
"""
speakers_url = "/speakers/"+collection_name
resp = self.api_request(speakers_url)
if 'speakers' in resp:
return resp['speakers']
else:
return [] | python | def get_speakers(self, collection_name):
"""Get a list of speaker URLs for this collection
:type collection_name: String
:param collection_name: the name of the collection to search
:rtype: List
:returns: a list of URLs for the speakers associated with
the given collection
"""
speakers_url = "/speakers/"+collection_name
resp = self.api_request(speakers_url)
if 'speakers' in resp:
return resp['speakers']
else:
return [] | [
"def",
"get_speakers",
"(",
"self",
",",
"collection_name",
")",
":",
"speakers_url",
"=",
"\"/speakers/\"",
"+",
"collection_name",
"resp",
"=",
"self",
".",
"api_request",
"(",
"speakers_url",
")",
"if",
"'speakers'",
"in",
"resp",
":",
"return",
"resp",
"[",
"'speakers'",
"]",
"else",
":",
"return",
"[",
"]"
]
| Get a list of speaker URLs for this collection
:type collection_name: String
:param collection_name: the name of the collection to search
:rtype: List
:returns: a list of URLs for the speakers associated with
the given collection | [
"Get",
"a",
"list",
"of",
"speaker",
"URLs",
"for",
"this",
"collection"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1395-L1412 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.add_speaker | def add_speaker(self, collection_name, metadata):
"""Add a new speaker to this collection.
:type collection_name: String
:param collection_name: the name of the collection to search
:type metadata: Dict
:param metadata: dictionary of metadata properties and values
for this speaker. Must include 'dcterms:identifier' a unique
identifier for the speaker.
:rtype: String
:returns: the URL of the newly created speaker, or None if there was an
error
"""
if 'dcterms:identifier' not in metadata:
raise APIError(msg="No identifier in speaker metadata")
if '@context' not in metadata:
metadata['@context'] = CONTEXT
speakers_url = "/speakers/"+collection_name+"/"
resp = self.api_request(speakers_url, data=json.dumps(metadata), method="POST")
if 'success' in resp:
return resp['success']['URI']
else:
return None | python | def add_speaker(self, collection_name, metadata):
"""Add a new speaker to this collection.
:type collection_name: String
:param collection_name: the name of the collection to search
:type metadata: Dict
:param metadata: dictionary of metadata properties and values
for this speaker. Must include 'dcterms:identifier' a unique
identifier for the speaker.
:rtype: String
:returns: the URL of the newly created speaker, or None if there was an
error
"""
if 'dcterms:identifier' not in metadata:
raise APIError(msg="No identifier in speaker metadata")
if '@context' not in metadata:
metadata['@context'] = CONTEXT
speakers_url = "/speakers/"+collection_name+"/"
resp = self.api_request(speakers_url, data=json.dumps(metadata), method="POST")
if 'success' in resp:
return resp['success']['URI']
else:
return None | [
"def",
"add_speaker",
"(",
"self",
",",
"collection_name",
",",
"metadata",
")",
":",
"if",
"'dcterms:identifier'",
"not",
"in",
"metadata",
":",
"raise",
"APIError",
"(",
"msg",
"=",
"\"No identifier in speaker metadata\"",
")",
"if",
"'@context'",
"not",
"in",
"metadata",
":",
"metadata",
"[",
"'@context'",
"]",
"=",
"CONTEXT",
"speakers_url",
"=",
"\"/speakers/\"",
"+",
"collection_name",
"+",
"\"/\"",
"resp",
"=",
"self",
".",
"api_request",
"(",
"speakers_url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"metadata",
")",
",",
"method",
"=",
"\"POST\"",
")",
"if",
"'success'",
"in",
"resp",
":",
"return",
"resp",
"[",
"'success'",
"]",
"[",
"'URI'",
"]",
"else",
":",
"return",
"None"
]
| Add a new speaker to this collection.
:type collection_name: String
:param collection_name: the name of the collection to search
:type metadata: Dict
:param metadata: dictionary of metadata properties and values
for this speaker. Must include 'dcterms:identifier' a unique
identifier for the speaker.
:rtype: String
:returns: the URL of the newly created speaker, or None if there was an
error | [
"Add",
"a",
"new",
"speaker",
"to",
"this",
"collection",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1428-L1455 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.delete_speaker | def delete_speaker(self, speaker_uri):
"""Delete an speaker from a collection
:param speaker_uri: the URI that references the speaker
:type speaker_uri: String
:rtype: Boolean
:returns: True if the speaker was deleted
:raises: APIError if the request was not successful
"""
response = self.api_request(speaker_uri, method='DELETE')
return self.__check_success(response) | python | def delete_speaker(self, speaker_uri):
"""Delete an speaker from a collection
:param speaker_uri: the URI that references the speaker
:type speaker_uri: String
:rtype: Boolean
:returns: True if the speaker was deleted
:raises: APIError if the request was not successful
"""
response = self.api_request(speaker_uri, method='DELETE')
return self.__check_success(response) | [
"def",
"delete_speaker",
"(",
"self",
",",
"speaker_uri",
")",
":",
"response",
"=",
"self",
".",
"api_request",
"(",
"speaker_uri",
",",
"method",
"=",
"'DELETE'",
")",
"return",
"self",
".",
"__check_success",
"(",
"response",
")"
]
| Delete an speaker from a collection
:param speaker_uri: the URI that references the speaker
:type speaker_uri: String
:rtype: Boolean
:returns: True if the speaker was deleted
:raises: APIError if the request was not successful | [
"Delete",
"an",
"speaker",
"from",
"a",
"collection"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1457-L1470 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.sparql_query | def sparql_query(self, collection_name, query):
""" Submit a sparql query to the server to search metadata
and annotations.
:type collection_name: String
:param collection_name: the name of the collection to search
:type query: String
:param query: the sparql query
:rtype: Dict
:returns: the query result from the server as a Python dictionary
following the format of the SPARQL JSON result format documented
at http://www.w3.org/TR/rdf-sparql-json-res/
:raises: APIError if the request was not successful
"""
request_url = '/sparql/' + collection_name + '?'
request_url += urlencode((('query', query),))
return self.api_request(request_url) | python | def sparql_query(self, collection_name, query):
""" Submit a sparql query to the server to search metadata
and annotations.
:type collection_name: String
:param collection_name: the name of the collection to search
:type query: String
:param query: the sparql query
:rtype: Dict
:returns: the query result from the server as a Python dictionary
following the format of the SPARQL JSON result format documented
at http://www.w3.org/TR/rdf-sparql-json-res/
:raises: APIError if the request was not successful
"""
request_url = '/sparql/' + collection_name + '?'
request_url += urlencode((('query', query),))
return self.api_request(request_url) | [
"def",
"sparql_query",
"(",
"self",
",",
"collection_name",
",",
"query",
")",
":",
"request_url",
"=",
"'/sparql/'",
"+",
"collection_name",
"+",
"'?'",
"request_url",
"+=",
"urlencode",
"(",
"(",
"(",
"'query'",
",",
"query",
")",
",",
")",
")",
"return",
"self",
".",
"api_request",
"(",
"request_url",
")"
]
| Submit a sparql query to the server to search metadata
and annotations.
:type collection_name: String
:param collection_name: the name of the collection to search
:type query: String
:param query: the sparql query
:rtype: Dict
:returns: the query result from the server as a Python dictionary
following the format of the SPARQL JSON result format documented
at http://www.w3.org/TR/rdf-sparql-json-res/
:raises: APIError if the request was not successful | [
"Submit",
"a",
"sparql",
"query",
"to",
"the",
"server",
"to",
"search",
"metadata",
"and",
"annotations",
"."
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1472-L1493 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.get_contribution | def get_contribution(self, url):
"""Get the details of a particular contribution given it's
url"""
result = self.api_request(url)
# add the contrib id into the metadata
result['id'] = os.path.split(result['url'])[1]
return result | python | def get_contribution(self, url):
"""Get the details of a particular contribution given it's
url"""
result = self.api_request(url)
# add the contrib id into the metadata
result['id'] = os.path.split(result['url'])[1]
return result | [
"def",
"get_contribution",
"(",
"self",
",",
"url",
")",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"url",
")",
"# add the contrib id into the metadata",
"result",
"[",
"'id'",
"]",
"=",
"os",
".",
"path",
".",
"split",
"(",
"result",
"[",
"'url'",
"]",
")",
"[",
"1",
"]",
"return",
"result"
]
| Get the details of a particular contribution given it's
url | [
"Get",
"the",
"details",
"of",
"a",
"particular",
"contribution",
"given",
"it",
"s",
"url"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1509-L1518 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.create_contribution | def create_contribution(self, metadata):
"""Create a new contribution given a dictionary of metadata
{
"contribution_name": "HelloWorld",
"contribution_collection": "Cooee",
"contribution_text": "This is contribution description",
"contribution_abstract": "This is contribution abstract"
}
:rtype: dict
:returns: The metadata for the created contribution
"""
result = self.api_request('/contrib/', method='POST', data=json.dumps(metadata))
# add the contrib id into the metadata
result['id'] = os.path.split(result['url'])[1]
return result | python | def create_contribution(self, metadata):
"""Create a new contribution given a dictionary of metadata
{
"contribution_name": "HelloWorld",
"contribution_collection": "Cooee",
"contribution_text": "This is contribution description",
"contribution_abstract": "This is contribution abstract"
}
:rtype: dict
:returns: The metadata for the created contribution
"""
result = self.api_request('/contrib/', method='POST', data=json.dumps(metadata))
# add the contrib id into the metadata
result['id'] = os.path.split(result['url'])[1]
return result | [
"def",
"create_contribution",
"(",
"self",
",",
"metadata",
")",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"'/contrib/'",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"metadata",
")",
")",
"# add the contrib id into the metadata",
"result",
"[",
"'id'",
"]",
"=",
"os",
".",
"path",
".",
"split",
"(",
"result",
"[",
"'url'",
"]",
")",
"[",
"1",
"]",
"return",
"result"
]
| Create a new contribution given a dictionary of metadata
{
"contribution_name": "HelloWorld",
"contribution_collection": "Cooee",
"contribution_text": "This is contribution description",
"contribution_abstract": "This is contribution abstract"
}
:rtype: dict
:returns: The metadata for the created contribution | [
"Create",
"a",
"new",
"contribution",
"given",
"a",
"dictionary",
"of",
"metadata"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1520-L1540 | train |
Alveo/pyalveo | pyalveo/pyalveo.py | Client.delete_contribution | def delete_contribution(self, url):
"""Delete the contribution with this identifier
:rtype: bool
:returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist)
"""
# first validate that this is a real contrib
try:
result = self.api_request(url)
if 'url' in result and 'documents' in result:
self.api_request(result['url'], method='DELETE')
return True
except:
pass
return False | python | def delete_contribution(self, url):
"""Delete the contribution with this identifier
:rtype: bool
:returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist)
"""
# first validate that this is a real contrib
try:
result = self.api_request(url)
if 'url' in result and 'documents' in result:
self.api_request(result['url'], method='DELETE')
return True
except:
pass
return False | [
"def",
"delete_contribution",
"(",
"self",
",",
"url",
")",
":",
"# first validate that this is a real contrib",
"try",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"url",
")",
"if",
"'url'",
"in",
"result",
"and",
"'documents'",
"in",
"result",
":",
"self",
".",
"api_request",
"(",
"result",
"[",
"'url'",
"]",
",",
"method",
"=",
"'DELETE'",
")",
"return",
"True",
"except",
":",
"pass",
"return",
"False"
]
| Delete the contribution with this identifier
:rtype: bool
:returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist) | [
"Delete",
"the",
"contribution",
"with",
"this",
"identifier"
]
| 1e9eec22bc031bc9a08066f9966565a546e6242e | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1542-L1559 | train |
TUNE-Archive/freight_forwarder | build.py | lint | def lint():
"""
run linter on our code base.
"""
path = os.path.realpath(os.getcwd())
cmd = 'flake8 %s' % path
opt = ''
print(">>> Linting codebase with the following command: %s %s" % (cmd, opt))
try:
return_code = call([cmd, opt], shell=True)
if return_code < 0:
print(">>> Terminated by signal", -return_code, file=sys.stderr)
elif return_code != 0:
sys.exit('>>> Lint checks failed')
else:
print(">>> Lint checks passed", return_code, file=sys.stderr)
except OSError as e:
print(">>> Execution failed:", e, file=sys.stderr) | python | def lint():
"""
run linter on our code base.
"""
path = os.path.realpath(os.getcwd())
cmd = 'flake8 %s' % path
opt = ''
print(">>> Linting codebase with the following command: %s %s" % (cmd, opt))
try:
return_code = call([cmd, opt], shell=True)
if return_code < 0:
print(">>> Terminated by signal", -return_code, file=sys.stderr)
elif return_code != 0:
sys.exit('>>> Lint checks failed')
else:
print(">>> Lint checks passed", return_code, file=sys.stderr)
except OSError as e:
print(">>> Execution failed:", e, file=sys.stderr) | [
"def",
"lint",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"cmd",
"=",
"'flake8 %s'",
"%",
"path",
"opt",
"=",
"''",
"print",
"(",
"\">>> Linting codebase with the following command: %s %s\"",
"%",
"(",
"cmd",
",",
"opt",
")",
")",
"try",
":",
"return_code",
"=",
"call",
"(",
"[",
"cmd",
",",
"opt",
"]",
",",
"shell",
"=",
"True",
")",
"if",
"return_code",
"<",
"0",
":",
"print",
"(",
"\">>> Terminated by signal\"",
",",
"-",
"return_code",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"elif",
"return_code",
"!=",
"0",
":",
"sys",
".",
"exit",
"(",
"'>>> Lint checks failed'",
")",
"else",
":",
"print",
"(",
"\">>> Lint checks passed\"",
",",
"return_code",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"except",
"OSError",
"as",
"e",
":",
"print",
"(",
"\">>> Execution failed:\"",
",",
"e",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
]
| run linter on our code base. | [
"run",
"linter",
"on",
"our",
"code",
"base",
"."
]
| 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/build.py#L12-L30 | train |
Kortemme-Lab/klab | klab/tui/utils.py | prompt_yn | def prompt_yn(stmt):
'''Prints the statement stmt to the terminal and wait for a Y or N answer.
Returns True for 'Y', False for 'N'.'''
print(stmt)
answer = ''
while answer not in ['Y', 'N']:
sys.stdout.write("$ ")
answer = sys.stdin.readline().upper().strip()
return answer == 'Y' | python | def prompt_yn(stmt):
'''Prints the statement stmt to the terminal and wait for a Y or N answer.
Returns True for 'Y', False for 'N'.'''
print(stmt)
answer = ''
while answer not in ['Y', 'N']:
sys.stdout.write("$ ")
answer = sys.stdin.readline().upper().strip()
return answer == 'Y' | [
"def",
"prompt_yn",
"(",
"stmt",
")",
":",
"print",
"(",
"stmt",
")",
"answer",
"=",
"''",
"while",
"answer",
"not",
"in",
"[",
"'Y'",
",",
"'N'",
"]",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"$ \"",
")",
"answer",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
"return",
"answer",
"==",
"'Y'"
]
| Prints the statement stmt to the terminal and wait for a Y or N answer.
Returns True for 'Y', False for 'N'. | [
"Prints",
"the",
"statement",
"stmt",
"to",
"the",
"terminal",
"and",
"wait",
"for",
"a",
"Y",
"or",
"N",
"answer",
".",
"Returns",
"True",
"for",
"Y",
"False",
"for",
"N",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/tui/utils.py#L4-L12 | train |
assamite/creamas | creamas/core/environment.py | Environment.get_agents | def get_agents(self, addr=True, agent_cls=None, include_manager=False):
'''Get agents in the environment.
:param bool addr: If ``True``, returns only addresses of the agents.
:param agent_cls:
Optional, if specified returns only agents belonging to that
particular class.
:param bool include_manager:
If `True``` includes the environment's manager, i.e. the agent in
the address ``tcp://environment-host:port/0``, to the returned
list if the environment has attribute :attr:`manager`. If
environment does not have :attr:`manager`, then the parameter does
nothing.
:returns: A list of agents in the environment.
:rtype: list
.. note::
By design, manager agents are excluded from the returned lists of
agents by default.
'''
agents = list(self.agents.dict.values())
if hasattr(self, 'manager') and self.manager is not None:
if not include_manager:
agents = [a for a in agents if a.addr.rsplit('/', 1)[1] != '0']
if agent_cls is not None:
agents = [a for a in agents if type(a) is agent_cls]
if addr:
agents = [agent.addr for agent in agents]
return agents | python | def get_agents(self, addr=True, agent_cls=None, include_manager=False):
'''Get agents in the environment.
:param bool addr: If ``True``, returns only addresses of the agents.
:param agent_cls:
Optional, if specified returns only agents belonging to that
particular class.
:param bool include_manager:
If `True``` includes the environment's manager, i.e. the agent in
the address ``tcp://environment-host:port/0``, to the returned
list if the environment has attribute :attr:`manager`. If
environment does not have :attr:`manager`, then the parameter does
nothing.
:returns: A list of agents in the environment.
:rtype: list
.. note::
By design, manager agents are excluded from the returned lists of
agents by default.
'''
agents = list(self.agents.dict.values())
if hasattr(self, 'manager') and self.manager is not None:
if not include_manager:
agents = [a for a in agents if a.addr.rsplit('/', 1)[1] != '0']
if agent_cls is not None:
agents = [a for a in agents if type(a) is agent_cls]
if addr:
agents = [agent.addr for agent in agents]
return agents | [
"def",
"get_agents",
"(",
"self",
",",
"addr",
"=",
"True",
",",
"agent_cls",
"=",
"None",
",",
"include_manager",
"=",
"False",
")",
":",
"agents",
"=",
"list",
"(",
"self",
".",
"agents",
".",
"dict",
".",
"values",
"(",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"'manager'",
")",
"and",
"self",
".",
"manager",
"is",
"not",
"None",
":",
"if",
"not",
"include_manager",
":",
"agents",
"=",
"[",
"a",
"for",
"a",
"in",
"agents",
"if",
"a",
".",
"addr",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"1",
"]",
"!=",
"'0'",
"]",
"if",
"agent_cls",
"is",
"not",
"None",
":",
"agents",
"=",
"[",
"a",
"for",
"a",
"in",
"agents",
"if",
"type",
"(",
"a",
")",
"is",
"agent_cls",
"]",
"if",
"addr",
":",
"agents",
"=",
"[",
"agent",
".",
"addr",
"for",
"agent",
"in",
"agents",
"]",
"return",
"agents"
]
| Get agents in the environment.
:param bool addr: If ``True``, returns only addresses of the agents.
:param agent_cls:
Optional, if specified returns only agents belonging to that
particular class.
:param bool include_manager:
If `True``` includes the environment's manager, i.e. the agent in
the address ``tcp://environment-host:port/0``, to the returned
list if the environment has attribute :attr:`manager`. If
environment does not have :attr:`manager`, then the parameter does
nothing.
:returns: A list of agents in the environment.
:rtype: list
.. note::
By design, manager agents are excluded from the returned lists of
agents by default. | [
"Get",
"agents",
"in",
"the",
"environment",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L88-L118 | train |
assamite/creamas | creamas/core/environment.py | Environment.trigger_act | async def trigger_act(self, *args, addr=None, agent=None, **kwargs):
'''Trigger agent to act.
If *agent* is None, then looks the agent by the address.
:raises ValueError: if both *agent* and *addr* are None.
'''
if agent is None and addr is None:
raise TypeError("Either addr or agent has to be defined.")
if agent is None:
for a in self.get_agents(addr=False):
if addr == a.addr:
agent = a
self._log(logging.DEBUG, "Triggering agent in {}".format(agent.addr))
ret = await agent.act(*args, **kwargs)
return ret | python | async def trigger_act(self, *args, addr=None, agent=None, **kwargs):
'''Trigger agent to act.
If *agent* is None, then looks the agent by the address.
:raises ValueError: if both *agent* and *addr* are None.
'''
if agent is None and addr is None:
raise TypeError("Either addr or agent has to be defined.")
if agent is None:
for a in self.get_agents(addr=False):
if addr == a.addr:
agent = a
self._log(logging.DEBUG, "Triggering agent in {}".format(agent.addr))
ret = await agent.act(*args, **kwargs)
return ret | [
"async",
"def",
"trigger_act",
"(",
"self",
",",
"*",
"args",
",",
"addr",
"=",
"None",
",",
"agent",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"agent",
"is",
"None",
"and",
"addr",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Either addr or agent has to be defined.\"",
")",
"if",
"agent",
"is",
"None",
":",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
":",
"if",
"addr",
"==",
"a",
".",
"addr",
":",
"agent",
"=",
"a",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"\"Triggering agent in {}\"",
".",
"format",
"(",
"agent",
".",
"addr",
")",
")",
"ret",
"=",
"await",
"agent",
".",
"act",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"ret"
]
| Trigger agent to act.
If *agent* is None, then looks the agent by the address.
:raises ValueError: if both *agent* and *addr* are None. | [
"Trigger",
"agent",
"to",
"act",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L120-L135 | train |
assamite/creamas | creamas/core/environment.py | Environment.trigger_all | async def trigger_all(self, *args, **kwargs):
'''Trigger all agents in the environment to act asynchronously.
:returns: A list of agents' :meth:`act` return values.
Given arguments and keyword arguments are passed down to each agent's
:meth:`creamas.core.agent.CreativeAgent.act`.
.. note::
By design, the environment's manager agent, i.e. if the environment
has :attr:`manager`, is excluded from acting.
'''
tasks = []
for a in self.get_agents(addr=False, include_manager=False):
task = asyncio.ensure_future(self.trigger_act
(*args, agent=a, **kwargs))
tasks.append(task)
rets = await asyncio.gather(*tasks)
return rets | python | async def trigger_all(self, *args, **kwargs):
'''Trigger all agents in the environment to act asynchronously.
:returns: A list of agents' :meth:`act` return values.
Given arguments and keyword arguments are passed down to each agent's
:meth:`creamas.core.agent.CreativeAgent.act`.
.. note::
By design, the environment's manager agent, i.e. if the environment
has :attr:`manager`, is excluded from acting.
'''
tasks = []
for a in self.get_agents(addr=False, include_manager=False):
task = asyncio.ensure_future(self.trigger_act
(*args, agent=a, **kwargs))
tasks.append(task)
rets = await asyncio.gather(*tasks)
return rets | [
"async",
"def",
"trigger_all",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tasks",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
",",
"include_manager",
"=",
"False",
")",
":",
"task",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"trigger_act",
"(",
"*",
"args",
",",
"agent",
"=",
"a",
",",
"*",
"*",
"kwargs",
")",
")",
"tasks",
".",
"append",
"(",
"task",
")",
"rets",
"=",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
")",
"return",
"rets"
]
| Trigger all agents in the environment to act asynchronously.
:returns: A list of agents' :meth:`act` return values.
Given arguments and keyword arguments are passed down to each agent's
:meth:`creamas.core.agent.CreativeAgent.act`.
.. note::
By design, the environment's manager agent, i.e. if the environment
has :attr:`manager`, is excluded from acting. | [
"Trigger",
"all",
"agents",
"in",
"the",
"environment",
"to",
"act",
"asynchronously",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L137-L156 | train |
assamite/creamas | creamas/core/environment.py | Environment.create_random_connections | def create_random_connections(self, n=5):
'''Create random connections for all agents in the environment.
:param int n: the number of connections for each agent
Existing agent connections that would be created by chance are not
doubled in the agent's :attr:`connections`, but count towards
connections created.
'''
if type(n) != int:
raise TypeError("Argument 'n' must be of type int.")
if n <= 0:
raise ValueError("Argument 'n' must be greater than zero.")
for a in self.get_agents(addr=False):
others = self.get_agents(addr=False)[:]
others.remove(a)
shuffle(others)
for r_agent in others[:n]:
a.add_connection(r_agent) | python | def create_random_connections(self, n=5):
'''Create random connections for all agents in the environment.
:param int n: the number of connections for each agent
Existing agent connections that would be created by chance are not
doubled in the agent's :attr:`connections`, but count towards
connections created.
'''
if type(n) != int:
raise TypeError("Argument 'n' must be of type int.")
if n <= 0:
raise ValueError("Argument 'n' must be greater than zero.")
for a in self.get_agents(addr=False):
others = self.get_agents(addr=False)[:]
others.remove(a)
shuffle(others)
for r_agent in others[:n]:
a.add_connection(r_agent) | [
"def",
"create_random_connections",
"(",
"self",
",",
"n",
"=",
"5",
")",
":",
"if",
"type",
"(",
"n",
")",
"!=",
"int",
":",
"raise",
"TypeError",
"(",
"\"Argument 'n' must be of type int.\"",
")",
"if",
"n",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Argument 'n' must be greater than zero.\"",
")",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
":",
"others",
"=",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
"[",
":",
"]",
"others",
".",
"remove",
"(",
"a",
")",
"shuffle",
"(",
"others",
")",
"for",
"r_agent",
"in",
"others",
"[",
":",
"n",
"]",
":",
"a",
".",
"add_connection",
"(",
"r_agent",
")"
]
| Create random connections for all agents in the environment.
:param int n: the number of connections for each agent
Existing agent connections that would be created by chance are not
doubled in the agent's :attr:`connections`, but count towards
connections created. | [
"Create",
"random",
"connections",
"for",
"all",
"agents",
"in",
"the",
"environment",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L178-L196 | train |
assamite/creamas | creamas/core/environment.py | Environment.create_connections | def create_connections(self, connection_map):
'''Create agent connections from a given connection map.
:param dict connection_map:
A map of connections to be created. Dictionary where keys are
agent addresses and values are lists of (addr, attitude)-tuples
suitable for
:meth:`~creamas.core.agent.CreativeAgent.add_connections`.
Only connections for agents in this environment are made.
'''
agents = self.get_agents(addr=False)
rets = []
for a in agents:
if a.addr in connection_map:
r = a.add_connections(connection_map[a.addr])
rets.append(r)
return rets | python | def create_connections(self, connection_map):
'''Create agent connections from a given connection map.
:param dict connection_map:
A map of connections to be created. Dictionary where keys are
agent addresses and values are lists of (addr, attitude)-tuples
suitable for
:meth:`~creamas.core.agent.CreativeAgent.add_connections`.
Only connections for agents in this environment are made.
'''
agents = self.get_agents(addr=False)
rets = []
for a in agents:
if a.addr in connection_map:
r = a.add_connections(connection_map[a.addr])
rets.append(r)
return rets | [
"def",
"create_connections",
"(",
"self",
",",
"connection_map",
")",
":",
"agents",
"=",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
"rets",
"=",
"[",
"]",
"for",
"a",
"in",
"agents",
":",
"if",
"a",
".",
"addr",
"in",
"connection_map",
":",
"r",
"=",
"a",
".",
"add_connections",
"(",
"connection_map",
"[",
"a",
".",
"addr",
"]",
")",
"rets",
".",
"append",
"(",
"r",
")",
"return",
"rets"
]
| Create agent connections from a given connection map.
:param dict connection_map:
A map of connections to be created. Dictionary where keys are
agent addresses and values are lists of (addr, attitude)-tuples
suitable for
:meth:`~creamas.core.agent.CreativeAgent.add_connections`.
Only connections for agents in this environment are made. | [
"Create",
"agent",
"connections",
"from",
"a",
"given",
"connection",
"map",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L198-L215 | train |
assamite/creamas | creamas/core/environment.py | Environment.get_connections | def get_connections(self, data=True):
"""Return connections from all the agents in the environment.
:param bool data:
If ``True`` return also the dictionary associated with each
connection
:returns:
A list of ``(addr, connections)``-tuples, where ``connections`` is
a list of addresses agent in ``addr`` is connected to. If
``data`` parameter is ``True``, then the ``connections``
list contains tuples of ``(nb_addr, data)``-pairs , where ``data``
is a dictionary.
:rtype: dict
.. note::
By design, potential manager agent is excluded from the returned
list.
"""
connections = []
for a in self.get_agents(addr=False):
c = (a.addr, a.get_connections(data=data))
connections.append(c)
return connections | python | def get_connections(self, data=True):
"""Return connections from all the agents in the environment.
:param bool data:
If ``True`` return also the dictionary associated with each
connection
:returns:
A list of ``(addr, connections)``-tuples, where ``connections`` is
a list of addresses agent in ``addr`` is connected to. If
``data`` parameter is ``True``, then the ``connections``
list contains tuples of ``(nb_addr, data)``-pairs , where ``data``
is a dictionary.
:rtype: dict
.. note::
By design, potential manager agent is excluded from the returned
list.
"""
connections = []
for a in self.get_agents(addr=False):
c = (a.addr, a.get_connections(data=data))
connections.append(c)
return connections | [
"def",
"get_connections",
"(",
"self",
",",
"data",
"=",
"True",
")",
":",
"connections",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
":",
"c",
"=",
"(",
"a",
".",
"addr",
",",
"a",
".",
"get_connections",
"(",
"data",
"=",
"data",
")",
")",
"connections",
".",
"append",
"(",
"c",
")",
"return",
"connections"
]
| Return connections from all the agents in the environment.
:param bool data:
If ``True`` return also the dictionary associated with each
connection
:returns:
A list of ``(addr, connections)``-tuples, where ``connections`` is
a list of addresses agent in ``addr`` is connected to. If
``data`` parameter is ``True``, then the ``connections``
list contains tuples of ``(nb_addr, data)``-pairs , where ``data``
is a dictionary.
:rtype: dict
.. note::
By design, potential manager agent is excluded from the returned
list. | [
"Return",
"connections",
"from",
"all",
"the",
"agents",
"in",
"the",
"environment",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L217-L242 | train |
assamite/creamas | creamas/core/environment.py | Environment.get_random_agent | def get_random_agent(self, agent):
'''Return random agent that is not the same as agent given as
parameter.
:param agent: Agent that is not wanted to return
:type agent: :py:class:`~creamas.core.agent.CreativeAgent`
:returns: random, non-connected, agent from the environment
:rtype: :py:class:`~creamas.core.agent.CreativeAgent`
'''
r_agent = choice(self.get_agents(addr=False))
while r_agent.addr == agent.addr:
r_agent = choice(self.get_agents(addr=False))
return r_agent | python | def get_random_agent(self, agent):
'''Return random agent that is not the same as agent given as
parameter.
:param agent: Agent that is not wanted to return
:type agent: :py:class:`~creamas.core.agent.CreativeAgent`
:returns: random, non-connected, agent from the environment
:rtype: :py:class:`~creamas.core.agent.CreativeAgent`
'''
r_agent = choice(self.get_agents(addr=False))
while r_agent.addr == agent.addr:
r_agent = choice(self.get_agents(addr=False))
return r_agent | [
"def",
"get_random_agent",
"(",
"self",
",",
"agent",
")",
":",
"r_agent",
"=",
"choice",
"(",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
")",
"while",
"r_agent",
".",
"addr",
"==",
"agent",
".",
"addr",
":",
"r_agent",
"=",
"choice",
"(",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
")",
"return",
"r_agent"
]
| Return random agent that is not the same as agent given as
parameter.
:param agent: Agent that is not wanted to return
:type agent: :py:class:`~creamas.core.agent.CreativeAgent`
:returns: random, non-connected, agent from the environment
:rtype: :py:class:`~creamas.core.agent.CreativeAgent` | [
"Return",
"random",
"agent",
"that",
"is",
"not",
"the",
"same",
"as",
"agent",
"given",
"as",
"parameter",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L250-L262 | train |
assamite/creamas | creamas/core/environment.py | Environment.add_artifact | def add_artifact(self, artifact):
'''Add artifact with given framing to the environment.
:param object artifact: Artifact to be added.
'''
artifact.env_time = self.age
self.artifacts.append(artifact)
self._log(logging.DEBUG, "ARTIFACTS appended: '{}', length={}"
.format(artifact, len(self.artifacts))) | python | def add_artifact(self, artifact):
'''Add artifact with given framing to the environment.
:param object artifact: Artifact to be added.
'''
artifact.env_time = self.age
self.artifacts.append(artifact)
self._log(logging.DEBUG, "ARTIFACTS appended: '{}', length={}"
.format(artifact, len(self.artifacts))) | [
"def",
"add_artifact",
"(",
"self",
",",
"artifact",
")",
":",
"artifact",
".",
"env_time",
"=",
"self",
".",
"age",
"self",
".",
"artifacts",
".",
"append",
"(",
"artifact",
")",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"\"ARTIFACTS appended: '{}', length={}\"",
".",
"format",
"(",
"artifact",
",",
"len",
"(",
"self",
".",
"artifacts",
")",
")",
")"
]
| Add artifact with given framing to the environment.
:param object artifact: Artifact to be added. | [
"Add",
"artifact",
"with",
"given",
"framing",
"to",
"the",
"environment",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L264-L272 | train |
assamite/creamas | creamas/core/environment.py | Environment.get_artifacts | async def get_artifacts(self, agent=None):
'''Return artifacts published to the environment.
:param agent:
If not ``None``, then returns only artifacts created by the agent.
:returns: All artifacts published (by the agent).
:rtype: list
If environment has a :attr:`manager` agent, e.g. it is a slave
environment in a :class:`~creamas.mp.MultiEnvironment`, then the
manager's :meth:`~creamas.mp.EnvManager.get_artifacts` is called.
'''
# TODO: Figure better way for this
if hasattr(self, 'manager') and self.manager is not None:
artifacts = await self.manager.get_artifacts()
else:
artifacts = self.artifacts
if agent is not None:
artifacts = [a for a in artifacts if agent.name == a.creator]
return artifacts | python | async def get_artifacts(self, agent=None):
'''Return artifacts published to the environment.
:param agent:
If not ``None``, then returns only artifacts created by the agent.
:returns: All artifacts published (by the agent).
:rtype: list
If environment has a :attr:`manager` agent, e.g. it is a slave
environment in a :class:`~creamas.mp.MultiEnvironment`, then the
manager's :meth:`~creamas.mp.EnvManager.get_artifacts` is called.
'''
# TODO: Figure better way for this
if hasattr(self, 'manager') and self.manager is not None:
artifacts = await self.manager.get_artifacts()
else:
artifacts = self.artifacts
if agent is not None:
artifacts = [a for a in artifacts if agent.name == a.creator]
return artifacts | [
"async",
"def",
"get_artifacts",
"(",
"self",
",",
"agent",
"=",
"None",
")",
":",
"# TODO: Figure better way for this",
"if",
"hasattr",
"(",
"self",
",",
"'manager'",
")",
"and",
"self",
".",
"manager",
"is",
"not",
"None",
":",
"artifacts",
"=",
"await",
"self",
".",
"manager",
".",
"get_artifacts",
"(",
")",
"else",
":",
"artifacts",
"=",
"self",
".",
"artifacts",
"if",
"agent",
"is",
"not",
"None",
":",
"artifacts",
"=",
"[",
"a",
"for",
"a",
"in",
"artifacts",
"if",
"agent",
".",
"name",
"==",
"a",
".",
"creator",
"]",
"return",
"artifacts"
]
| Return artifacts published to the environment.
:param agent:
If not ``None``, then returns only artifacts created by the agent.
:returns: All artifacts published (by the agent).
:rtype: list
If environment has a :attr:`manager` agent, e.g. it is a slave
environment in a :class:`~creamas.mp.MultiEnvironment`, then the
manager's :meth:`~creamas.mp.EnvManager.get_artifacts` is called. | [
"Return",
"artifacts",
"published",
"to",
"the",
"environment",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L283-L303 | train |
assamite/creamas | creamas/core/environment.py | Environment.destroy | def destroy(self, folder=None, as_coro=False):
'''Destroy the environment.
Does the following:
1. calls :py:meth:`~creamas.core.Environment.save_info`
2. for each agent: calls :py:meth:`close`
3. Shuts down its RPC-service.
'''
async def _destroy(folder):
ret = self.save_info(folder)
for a in self.get_agents(addr=False):
a.close(folder=folder)
await self.shutdown(as_coro=True)
return ret
return run_or_coro(_destroy(folder), as_coro) | python | def destroy(self, folder=None, as_coro=False):
'''Destroy the environment.
Does the following:
1. calls :py:meth:`~creamas.core.Environment.save_info`
2. for each agent: calls :py:meth:`close`
3. Shuts down its RPC-service.
'''
async def _destroy(folder):
ret = self.save_info(folder)
for a in self.get_agents(addr=False):
a.close(folder=folder)
await self.shutdown(as_coro=True)
return ret
return run_or_coro(_destroy(folder), as_coro) | [
"def",
"destroy",
"(",
"self",
",",
"folder",
"=",
"None",
",",
"as_coro",
"=",
"False",
")",
":",
"async",
"def",
"_destroy",
"(",
"folder",
")",
":",
"ret",
"=",
"self",
".",
"save_info",
"(",
"folder",
")",
"for",
"a",
"in",
"self",
".",
"get_agents",
"(",
"addr",
"=",
"False",
")",
":",
"a",
".",
"close",
"(",
"folder",
"=",
"folder",
")",
"await",
"self",
".",
"shutdown",
"(",
"as_coro",
"=",
"True",
")",
"return",
"ret",
"return",
"run_or_coro",
"(",
"_destroy",
"(",
"folder",
")",
",",
"as_coro",
")"
]
| Destroy the environment.
Does the following:
1. calls :py:meth:`~creamas.core.Environment.save_info`
2. for each agent: calls :py:meth:`close`
3. Shuts down its RPC-service. | [
"Destroy",
"the",
"environment",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/environment.py#L319-L335 | train |
Kortemme-Lab/klab | klab/process.py | tee | def tee(*popenargs, **kwargs):
"""
Run a command as if it were piped though tee.
Output generated by the command is displayed in real time to the terminal.
It is also captured in strings and returned once the process terminated.
This function is very useful for logging output from cluster runs. Naive
approaches like check_output() are vulnerable to crashes (i.e. if a job
exceeds its time limit) if they hold all output until the end. This
function echos any output as soon as it's generated, so that the cluster
logging system will still work.
"""
import subprocess, select, sys
process = subprocess.Popen(
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
*popenargs, **kwargs)
stdout, stderr = '', ''
def read_stream(input_callback, output_stream): # (no fold)
read = input_callback()
output_stream.write(read)
output_stream.flush()
return read
while process.poll() is None:
watch = process.stdout.fileno(), process.stderr.fileno()
ready = select.select(watch, [], [])[0]
for fd in ready:
if fd == process.stdout.fileno():
stdout += read_stream(process.stdout.readline, sys.stdout)
if fd == process.stderr.fileno():
stderr += read_stream(process.stderr.readline, sys.stderr)
stdout += read_stream(process.stdout.read, sys.stdout)
stderr += read_stream(process.stderr.read, sys.stderr)
return stdout, stderr | python | def tee(*popenargs, **kwargs):
"""
Run a command as if it were piped though tee.
Output generated by the command is displayed in real time to the terminal.
It is also captured in strings and returned once the process terminated.
This function is very useful for logging output from cluster runs. Naive
approaches like check_output() are vulnerable to crashes (i.e. if a job
exceeds its time limit) if they hold all output until the end. This
function echos any output as soon as it's generated, so that the cluster
logging system will still work.
"""
import subprocess, select, sys
process = subprocess.Popen(
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
*popenargs, **kwargs)
stdout, stderr = '', ''
def read_stream(input_callback, output_stream): # (no fold)
read = input_callback()
output_stream.write(read)
output_stream.flush()
return read
while process.poll() is None:
watch = process.stdout.fileno(), process.stderr.fileno()
ready = select.select(watch, [], [])[0]
for fd in ready:
if fd == process.stdout.fileno():
stdout += read_stream(process.stdout.readline, sys.stdout)
if fd == process.stderr.fileno():
stderr += read_stream(process.stderr.readline, sys.stderr)
stdout += read_stream(process.stdout.read, sys.stdout)
stderr += read_stream(process.stderr.read, sys.stderr)
return stdout, stderr | [
"def",
"tee",
"(",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"subprocess",
",",
"select",
",",
"sys",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
"stdout",
",",
"stderr",
"=",
"''",
",",
"''",
"def",
"read_stream",
"(",
"input_callback",
",",
"output_stream",
")",
":",
"# (no fold)",
"read",
"=",
"input_callback",
"(",
")",
"output_stream",
".",
"write",
"(",
"read",
")",
"output_stream",
".",
"flush",
"(",
")",
"return",
"read",
"while",
"process",
".",
"poll",
"(",
")",
"is",
"None",
":",
"watch",
"=",
"process",
".",
"stdout",
".",
"fileno",
"(",
")",
",",
"process",
".",
"stderr",
".",
"fileno",
"(",
")",
"ready",
"=",
"select",
".",
"select",
"(",
"watch",
",",
"[",
"]",
",",
"[",
"]",
")",
"[",
"0",
"]",
"for",
"fd",
"in",
"ready",
":",
"if",
"fd",
"==",
"process",
".",
"stdout",
".",
"fileno",
"(",
")",
":",
"stdout",
"+=",
"read_stream",
"(",
"process",
".",
"stdout",
".",
"readline",
",",
"sys",
".",
"stdout",
")",
"if",
"fd",
"==",
"process",
".",
"stderr",
".",
"fileno",
"(",
")",
":",
"stderr",
"+=",
"read_stream",
"(",
"process",
".",
"stderr",
".",
"readline",
",",
"sys",
".",
"stderr",
")",
"stdout",
"+=",
"read_stream",
"(",
"process",
".",
"stdout",
".",
"read",
",",
"sys",
".",
"stdout",
")",
"stderr",
"+=",
"read_stream",
"(",
"process",
".",
"stderr",
".",
"read",
",",
"sys",
".",
"stderr",
")",
"return",
"stdout",
",",
"stderr"
]
| Run a command as if it were piped though tee.
Output generated by the command is displayed in real time to the terminal.
It is also captured in strings and returned once the process terminated.
This function is very useful for logging output from cluster runs. Naive
approaches like check_output() are vulnerable to crashes (i.e. if a job
exceeds its time limit) if they hold all output until the end. This
function echos any output as soon as it's generated, so that the cluster
logging system will still work. | [
"Run",
"a",
"command",
"as",
"if",
"it",
"were",
"piped",
"though",
"tee",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/process.py#L26-L66 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.save | def save(self, user, commit=True):
""" Persist user and emit event """
self.is_instance(user)
schema = UpdateSchema()
valid = schema.process(user)
if not valid:
return valid
db.session.add(user)
if commit:
db.session.commit()
events.user_save_event.send(user)
return user | python | def save(self, user, commit=True):
""" Persist user and emit event """
self.is_instance(user)
schema = UpdateSchema()
valid = schema.process(user)
if not valid:
return valid
db.session.add(user)
if commit:
db.session.commit()
events.user_save_event.send(user)
return user | [
"def",
"save",
"(",
"self",
",",
"user",
",",
"commit",
"=",
"True",
")",
":",
"self",
".",
"is_instance",
"(",
"user",
")",
"schema",
"=",
"UpdateSchema",
"(",
")",
"valid",
"=",
"schema",
".",
"process",
"(",
"user",
")",
"if",
"not",
"valid",
":",
"return",
"valid",
"db",
".",
"session",
".",
"add",
"(",
"user",
")",
"if",
"commit",
":",
"db",
".",
"session",
".",
"commit",
"(",
")",
"events",
".",
"user_save_event",
".",
"send",
"(",
"user",
")",
"return",
"user"
]
| Persist user and emit event | [
"Persist",
"user",
"and",
"emit",
"event"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L73-L87 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.login | def login(self, email=None, password=None, remember=False):
""" Authenticate user and emit event. """
from flask_login import login_user
user = self.first(email=email)
if user is None:
events.login_failed_nonexistent_event.send()
return False
# check for account being locked
if user.is_locked():
raise x.AccountLocked(locked_until=user.locked_until)
# check for email being confirmed
is_new = user.email and not user.email_new
if is_new and not user.email_confirmed and self.require_confirmation:
raise x.EmailNotConfirmed(email=user.email_secure)
verified = user.verify_password(password)
if not verified:
user.increment_failed_logins()
self.save(user)
events.login_failed_event.send(user)
return False
# login otherwise
login_user(user=user, remember=remember)
user.reset_login_counter()
self.save(user)
events.login_event.send(user)
# notify principal
app = current_app._get_current_object()
identity_changed.send(app, identity=Identity(user.id))
# and return
return True | python | def login(self, email=None, password=None, remember=False):
""" Authenticate user and emit event. """
from flask_login import login_user
user = self.first(email=email)
if user is None:
events.login_failed_nonexistent_event.send()
return False
# check for account being locked
if user.is_locked():
raise x.AccountLocked(locked_until=user.locked_until)
# check for email being confirmed
is_new = user.email and not user.email_new
if is_new and not user.email_confirmed and self.require_confirmation:
raise x.EmailNotConfirmed(email=user.email_secure)
verified = user.verify_password(password)
if not verified:
user.increment_failed_logins()
self.save(user)
events.login_failed_event.send(user)
return False
# login otherwise
login_user(user=user, remember=remember)
user.reset_login_counter()
self.save(user)
events.login_event.send(user)
# notify principal
app = current_app._get_current_object()
identity_changed.send(app, identity=Identity(user.id))
# and return
return True | [
"def",
"login",
"(",
"self",
",",
"email",
"=",
"None",
",",
"password",
"=",
"None",
",",
"remember",
"=",
"False",
")",
":",
"from",
"flask_login",
"import",
"login_user",
"user",
"=",
"self",
".",
"first",
"(",
"email",
"=",
"email",
")",
"if",
"user",
"is",
"None",
":",
"events",
".",
"login_failed_nonexistent_event",
".",
"send",
"(",
")",
"return",
"False",
"# check for account being locked",
"if",
"user",
".",
"is_locked",
"(",
")",
":",
"raise",
"x",
".",
"AccountLocked",
"(",
"locked_until",
"=",
"user",
".",
"locked_until",
")",
"# check for email being confirmed",
"is_new",
"=",
"user",
".",
"email",
"and",
"not",
"user",
".",
"email_new",
"if",
"is_new",
"and",
"not",
"user",
".",
"email_confirmed",
"and",
"self",
".",
"require_confirmation",
":",
"raise",
"x",
".",
"EmailNotConfirmed",
"(",
"email",
"=",
"user",
".",
"email_secure",
")",
"verified",
"=",
"user",
".",
"verify_password",
"(",
"password",
")",
"if",
"not",
"verified",
":",
"user",
".",
"increment_failed_logins",
"(",
")",
"self",
".",
"save",
"(",
"user",
")",
"events",
".",
"login_failed_event",
".",
"send",
"(",
"user",
")",
"return",
"False",
"# login otherwise",
"login_user",
"(",
"user",
"=",
"user",
",",
"remember",
"=",
"remember",
")",
"user",
".",
"reset_login_counter",
"(",
")",
"self",
".",
"save",
"(",
"user",
")",
"events",
".",
"login_event",
".",
"send",
"(",
"user",
")",
"# notify principal",
"app",
"=",
"current_app",
".",
"_get_current_object",
"(",
")",
"identity_changed",
".",
"send",
"(",
"app",
",",
"identity",
"=",
"Identity",
"(",
"user",
".",
"id",
")",
")",
"# and return",
"return",
"True"
]
| Authenticate user and emit event. | [
"Authenticate",
"user",
"and",
"emit",
"event",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L98-L133 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.force_login | def force_login(self, user):
""" Force login a user without credentials """
from flask_login import login_user
# check for account being locked
if user.is_locked():
raise x.AccountLocked(locked_until=user.locked_until)
# check for email being confirmed
is_new = user.email and not user.email_new
if is_new and not user.email_confirmed and self.require_confirmation:
raise x.EmailNotConfirmed(email=user.email_secure)
# login
login_user(user=user, remember=True)
user.reset_login_counter()
self.save(user)
# notify principal
app = current_app._get_current_object()
identity_changed.send(app, identity=Identity(user.id))
# and return
return True | python | def force_login(self, user):
""" Force login a user without credentials """
from flask_login import login_user
# check for account being locked
if user.is_locked():
raise x.AccountLocked(locked_until=user.locked_until)
# check for email being confirmed
is_new = user.email and not user.email_new
if is_new and not user.email_confirmed and self.require_confirmation:
raise x.EmailNotConfirmed(email=user.email_secure)
# login
login_user(user=user, remember=True)
user.reset_login_counter()
self.save(user)
# notify principal
app = current_app._get_current_object()
identity_changed.send(app, identity=Identity(user.id))
# and return
return True | [
"def",
"force_login",
"(",
"self",
",",
"user",
")",
":",
"from",
"flask_login",
"import",
"login_user",
"# check for account being locked",
"if",
"user",
".",
"is_locked",
"(",
")",
":",
"raise",
"x",
".",
"AccountLocked",
"(",
"locked_until",
"=",
"user",
".",
"locked_until",
")",
"# check for email being confirmed",
"is_new",
"=",
"user",
".",
"email",
"and",
"not",
"user",
".",
"email_new",
"if",
"is_new",
"and",
"not",
"user",
".",
"email_confirmed",
"and",
"self",
".",
"require_confirmation",
":",
"raise",
"x",
".",
"EmailNotConfirmed",
"(",
"email",
"=",
"user",
".",
"email_secure",
")",
"# login",
"login_user",
"(",
"user",
"=",
"user",
",",
"remember",
"=",
"True",
")",
"user",
".",
"reset_login_counter",
"(",
")",
"self",
".",
"save",
"(",
"user",
")",
"# notify principal",
"app",
"=",
"current_app",
".",
"_get_current_object",
"(",
")",
"identity_changed",
".",
"send",
"(",
"app",
",",
"identity",
"=",
"Identity",
"(",
"user",
".",
"id",
")",
")",
"# and return",
"return",
"True"
]
| Force login a user without credentials | [
"Force",
"login",
"a",
"user",
"without",
"credentials"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L135-L158 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.logout | def logout(self):
""" Logout user and emit event."""
from flask_login import logout_user, current_user
if not current_user.is_authenticated:
return True
# logout otherwise
user = current_user
events.logout_event.send(user)
logout_user()
# notify principal
app = current_app._get_current_object()
identity_changed.send(app, identity=AnonymousIdentity())
return True | python | def logout(self):
""" Logout user and emit event."""
from flask_login import logout_user, current_user
if not current_user.is_authenticated:
return True
# logout otherwise
user = current_user
events.logout_event.send(user)
logout_user()
# notify principal
app = current_app._get_current_object()
identity_changed.send(app, identity=AnonymousIdentity())
return True | [
"def",
"logout",
"(",
"self",
")",
":",
"from",
"flask_login",
"import",
"logout_user",
",",
"current_user",
"if",
"not",
"current_user",
".",
"is_authenticated",
":",
"return",
"True",
"# logout otherwise",
"user",
"=",
"current_user",
"events",
".",
"logout_event",
".",
"send",
"(",
"user",
")",
"logout_user",
"(",
")",
"# notify principal",
"app",
"=",
"current_app",
".",
"_get_current_object",
"(",
")",
"identity_changed",
".",
"send",
"(",
"app",
",",
"identity",
"=",
"AnonymousIdentity",
"(",
")",
")",
"return",
"True"
]
| Logout user and emit event. | [
"Logout",
"user",
"and",
"emit",
"event",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L160-L175 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.attempt_social_login | def attempt_social_login(self, provider, id):
""" Attempt social login and return boolean result """
if not provider or not id:
return False
params = dict()
params[provider.lower() + '_id'] = id
user = self.first(**params)
if not user:
return False
self.force_login(user)
return True | python | def attempt_social_login(self, provider, id):
""" Attempt social login and return boolean result """
if not provider or not id:
return False
params = dict()
params[provider.lower() + '_id'] = id
user = self.first(**params)
if not user:
return False
self.force_login(user)
return True | [
"def",
"attempt_social_login",
"(",
"self",
",",
"provider",
",",
"id",
")",
":",
"if",
"not",
"provider",
"or",
"not",
"id",
":",
"return",
"False",
"params",
"=",
"dict",
"(",
")",
"params",
"[",
"provider",
".",
"lower",
"(",
")",
"+",
"'_id'",
"]",
"=",
"id",
"user",
"=",
"self",
".",
"first",
"(",
"*",
"*",
"params",
")",
"if",
"not",
"user",
":",
"return",
"False",
"self",
".",
"force_login",
"(",
"user",
")",
"return",
"True"
]
| Attempt social login and return boolean result | [
"Attempt",
"social",
"login",
"and",
"return",
"boolean",
"result"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L177-L189 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.get_token | def get_token(self, user_id):
"""
Get user token
Checks if a custom token implementation is registered and uses that.
Otherwise falls back to default token implementation. Returns a string
token on success.
:param user_id: int, user id
:return: str
"""
if not self.jwt_implementation:
return self.default_token_implementation(user_id)
try:
implementation = import_string(self.jwt_implementation)
except ImportError:
msg = 'Failed to import custom JWT implementation. '
msg += 'Check that configured module exists [{}]'
raise x.ConfigurationException(msg.format(self.jwt_implementation))
# return custom token
return implementation(user_id) | python | def get_token(self, user_id):
"""
Get user token
Checks if a custom token implementation is registered and uses that.
Otherwise falls back to default token implementation. Returns a string
token on success.
:param user_id: int, user id
:return: str
"""
if not self.jwt_implementation:
return self.default_token_implementation(user_id)
try:
implementation = import_string(self.jwt_implementation)
except ImportError:
msg = 'Failed to import custom JWT implementation. '
msg += 'Check that configured module exists [{}]'
raise x.ConfigurationException(msg.format(self.jwt_implementation))
# return custom token
return implementation(user_id) | [
"def",
"get_token",
"(",
"self",
",",
"user_id",
")",
":",
"if",
"not",
"self",
".",
"jwt_implementation",
":",
"return",
"self",
".",
"default_token_implementation",
"(",
"user_id",
")",
"try",
":",
"implementation",
"=",
"import_string",
"(",
"self",
".",
"jwt_implementation",
")",
"except",
"ImportError",
":",
"msg",
"=",
"'Failed to import custom JWT implementation. '",
"msg",
"+=",
"'Check that configured module exists [{}]'",
"raise",
"x",
".",
"ConfigurationException",
"(",
"msg",
".",
"format",
"(",
"self",
".",
"jwt_implementation",
")",
")",
"# return custom token",
"return",
"implementation",
"(",
"user_id",
")"
]
| Get user token
Checks if a custom token implementation is registered and uses that.
Otherwise falls back to default token implementation. Returns a string
token on success.
:param user_id: int, user id
:return: str | [
"Get",
"user",
"token",
"Checks",
"if",
"a",
"custom",
"token",
"implementation",
"is",
"registered",
"and",
"uses",
"that",
".",
"Otherwise",
"falls",
"back",
"to",
"default",
"token",
"implementation",
".",
"Returns",
"a",
"string",
"token",
"on",
"success",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L220-L241 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.get_user_by_token | def get_user_by_token(self, token):
"""
Get user by token
Using for logging in. Check to see if a custom token user loader was
registered and uses that. Otherwise falls back to default loader
implementation. You should be fine with default implementation as long
as your token has user_id claim in it.
:param token: str, user token
:return: boiler.user.models.User
"""
if not self.jwt_loader_implementation:
return self.default_token_user_loader(token)
try:
implementation = import_string(self.jwt_loader_implementation)
except ImportError:
msg = 'Failed to import custom JWT user loader implementation. '
msg += 'Check that configured module exists [{}]'
raise x.ConfigurationException(
msg.format(self.jwt_loader_implementation)
)
# return user from custom loader
return implementation(token) | python | def get_user_by_token(self, token):
"""
Get user by token
Using for logging in. Check to see if a custom token user loader was
registered and uses that. Otherwise falls back to default loader
implementation. You should be fine with default implementation as long
as your token has user_id claim in it.
:param token: str, user token
:return: boiler.user.models.User
"""
if not self.jwt_loader_implementation:
return self.default_token_user_loader(token)
try:
implementation = import_string(self.jwt_loader_implementation)
except ImportError:
msg = 'Failed to import custom JWT user loader implementation. '
msg += 'Check that configured module exists [{}]'
raise x.ConfigurationException(
msg.format(self.jwt_loader_implementation)
)
# return user from custom loader
return implementation(token) | [
"def",
"get_user_by_token",
"(",
"self",
",",
"token",
")",
":",
"if",
"not",
"self",
".",
"jwt_loader_implementation",
":",
"return",
"self",
".",
"default_token_user_loader",
"(",
"token",
")",
"try",
":",
"implementation",
"=",
"import_string",
"(",
"self",
".",
"jwt_loader_implementation",
")",
"except",
"ImportError",
":",
"msg",
"=",
"'Failed to import custom JWT user loader implementation. '",
"msg",
"+=",
"'Check that configured module exists [{}]'",
"raise",
"x",
".",
"ConfigurationException",
"(",
"msg",
".",
"format",
"(",
"self",
".",
"jwt_loader_implementation",
")",
")",
"# return user from custom loader",
"return",
"implementation",
"(",
"token",
")"
]
| Get user by token
Using for logging in. Check to see if a custom token user loader was
registered and uses that. Otherwise falls back to default loader
implementation. You should be fine with default implementation as long
as your token has user_id claim in it.
:param token: str, user token
:return: boiler.user.models.User | [
"Get",
"user",
"by",
"token",
"Using",
"for",
"logging",
"in",
".",
"Check",
"to",
"see",
"if",
"a",
"custom",
"token",
"user",
"loader",
"was",
"registered",
"and",
"uses",
"that",
".",
"Otherwise",
"falls",
"back",
"to",
"default",
"loader",
"implementation",
".",
"You",
"should",
"be",
"fine",
"with",
"default",
"implementation",
"as",
"long",
"as",
"your",
"token",
"has",
"user_id",
"claim",
"in",
"it",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L243-L267 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.default_token_implementation | def default_token_implementation(self, user_id):
"""
Default JWT token implementation
This is used by default for generating user tokens if custom
implementation was not configured. The token will contain user_id and
expiration date. If you need more information added to the token,
register your custom implementation.
It will load a user to see if token is already on file. If it is, the
existing token will be checked for expiration and returned if valid.
Otherwise a new token will be generated and persisted. This can be used
to perform token revocation.
:param user_id: int, user id
:return: string
"""
user = self.get(user_id)
if not user:
msg = 'No user with such id [{}]'
raise x.JwtNoUser(msg.format(user_id))
# return token if exists and valid
if user._token:
try:
self.decode_token(user._token)
return user._token
except jwt.exceptions.ExpiredSignatureError:
pass
from_now = datetime.timedelta(seconds=self.jwt_lifetime)
expires = datetime.datetime.utcnow() + from_now
issued = datetime.datetime.utcnow()
not_before = datetime.datetime.utcnow()
data = dict(
exp=expires,
nbf=not_before,
iat=issued,
user_id=user_id
)
token = jwt.encode(data, self.jwt_secret, algorithm=self.jwt_algo)
string_token = token.decode('utf-8')
user._token = string_token
self.save(user)
return string_token | python | def default_token_implementation(self, user_id):
"""
Default JWT token implementation
This is used by default for generating user tokens if custom
implementation was not configured. The token will contain user_id and
expiration date. If you need more information added to the token,
register your custom implementation.
It will load a user to see if token is already on file. If it is, the
existing token will be checked for expiration and returned if valid.
Otherwise a new token will be generated and persisted. This can be used
to perform token revocation.
:param user_id: int, user id
:return: string
"""
user = self.get(user_id)
if not user:
msg = 'No user with such id [{}]'
raise x.JwtNoUser(msg.format(user_id))
# return token if exists and valid
if user._token:
try:
self.decode_token(user._token)
return user._token
except jwt.exceptions.ExpiredSignatureError:
pass
from_now = datetime.timedelta(seconds=self.jwt_lifetime)
expires = datetime.datetime.utcnow() + from_now
issued = datetime.datetime.utcnow()
not_before = datetime.datetime.utcnow()
data = dict(
exp=expires,
nbf=not_before,
iat=issued,
user_id=user_id
)
token = jwt.encode(data, self.jwt_secret, algorithm=self.jwt_algo)
string_token = token.decode('utf-8')
user._token = string_token
self.save(user)
return string_token | [
"def",
"default_token_implementation",
"(",
"self",
",",
"user_id",
")",
":",
"user",
"=",
"self",
".",
"get",
"(",
"user_id",
")",
"if",
"not",
"user",
":",
"msg",
"=",
"'No user with such id [{}]'",
"raise",
"x",
".",
"JwtNoUser",
"(",
"msg",
".",
"format",
"(",
"user_id",
")",
")",
"# return token if exists and valid",
"if",
"user",
".",
"_token",
":",
"try",
":",
"self",
".",
"decode_token",
"(",
"user",
".",
"_token",
")",
"return",
"user",
".",
"_token",
"except",
"jwt",
".",
"exceptions",
".",
"ExpiredSignatureError",
":",
"pass",
"from_now",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"jwt_lifetime",
")",
"expires",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"from_now",
"issued",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"not_before",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"data",
"=",
"dict",
"(",
"exp",
"=",
"expires",
",",
"nbf",
"=",
"not_before",
",",
"iat",
"=",
"issued",
",",
"user_id",
"=",
"user_id",
")",
"token",
"=",
"jwt",
".",
"encode",
"(",
"data",
",",
"self",
".",
"jwt_secret",
",",
"algorithm",
"=",
"self",
".",
"jwt_algo",
")",
"string_token",
"=",
"token",
".",
"decode",
"(",
"'utf-8'",
")",
"user",
".",
"_token",
"=",
"string_token",
"self",
".",
"save",
"(",
"user",
")",
"return",
"string_token"
]
| Default JWT token implementation
This is used by default for generating user tokens if custom
implementation was not configured. The token will contain user_id and
expiration date. If you need more information added to the token,
register your custom implementation.
It will load a user to see if token is already on file. If it is, the
existing token will be checked for expiration and returned if valid.
Otherwise a new token will be generated and persisted. This can be used
to perform token revocation.
:param user_id: int, user id
:return: string | [
"Default",
"JWT",
"token",
"implementation",
"This",
"is",
"used",
"by",
"default",
"for",
"generating",
"user",
"tokens",
"if",
"custom",
"implementation",
"was",
"not",
"configured",
".",
"The",
"token",
"will",
"contain",
"user_id",
"and",
"expiration",
"date",
".",
"If",
"you",
"need",
"more",
"information",
"added",
"to",
"the",
"token",
"register",
"your",
"custom",
"implementation",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L269-L312 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.default_token_user_loader | def default_token_user_loader(self, token):
"""
Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherwise throws an exception.
:param token: str, token string
:return: boiler.user.models.User
"""
try:
data = self.decode_token(token)
except jwt.exceptions.DecodeError as e:
raise x.JwtDecodeError(str(e))
except jwt.ExpiredSignatureError as e:
raise x.JwtExpired(str(e))
user = self.get(data['user_id'])
if not user:
msg = 'No user with such id [{}]'
raise x.JwtNoUser(msg.format(data['user_id']))
if user.is_locked():
msg = 'This account is locked'
raise x.AccountLocked(msg, locked_until=user.locked_until)
if self.require_confirmation and not user.email_confirmed:
msg = 'Please confirm your email address [{}]'
raise x.EmailNotConfirmed(
msg.format(user.email_secure),
email=user.email
)
# test token matches the one on file
if not token == user._token:
raise x.JwtTokenMismatch('The token does not match our records')
# return on success
return user | python | def default_token_user_loader(self, token):
"""
Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherwise throws an exception.
:param token: str, token string
:return: boiler.user.models.User
"""
try:
data = self.decode_token(token)
except jwt.exceptions.DecodeError as e:
raise x.JwtDecodeError(str(e))
except jwt.ExpiredSignatureError as e:
raise x.JwtExpired(str(e))
user = self.get(data['user_id'])
if not user:
msg = 'No user with such id [{}]'
raise x.JwtNoUser(msg.format(data['user_id']))
if user.is_locked():
msg = 'This account is locked'
raise x.AccountLocked(msg, locked_until=user.locked_until)
if self.require_confirmation and not user.email_confirmed:
msg = 'Please confirm your email address [{}]'
raise x.EmailNotConfirmed(
msg.format(user.email_secure),
email=user.email
)
# test token matches the one on file
if not token == user._token:
raise x.JwtTokenMismatch('The token does not match our records')
# return on success
return user | [
"def",
"default_token_user_loader",
"(",
"self",
",",
"token",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"decode_token",
"(",
"token",
")",
"except",
"jwt",
".",
"exceptions",
".",
"DecodeError",
"as",
"e",
":",
"raise",
"x",
".",
"JwtDecodeError",
"(",
"str",
"(",
"e",
")",
")",
"except",
"jwt",
".",
"ExpiredSignatureError",
"as",
"e",
":",
"raise",
"x",
".",
"JwtExpired",
"(",
"str",
"(",
"e",
")",
")",
"user",
"=",
"self",
".",
"get",
"(",
"data",
"[",
"'user_id'",
"]",
")",
"if",
"not",
"user",
":",
"msg",
"=",
"'No user with such id [{}]'",
"raise",
"x",
".",
"JwtNoUser",
"(",
"msg",
".",
"format",
"(",
"data",
"[",
"'user_id'",
"]",
")",
")",
"if",
"user",
".",
"is_locked",
"(",
")",
":",
"msg",
"=",
"'This account is locked'",
"raise",
"x",
".",
"AccountLocked",
"(",
"msg",
",",
"locked_until",
"=",
"user",
".",
"locked_until",
")",
"if",
"self",
".",
"require_confirmation",
"and",
"not",
"user",
".",
"email_confirmed",
":",
"msg",
"=",
"'Please confirm your email address [{}]'",
"raise",
"x",
".",
"EmailNotConfirmed",
"(",
"msg",
".",
"format",
"(",
"user",
".",
"email_secure",
")",
",",
"email",
"=",
"user",
".",
"email",
")",
"# test token matches the one on file",
"if",
"not",
"token",
"==",
"user",
".",
"_token",
":",
"raise",
"x",
".",
"JwtTokenMismatch",
"(",
"'The token does not match our records'",
")",
"# return on success",
"return",
"user"
]
| Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherwise throws an exception.
:param token: str, token string
:return: boiler.user.models.User | [
"Default",
"token",
"user",
"loader",
"Accepts",
"a",
"token",
"and",
"decodes",
"it",
"checking",
"signature",
"and",
"expiration",
".",
"Then",
"loads",
"user",
"by",
"id",
"from",
"the",
"token",
"to",
"see",
"if",
"account",
"is",
"not",
"locked",
".",
"If",
"all",
"is",
"good",
"returns",
"user",
"record",
"otherwise",
"throws",
"an",
"exception",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L314-L352 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.register | def register(self, user_data, base_confirm_url='', send_welcome=True):
"""
Register user
Accepts user data, validates it and performs registration. Will send
a welcome message with a confirmation link on success.
:param user_data: dic, populate user with data
:param send_welcome: bool, whether to send welcome or skip it (testing)
:param base_confirm_url: str, base confirmation link url
:return: boiler.user.models.User
"""
user = self.__model__(**user_data)
schema = RegisterSchema()
valid = schema.process(user)
if not valid:
return valid
db.session.add(user)
db.session.commit()
if not user.id:
return False
# send welcome message
if send_welcome:
self.send_welcome_message(user, base_confirm_url)
events.register_event.send(user)
return user | python | def register(self, user_data, base_confirm_url='', send_welcome=True):
"""
Register user
Accepts user data, validates it and performs registration. Will send
a welcome message with a confirmation link on success.
:param user_data: dic, populate user with data
:param send_welcome: bool, whether to send welcome or skip it (testing)
:param base_confirm_url: str, base confirmation link url
:return: boiler.user.models.User
"""
user = self.__model__(**user_data)
schema = RegisterSchema()
valid = schema.process(user)
if not valid:
return valid
db.session.add(user)
db.session.commit()
if not user.id:
return False
# send welcome message
if send_welcome:
self.send_welcome_message(user, base_confirm_url)
events.register_event.send(user)
return user | [
"def",
"register",
"(",
"self",
",",
"user_data",
",",
"base_confirm_url",
"=",
"''",
",",
"send_welcome",
"=",
"True",
")",
":",
"user",
"=",
"self",
".",
"__model__",
"(",
"*",
"*",
"user_data",
")",
"schema",
"=",
"RegisterSchema",
"(",
")",
"valid",
"=",
"schema",
".",
"process",
"(",
"user",
")",
"if",
"not",
"valid",
":",
"return",
"valid",
"db",
".",
"session",
".",
"add",
"(",
"user",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"if",
"not",
"user",
".",
"id",
":",
"return",
"False",
"# send welcome message",
"if",
"send_welcome",
":",
"self",
".",
"send_welcome_message",
"(",
"user",
",",
"base_confirm_url",
")",
"events",
".",
"register_event",
".",
"send",
"(",
"user",
")",
"return",
"user"
]
| Register user
Accepts user data, validates it and performs registration. Will send
a welcome message with a confirmation link on success.
:param user_data: dic, populate user with data
:param send_welcome: bool, whether to send welcome or skip it (testing)
:param base_confirm_url: str, base confirmation link url
:return: boiler.user.models.User | [
"Register",
"user",
"Accepts",
"user",
"data",
"validates",
"it",
"and",
"performs",
"registration",
".",
"Will",
"send",
"a",
"welcome",
"message",
"with",
"a",
"confirmation",
"link",
"on",
"success",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L358-L385 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.send_welcome_message | def send_welcome_message(self, user, base_url):
""" Send welcome mail with email confirmation link """
if not self.require_confirmation and not self.welcome_message:
return
# get subject
subject = ''
subjects = self.email_subjects
if self.require_confirmation:
subject = 'Welcome, please activate your account!'
if 'welcome_confirm' in subjects.keys():
subject = subjects['welcome_confirm']
if not self.require_confirmation:
subject = 'Welcome to our site!'
if 'welcome' in subjects.keys():
subject = subjects['welcome']
# prepare data
sender = current_app.config['MAIL_DEFAULT_SENDER']
recipient = user.email
link = '{url}/{link}/'.format(
url=base_url.rstrip('/'),
link=user.email_link
)
data = dict(link=link)
# render message
if self.require_confirmation:
html = render_template('user/mail/account-confirm.html', **data)
txt = render_template('user/mail/account-confirm.txt', **data)
else:
html = render_template('user/mail/welcome.html', **data)
txt = render_template('user/mail/welcome.txt', **data)
# and send
mail.send(Message(
subject=subject,
recipients=[recipient],
body=txt,
html=html,
sender=sender
)) | python | def send_welcome_message(self, user, base_url):
""" Send welcome mail with email confirmation link """
if not self.require_confirmation and not self.welcome_message:
return
# get subject
subject = ''
subjects = self.email_subjects
if self.require_confirmation:
subject = 'Welcome, please activate your account!'
if 'welcome_confirm' in subjects.keys():
subject = subjects['welcome_confirm']
if not self.require_confirmation:
subject = 'Welcome to our site!'
if 'welcome' in subjects.keys():
subject = subjects['welcome']
# prepare data
sender = current_app.config['MAIL_DEFAULT_SENDER']
recipient = user.email
link = '{url}/{link}/'.format(
url=base_url.rstrip('/'),
link=user.email_link
)
data = dict(link=link)
# render message
if self.require_confirmation:
html = render_template('user/mail/account-confirm.html', **data)
txt = render_template('user/mail/account-confirm.txt', **data)
else:
html = render_template('user/mail/welcome.html', **data)
txt = render_template('user/mail/welcome.txt', **data)
# and send
mail.send(Message(
subject=subject,
recipients=[recipient],
body=txt,
html=html,
sender=sender
)) | [
"def",
"send_welcome_message",
"(",
"self",
",",
"user",
",",
"base_url",
")",
":",
"if",
"not",
"self",
".",
"require_confirmation",
"and",
"not",
"self",
".",
"welcome_message",
":",
"return",
"# get subject",
"subject",
"=",
"''",
"subjects",
"=",
"self",
".",
"email_subjects",
"if",
"self",
".",
"require_confirmation",
":",
"subject",
"=",
"'Welcome, please activate your account!'",
"if",
"'welcome_confirm'",
"in",
"subjects",
".",
"keys",
"(",
")",
":",
"subject",
"=",
"subjects",
"[",
"'welcome_confirm'",
"]",
"if",
"not",
"self",
".",
"require_confirmation",
":",
"subject",
"=",
"'Welcome to our site!'",
"if",
"'welcome'",
"in",
"subjects",
".",
"keys",
"(",
")",
":",
"subject",
"=",
"subjects",
"[",
"'welcome'",
"]",
"# prepare data",
"sender",
"=",
"current_app",
".",
"config",
"[",
"'MAIL_DEFAULT_SENDER'",
"]",
"recipient",
"=",
"user",
".",
"email",
"link",
"=",
"'{url}/{link}/'",
".",
"format",
"(",
"url",
"=",
"base_url",
".",
"rstrip",
"(",
"'/'",
")",
",",
"link",
"=",
"user",
".",
"email_link",
")",
"data",
"=",
"dict",
"(",
"link",
"=",
"link",
")",
"# render message",
"if",
"self",
".",
"require_confirmation",
":",
"html",
"=",
"render_template",
"(",
"'user/mail/account-confirm.html'",
",",
"*",
"*",
"data",
")",
"txt",
"=",
"render_template",
"(",
"'user/mail/account-confirm.txt'",
",",
"*",
"*",
"data",
")",
"else",
":",
"html",
"=",
"render_template",
"(",
"'user/mail/welcome.html'",
",",
"*",
"*",
"data",
")",
"txt",
"=",
"render_template",
"(",
"'user/mail/welcome.txt'",
",",
"*",
"*",
"data",
")",
"# and send",
"mail",
".",
"send",
"(",
"Message",
"(",
"subject",
"=",
"subject",
",",
"recipients",
"=",
"[",
"recipient",
"]",
",",
"body",
"=",
"txt",
",",
"html",
"=",
"html",
",",
"sender",
"=",
"sender",
")",
")"
]
| Send welcome mail with email confirmation link | [
"Send",
"welcome",
"mail",
"with",
"email",
"confirmation",
"link"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L387-L428 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.resend_welcome_message | def resend_welcome_message(self, user, base_url):
""" Regenerate email link and resend welcome """
user.require_email_confirmation()
self.save(user)
self.send_welcome_message(user, base_url) | python | def resend_welcome_message(self, user, base_url):
""" Regenerate email link and resend welcome """
user.require_email_confirmation()
self.save(user)
self.send_welcome_message(user, base_url) | [
"def",
"resend_welcome_message",
"(",
"self",
",",
"user",
",",
"base_url",
")",
":",
"user",
".",
"require_email_confirmation",
"(",
")",
"self",
".",
"save",
"(",
"user",
")",
"self",
".",
"send_welcome_message",
"(",
"user",
",",
"base_url",
")"
]
| Regenerate email link and resend welcome | [
"Regenerate",
"email",
"link",
"and",
"resend",
"welcome"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L430-L434 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.confirm_email_with_link | def confirm_email_with_link(self, link):
"""
Confirm email with link
A universal method to confirm email. used for both initial
confirmation and when email is changed.
"""
user = self.first(email_link=link)
if not user:
return False
elif user and user.email_confirmed:
return True
elif user and user.email_link_expired():
raise x.EmailLinkExpired('Link expired, generate a new one')
# confirm otherwise
user.confirm_email()
db.session.add(user)
db.session.commit()
events.email_confirmed_event.send(user)
return user | python | def confirm_email_with_link(self, link):
"""
Confirm email with link
A universal method to confirm email. used for both initial
confirmation and when email is changed.
"""
user = self.first(email_link=link)
if not user:
return False
elif user and user.email_confirmed:
return True
elif user and user.email_link_expired():
raise x.EmailLinkExpired('Link expired, generate a new one')
# confirm otherwise
user.confirm_email()
db.session.add(user)
db.session.commit()
events.email_confirmed_event.send(user)
return user | [
"def",
"confirm_email_with_link",
"(",
"self",
",",
"link",
")",
":",
"user",
"=",
"self",
".",
"first",
"(",
"email_link",
"=",
"link",
")",
"if",
"not",
"user",
":",
"return",
"False",
"elif",
"user",
"and",
"user",
".",
"email_confirmed",
":",
"return",
"True",
"elif",
"user",
"and",
"user",
".",
"email_link_expired",
"(",
")",
":",
"raise",
"x",
".",
"EmailLinkExpired",
"(",
"'Link expired, generate a new one'",
")",
"# confirm otherwise",
"user",
".",
"confirm_email",
"(",
")",
"db",
".",
"session",
".",
"add",
"(",
"user",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"events",
".",
"email_confirmed_event",
".",
"send",
"(",
"user",
")",
"return",
"user"
]
| Confirm email with link
A universal method to confirm email. used for both initial
confirmation and when email is changed. | [
"Confirm",
"email",
"with",
"link",
"A",
"universal",
"method",
"to",
"confirm",
"email",
".",
"used",
"for",
"both",
"initial",
"confirmation",
"and",
"when",
"email",
"is",
"changed",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L440-L459 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.change_email | def change_email(
self, user, new_email, base_confirm_url='', send_message=True):
"""
Change email
Saves new email and sends confirmation before doing the switch.
Can optionally skip sending out message for testing purposes.
The email will be sent to the new email address to verify the user has
access to it. Important: please be sure to password-protect this.
:param user: boiler.user.models.User
:param new_email: str, new email
:param base_confirm_url: str, base url for confirmation links
:param send_message: bool, send email or skip
:return: None
"""
from boiler.user.models import UpdateSchema
schema = UpdateSchema()
user.email = new_email
valid = schema.validate(user)
if not valid:
return valid
db.session.add(user)
db.session.commit()
# send confirmation link
if send_message:
self.send_email_changed_message(user, base_confirm_url)
events.email_update_requested_event.send(user)
return user | python | def change_email(
self, user, new_email, base_confirm_url='', send_message=True):
"""
Change email
Saves new email and sends confirmation before doing the switch.
Can optionally skip sending out message for testing purposes.
The email will be sent to the new email address to verify the user has
access to it. Important: please be sure to password-protect this.
:param user: boiler.user.models.User
:param new_email: str, new email
:param base_confirm_url: str, base url for confirmation links
:param send_message: bool, send email or skip
:return: None
"""
from boiler.user.models import UpdateSchema
schema = UpdateSchema()
user.email = new_email
valid = schema.validate(user)
if not valid:
return valid
db.session.add(user)
db.session.commit()
# send confirmation link
if send_message:
self.send_email_changed_message(user, base_confirm_url)
events.email_update_requested_event.send(user)
return user | [
"def",
"change_email",
"(",
"self",
",",
"user",
",",
"new_email",
",",
"base_confirm_url",
"=",
"''",
",",
"send_message",
"=",
"True",
")",
":",
"from",
"boiler",
".",
"user",
".",
"models",
"import",
"UpdateSchema",
"schema",
"=",
"UpdateSchema",
"(",
")",
"user",
".",
"email",
"=",
"new_email",
"valid",
"=",
"schema",
".",
"validate",
"(",
"user",
")",
"if",
"not",
"valid",
":",
"return",
"valid",
"db",
".",
"session",
".",
"add",
"(",
"user",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"# send confirmation link",
"if",
"send_message",
":",
"self",
".",
"send_email_changed_message",
"(",
"user",
",",
"base_confirm_url",
")",
"events",
".",
"email_update_requested_event",
".",
"send",
"(",
"user",
")",
"return",
"user"
]
| Change email
Saves new email and sends confirmation before doing the switch.
Can optionally skip sending out message for testing purposes.
The email will be sent to the new email address to verify the user has
access to it. Important: please be sure to password-protect this.
:param user: boiler.user.models.User
:param new_email: str, new email
:param base_confirm_url: str, base url for confirmation links
:param send_message: bool, send email or skip
:return: None | [
"Change",
"email",
"Saves",
"new",
"email",
"and",
"sends",
"confirmation",
"before",
"doing",
"the",
"switch",
".",
"Can",
"optionally",
"skip",
"sending",
"out",
"message",
"for",
"testing",
"purposes",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L465-L496 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.resend_email_changed_message | def resend_email_changed_message(self, user, base_url):
""" Regenerate email confirmation link and resend message """
user.require_email_confirmation()
self.save(user)
self.send_email_changed_message(user, base_url) | python | def resend_email_changed_message(self, user, base_url):
""" Regenerate email confirmation link and resend message """
user.require_email_confirmation()
self.save(user)
self.send_email_changed_message(user, base_url) | [
"def",
"resend_email_changed_message",
"(",
"self",
",",
"user",
",",
"base_url",
")",
":",
"user",
".",
"require_email_confirmation",
"(",
")",
"self",
".",
"save",
"(",
"user",
")",
"self",
".",
"send_email_changed_message",
"(",
"user",
",",
"base_url",
")"
]
| Regenerate email confirmation link and resend message | [
"Regenerate",
"email",
"confirmation",
"link",
"and",
"resend",
"message"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L522-L526 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.request_password_reset | def request_password_reset(self, user, base_url):
""" Regenerate password link and send message """
user.generate_password_link()
db.session.add(user)
db.session.commit()
events.password_change_requested_event.send(user)
self.send_password_change_message(user, base_url) | python | def request_password_reset(self, user, base_url):
""" Regenerate password link and send message """
user.generate_password_link()
db.session.add(user)
db.session.commit()
events.password_change_requested_event.send(user)
self.send_password_change_message(user, base_url) | [
"def",
"request_password_reset",
"(",
"self",
",",
"user",
",",
"base_url",
")",
":",
"user",
".",
"generate_password_link",
"(",
")",
"db",
".",
"session",
".",
"add",
"(",
"user",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"events",
".",
"password_change_requested_event",
".",
"send",
"(",
"user",
")",
"self",
".",
"send_password_change_message",
"(",
"user",
",",
"base_url",
")"
]
| Regenerate password link and send message | [
"Regenerate",
"password",
"link",
"and",
"send",
"message"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L532-L538 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.change_password | def change_password(self, user, new_password):
""" Change user password and logout """
from boiler.user.models import UpdateSchema
from flask_login import logout_user
schema = UpdateSchema()
user.password = new_password
user.password_link=None
user.password_link_expires=None
valid = schema.validate(user)
if not valid:
return valid
db.session.add(user)
db.session.commit()
# logout if a web request
if has_request_context():
logout_user()
events.password_changed_event.send(user)
return user | python | def change_password(self, user, new_password):
""" Change user password and logout """
from boiler.user.models import UpdateSchema
from flask_login import logout_user
schema = UpdateSchema()
user.password = new_password
user.password_link=None
user.password_link_expires=None
valid = schema.validate(user)
if not valid:
return valid
db.session.add(user)
db.session.commit()
# logout if a web request
if has_request_context():
logout_user()
events.password_changed_event.send(user)
return user | [
"def",
"change_password",
"(",
"self",
",",
"user",
",",
"new_password",
")",
":",
"from",
"boiler",
".",
"user",
".",
"models",
"import",
"UpdateSchema",
"from",
"flask_login",
"import",
"logout_user",
"schema",
"=",
"UpdateSchema",
"(",
")",
"user",
".",
"password",
"=",
"new_password",
"user",
".",
"password_link",
"=",
"None",
"user",
".",
"password_link_expires",
"=",
"None",
"valid",
"=",
"schema",
".",
"validate",
"(",
"user",
")",
"if",
"not",
"valid",
":",
"return",
"valid",
"db",
".",
"session",
".",
"add",
"(",
"user",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"# logout if a web request",
"if",
"has_request_context",
"(",
")",
":",
"logout_user",
"(",
")",
"events",
".",
"password_changed_event",
".",
"send",
"(",
"user",
")",
"return",
"user"
]
| Change user password and logout | [
"Change",
"user",
"password",
"and",
"logout"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L540-L562 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.send_password_change_message | def send_password_change_message(self, user, base_url):
""" Send password change message"""
subject = 'Change your password here'
if 'password_change' in self.email_subjects.keys():
subject = self.email_subjects['password_change']
sender = current_app.config['MAIL_DEFAULT_SENDER']
recipient = user.email
link = '{url}/{link}/'.format(
url=base_url.rstrip('/'),
link=user.password_link
)
data = dict(link=link)
html = render_template('user/mail/password-change.html', **data)
txt = render_template('user/mail/password-change.txt', **data)
mail.send(Message(
subject=subject,
recipients=[recipient],
body=txt,
html=html,
sender=sender
)) | python | def send_password_change_message(self, user, base_url):
""" Send password change message"""
subject = 'Change your password here'
if 'password_change' in self.email_subjects.keys():
subject = self.email_subjects['password_change']
sender = current_app.config['MAIL_DEFAULT_SENDER']
recipient = user.email
link = '{url}/{link}/'.format(
url=base_url.rstrip('/'),
link=user.password_link
)
data = dict(link=link)
html = render_template('user/mail/password-change.html', **data)
txt = render_template('user/mail/password-change.txt', **data)
mail.send(Message(
subject=subject,
recipients=[recipient],
body=txt,
html=html,
sender=sender
)) | [
"def",
"send_password_change_message",
"(",
"self",
",",
"user",
",",
"base_url",
")",
":",
"subject",
"=",
"'Change your password here'",
"if",
"'password_change'",
"in",
"self",
".",
"email_subjects",
".",
"keys",
"(",
")",
":",
"subject",
"=",
"self",
".",
"email_subjects",
"[",
"'password_change'",
"]",
"sender",
"=",
"current_app",
".",
"config",
"[",
"'MAIL_DEFAULT_SENDER'",
"]",
"recipient",
"=",
"user",
".",
"email",
"link",
"=",
"'{url}/{link}/'",
".",
"format",
"(",
"url",
"=",
"base_url",
".",
"rstrip",
"(",
"'/'",
")",
",",
"link",
"=",
"user",
".",
"password_link",
")",
"data",
"=",
"dict",
"(",
"link",
"=",
"link",
")",
"html",
"=",
"render_template",
"(",
"'user/mail/password-change.html'",
",",
"*",
"*",
"data",
")",
"txt",
"=",
"render_template",
"(",
"'user/mail/password-change.txt'",
",",
"*",
"*",
"data",
")",
"mail",
".",
"send",
"(",
"Message",
"(",
"subject",
"=",
"subject",
",",
"recipients",
"=",
"[",
"recipient",
"]",
",",
"body",
"=",
"txt",
",",
"html",
"=",
"html",
",",
"sender",
"=",
"sender",
")",
")"
]
| Send password change message | [
"Send",
"password",
"change",
"message"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L564-L586 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.add_role_to_user | def add_role_to_user(self, user, role):
""" Adds a role to user """
user.add_role(role)
self.save(user)
events.user_got_role_event.send(user, role=role) | python | def add_role_to_user(self, user, role):
""" Adds a role to user """
user.add_role(role)
self.save(user)
events.user_got_role_event.send(user, role=role) | [
"def",
"add_role_to_user",
"(",
"self",
",",
"user",
",",
"role",
")",
":",
"user",
".",
"add_role",
"(",
"role",
")",
"self",
".",
"save",
"(",
"user",
")",
"events",
".",
"user_got_role_event",
".",
"send",
"(",
"user",
",",
"role",
"=",
"role",
")"
]
| Adds a role to user | [
"Adds",
"a",
"role",
"to",
"user"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L592-L596 | train |
projectshift/shift-boiler | boiler/user/user_service.py | UserService.remove_role_from_user | def remove_role_from_user(self, user, role):
""" Removes role from user """
user.remove_role(role)
self.save(user)
events.user_lost_role_event.send(user, role=role) | python | def remove_role_from_user(self, user, role):
""" Removes role from user """
user.remove_role(role)
self.save(user)
events.user_lost_role_event.send(user, role=role) | [
"def",
"remove_role_from_user",
"(",
"self",
",",
"user",
",",
"role",
")",
":",
"user",
".",
"remove_role",
"(",
"role",
")",
"self",
".",
"save",
"(",
"user",
")",
"events",
".",
"user_lost_role_event",
".",
"send",
"(",
"user",
",",
"role",
"=",
"role",
")"
]
| Removes role from user | [
"Removes",
"role",
"from",
"user"
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/user_service.py#L598-L602 | train |
berkeley-cocosci/Wallace | wallace/processes.py | random_walk | def random_walk(network):
"""Take a random walk from a source.
Start at a node randomly selected from those that receive input from a
source. At each step, transmit to a randomly-selected downstream node.
"""
latest = network.latest_transmission_recipient()
if (not network.transmissions() or latest is None):
sender = random.choice(network.nodes(type=Source))
else:
sender = latest
receiver = random.choice(sender.neighbors(direction="to", type=Agent))
sender.transmit(to_whom=receiver) | python | def random_walk(network):
"""Take a random walk from a source.
Start at a node randomly selected from those that receive input from a
source. At each step, transmit to a randomly-selected downstream node.
"""
latest = network.latest_transmission_recipient()
if (not network.transmissions() or latest is None):
sender = random.choice(network.nodes(type=Source))
else:
sender = latest
receiver = random.choice(sender.neighbors(direction="to", type=Agent))
sender.transmit(to_whom=receiver) | [
"def",
"random_walk",
"(",
"network",
")",
":",
"latest",
"=",
"network",
".",
"latest_transmission_recipient",
"(",
")",
"if",
"(",
"not",
"network",
".",
"transmissions",
"(",
")",
"or",
"latest",
"is",
"None",
")",
":",
"sender",
"=",
"random",
".",
"choice",
"(",
"network",
".",
"nodes",
"(",
"type",
"=",
"Source",
")",
")",
"else",
":",
"sender",
"=",
"latest",
"receiver",
"=",
"random",
".",
"choice",
"(",
"sender",
".",
"neighbors",
"(",
"direction",
"=",
"\"to\"",
",",
"type",
"=",
"Agent",
")",
")",
"sender",
".",
"transmit",
"(",
"to_whom",
"=",
"receiver",
")"
]
| Take a random walk from a source.
Start at a node randomly selected from those that receive input from a
source. At each step, transmit to a randomly-selected downstream node. | [
"Take",
"a",
"random",
"walk",
"from",
"a",
"source",
"."
]
| 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/processes.py#L7-L22 | train |
berkeley-cocosci/Wallace | wallace/processes.py | moran_cultural | def moran_cultural(network):
"""Generalized cultural Moran process.
At eachtime step, an individual is chosen to receive information from
another individual. Nobody dies, but perhaps their ideas do.
"""
if not network.transmissions(): # first step, replacer is a source
replacer = random.choice(network.nodes(type=Source))
replacer.transmit()
else:
replacer = random.choice(network.nodes(type=Agent))
replaced = random.choice(
replacer.neighbors(direction="to", type=Agent))
from operator import attrgetter
replacer.transmit(
what=max(replacer.infos(), key=attrgetter('creation_time')),
to_whom=replaced) | python | def moran_cultural(network):
"""Generalized cultural Moran process.
At eachtime step, an individual is chosen to receive information from
another individual. Nobody dies, but perhaps their ideas do.
"""
if not network.transmissions(): # first step, replacer is a source
replacer = random.choice(network.nodes(type=Source))
replacer.transmit()
else:
replacer = random.choice(network.nodes(type=Agent))
replaced = random.choice(
replacer.neighbors(direction="to", type=Agent))
from operator import attrgetter
replacer.transmit(
what=max(replacer.infos(), key=attrgetter('creation_time')),
to_whom=replaced) | [
"def",
"moran_cultural",
"(",
"network",
")",
":",
"if",
"not",
"network",
".",
"transmissions",
"(",
")",
":",
"# first step, replacer is a source",
"replacer",
"=",
"random",
".",
"choice",
"(",
"network",
".",
"nodes",
"(",
"type",
"=",
"Source",
")",
")",
"replacer",
".",
"transmit",
"(",
")",
"else",
":",
"replacer",
"=",
"random",
".",
"choice",
"(",
"network",
".",
"nodes",
"(",
"type",
"=",
"Agent",
")",
")",
"replaced",
"=",
"random",
".",
"choice",
"(",
"replacer",
".",
"neighbors",
"(",
"direction",
"=",
"\"to\"",
",",
"type",
"=",
"Agent",
")",
")",
"from",
"operator",
"import",
"attrgetter",
"replacer",
".",
"transmit",
"(",
"what",
"=",
"max",
"(",
"replacer",
".",
"infos",
"(",
")",
",",
"key",
"=",
"attrgetter",
"(",
"'creation_time'",
")",
")",
",",
"to_whom",
"=",
"replaced",
")"
]
| Generalized cultural Moran process.
At eachtime step, an individual is chosen to receive information from
another individual. Nobody dies, but perhaps their ideas do. | [
"Generalized",
"cultural",
"Moran",
"process",
"."
]
| 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/processes.py#L25-L43 | train |
berkeley-cocosci/Wallace | wallace/processes.py | moran_sexual | def moran_sexual(network):
"""The generalized sexual Moran process.
Ateach time step, and individual is chosen for replication and another
individual is chosen to die. The replication replaces the one who dies.
For this process to work you need to add a new agent before calling step.
"""
if not network.transmissions():
replacer = random.choice(network.nodes(type=Source))
replacer.transmit()
else:
from operator import attrgetter
agents = network.nodes(type=Agent)
baby = max(agents, key=attrgetter('creation_time'))
agents = [a for a in agents if a.id != baby.id]
replacer = random.choice(agents)
replaced = random.choice(
replacer.neighbors(direction="to", type=Agent))
# Give the baby the same outgoing connections as the replaced.
for node in replaced.neighbors(direction="to"):
baby.connect(direction="to", whom=node)
# Give the baby the same incoming connections as the replaced.
for node in replaced.neighbors(direction="from"):
node.connect(direction="to", whom=baby)
# Kill the replaced agent.
replaced.fail()
# Endow the baby with the ome of the replacer.
replacer.transmit(to_whom=baby) | python | def moran_sexual(network):
"""The generalized sexual Moran process.
Ateach time step, and individual is chosen for replication and another
individual is chosen to die. The replication replaces the one who dies.
For this process to work you need to add a new agent before calling step.
"""
if not network.transmissions():
replacer = random.choice(network.nodes(type=Source))
replacer.transmit()
else:
from operator import attrgetter
agents = network.nodes(type=Agent)
baby = max(agents, key=attrgetter('creation_time'))
agents = [a for a in agents if a.id != baby.id]
replacer = random.choice(agents)
replaced = random.choice(
replacer.neighbors(direction="to", type=Agent))
# Give the baby the same outgoing connections as the replaced.
for node in replaced.neighbors(direction="to"):
baby.connect(direction="to", whom=node)
# Give the baby the same incoming connections as the replaced.
for node in replaced.neighbors(direction="from"):
node.connect(direction="to", whom=baby)
# Kill the replaced agent.
replaced.fail()
# Endow the baby with the ome of the replacer.
replacer.transmit(to_whom=baby) | [
"def",
"moran_sexual",
"(",
"network",
")",
":",
"if",
"not",
"network",
".",
"transmissions",
"(",
")",
":",
"replacer",
"=",
"random",
".",
"choice",
"(",
"network",
".",
"nodes",
"(",
"type",
"=",
"Source",
")",
")",
"replacer",
".",
"transmit",
"(",
")",
"else",
":",
"from",
"operator",
"import",
"attrgetter",
"agents",
"=",
"network",
".",
"nodes",
"(",
"type",
"=",
"Agent",
")",
"baby",
"=",
"max",
"(",
"agents",
",",
"key",
"=",
"attrgetter",
"(",
"'creation_time'",
")",
")",
"agents",
"=",
"[",
"a",
"for",
"a",
"in",
"agents",
"if",
"a",
".",
"id",
"!=",
"baby",
".",
"id",
"]",
"replacer",
"=",
"random",
".",
"choice",
"(",
"agents",
")",
"replaced",
"=",
"random",
".",
"choice",
"(",
"replacer",
".",
"neighbors",
"(",
"direction",
"=",
"\"to\"",
",",
"type",
"=",
"Agent",
")",
")",
"# Give the baby the same outgoing connections as the replaced.",
"for",
"node",
"in",
"replaced",
".",
"neighbors",
"(",
"direction",
"=",
"\"to\"",
")",
":",
"baby",
".",
"connect",
"(",
"direction",
"=",
"\"to\"",
",",
"whom",
"=",
"node",
")",
"# Give the baby the same incoming connections as the replaced.",
"for",
"node",
"in",
"replaced",
".",
"neighbors",
"(",
"direction",
"=",
"\"from\"",
")",
":",
"node",
".",
"connect",
"(",
"direction",
"=",
"\"to\"",
",",
"whom",
"=",
"baby",
")",
"# Kill the replaced agent.",
"replaced",
".",
"fail",
"(",
")",
"# Endow the baby with the ome of the replacer.",
"replacer",
".",
"transmit",
"(",
"to_whom",
"=",
"baby",
")"
]
| The generalized sexual Moran process.
Ateach time step, and individual is chosen for replication and another
individual is chosen to die. The replication replaces the one who dies.
For this process to work you need to add a new agent before calling step. | [
"The",
"generalized",
"sexual",
"Moran",
"process",
"."
]
| 3650c0bc3b0804d0adb1d178c5eba9992babb1b0 | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/processes.py#L46-L77 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/transcoders.py | JSONTranscoder.dump_object | def dump_object(self, obj):
"""
Called to encode unrecognized object.
:param object obj: the object to encode
:return: the encoded object
:raises TypeError: when `obj` cannot be encoded
This method is passed as the ``default`` keyword parameter
to :func:`json.dumps`. It provides default representations for
a number of Python language/standard library types.
+----------------------------+---------------------------------------+
| Python Type | String Format |
+----------------------------+---------------------------------------+
| :class:`bytes`, | Base64 encoded string. |
| :class:`bytearray`, | |
| :class:`memoryview` | |
+----------------------------+---------------------------------------+
| :class:`datetime.datetime` | ISO8601 formatted timestamp in the |
| | extended format including separators, |
| | milliseconds, and the timezone |
| | designator. |
+----------------------------+---------------------------------------+
| :class:`uuid.UUID` | Same as ``str(value)`` |
+----------------------------+---------------------------------------+
"""
if isinstance(obj, uuid.UUID):
return str(obj)
if hasattr(obj, 'isoformat'):
return obj.isoformat()
if isinstance(obj, (bytes, bytearray, memoryview)):
return base64.b64encode(obj).decode('ASCII')
raise TypeError('{!r} is not JSON serializable'.format(obj)) | python | def dump_object(self, obj):
"""
Called to encode unrecognized object.
:param object obj: the object to encode
:return: the encoded object
:raises TypeError: when `obj` cannot be encoded
This method is passed as the ``default`` keyword parameter
to :func:`json.dumps`. It provides default representations for
a number of Python language/standard library types.
+----------------------------+---------------------------------------+
| Python Type | String Format |
+----------------------------+---------------------------------------+
| :class:`bytes`, | Base64 encoded string. |
| :class:`bytearray`, | |
| :class:`memoryview` | |
+----------------------------+---------------------------------------+
| :class:`datetime.datetime` | ISO8601 formatted timestamp in the |
| | extended format including separators, |
| | milliseconds, and the timezone |
| | designator. |
+----------------------------+---------------------------------------+
| :class:`uuid.UUID` | Same as ``str(value)`` |
+----------------------------+---------------------------------------+
"""
if isinstance(obj, uuid.UUID):
return str(obj)
if hasattr(obj, 'isoformat'):
return obj.isoformat()
if isinstance(obj, (bytes, bytearray, memoryview)):
return base64.b64encode(obj).decode('ASCII')
raise TypeError('{!r} is not JSON serializable'.format(obj)) | [
"def",
"dump_object",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"uuid",
".",
"UUID",
")",
":",
"return",
"str",
"(",
"obj",
")",
"if",
"hasattr",
"(",
"obj",
",",
"'isoformat'",
")",
":",
"return",
"obj",
".",
"isoformat",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"bytes",
",",
"bytearray",
",",
"memoryview",
")",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"obj",
")",
".",
"decode",
"(",
"'ASCII'",
")",
"raise",
"TypeError",
"(",
"'{!r} is not JSON serializable'",
".",
"format",
"(",
"obj",
")",
")"
]
| Called to encode unrecognized object.
:param object obj: the object to encode
:return: the encoded object
:raises TypeError: when `obj` cannot be encoded
This method is passed as the ``default`` keyword parameter
to :func:`json.dumps`. It provides default representations for
a number of Python language/standard library types.
+----------------------------+---------------------------------------+
| Python Type | String Format |
+----------------------------+---------------------------------------+
| :class:`bytes`, | Base64 encoded string. |
| :class:`bytearray`, | |
| :class:`memoryview` | |
+----------------------------+---------------------------------------+
| :class:`datetime.datetime` | ISO8601 formatted timestamp in the |
| | extended format including separators, |
| | milliseconds, and the timezone |
| | designator. |
+----------------------------+---------------------------------------+
| :class:`uuid.UUID` | Same as ``str(value)`` |
+----------------------------+---------------------------------------+ | [
"Called",
"to",
"encode",
"unrecognized",
"object",
"."
]
| c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/transcoders.py#L81-L115 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/transcoders.py | MsgPackTranscoder.normalize_datum | def normalize_datum(self, datum):
"""
Convert `datum` into something that umsgpack likes.
:param datum: something that we want to process with umsgpack
:return: a packable version of `datum`
:raises TypeError: if `datum` cannot be packed
This message is called by :meth:`.packb` to recursively normalize
an input value before passing it to :func:`umsgpack.packb`. Values
are normalized according to the following table.
+-------------------------------+-------------------------------+
| **Value** | **MsgPack Family** |
+-------------------------------+-------------------------------+
| :data:`None` | `nil byte`_ (0xC0) |
+-------------------------------+-------------------------------+
| :data:`True` | `true byte`_ (0xC3) |
+-------------------------------+-------------------------------+
| :data:`False` | `false byte`_ (0xC2) |
+-------------------------------+-------------------------------+
| :class:`int` | `integer family`_ |
+-------------------------------+-------------------------------+
| :class:`float` | `float family`_ |
+-------------------------------+-------------------------------+
| String | `str family`_ |
+-------------------------------+-------------------------------+
| :class:`bytes` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`bytearray` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`memoryview` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Sequence` | `array family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Set` | `array family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Mapping` | `map family`_ |
+-------------------------------+-------------------------------+
| :class:`uuid.UUID` | Converted to String |
+-------------------------------+-------------------------------+
.. _nil byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#formats-nil
.. _true byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bool-format-family
.. _false byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bool-format-family
.. _integer family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#int-format-family
.. _float family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#float-format-family
.. _str family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#str-format-family
.. _array family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#array-format-family
.. _map family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md
#mapping-format-family
.. _bin family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bin-format-family
"""
if datum is None:
return datum
if isinstance(datum, self.PACKABLE_TYPES):
return datum
if isinstance(datum, uuid.UUID):
datum = str(datum)
if isinstance(datum, bytearray):
datum = bytes(datum)
if isinstance(datum, memoryview):
datum = datum.tobytes()
if hasattr(datum, 'isoformat'):
datum = datum.isoformat()
if isinstance(datum, (bytes, str)):
return datum
if isinstance(datum, (collections.Sequence, collections.Set)):
return [self.normalize_datum(item) for item in datum]
if isinstance(datum, collections.Mapping):
out = {}
for k, v in datum.items():
out[k] = self.normalize_datum(v)
return out
raise TypeError(
'{} is not msgpackable'.format(datum.__class__.__name__)) | python | def normalize_datum(self, datum):
"""
Convert `datum` into something that umsgpack likes.
:param datum: something that we want to process with umsgpack
:return: a packable version of `datum`
:raises TypeError: if `datum` cannot be packed
This message is called by :meth:`.packb` to recursively normalize
an input value before passing it to :func:`umsgpack.packb`. Values
are normalized according to the following table.
+-------------------------------+-------------------------------+
| **Value** | **MsgPack Family** |
+-------------------------------+-------------------------------+
| :data:`None` | `nil byte`_ (0xC0) |
+-------------------------------+-------------------------------+
| :data:`True` | `true byte`_ (0xC3) |
+-------------------------------+-------------------------------+
| :data:`False` | `false byte`_ (0xC2) |
+-------------------------------+-------------------------------+
| :class:`int` | `integer family`_ |
+-------------------------------+-------------------------------+
| :class:`float` | `float family`_ |
+-------------------------------+-------------------------------+
| String | `str family`_ |
+-------------------------------+-------------------------------+
| :class:`bytes` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`bytearray` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`memoryview` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Sequence` | `array family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Set` | `array family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Mapping` | `map family`_ |
+-------------------------------+-------------------------------+
| :class:`uuid.UUID` | Converted to String |
+-------------------------------+-------------------------------+
.. _nil byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#formats-nil
.. _true byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bool-format-family
.. _false byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bool-format-family
.. _integer family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#int-format-family
.. _float family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#float-format-family
.. _str family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#str-format-family
.. _array family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#array-format-family
.. _map family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md
#mapping-format-family
.. _bin family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bin-format-family
"""
if datum is None:
return datum
if isinstance(datum, self.PACKABLE_TYPES):
return datum
if isinstance(datum, uuid.UUID):
datum = str(datum)
if isinstance(datum, bytearray):
datum = bytes(datum)
if isinstance(datum, memoryview):
datum = datum.tobytes()
if hasattr(datum, 'isoformat'):
datum = datum.isoformat()
if isinstance(datum, (bytes, str)):
return datum
if isinstance(datum, (collections.Sequence, collections.Set)):
return [self.normalize_datum(item) for item in datum]
if isinstance(datum, collections.Mapping):
out = {}
for k, v in datum.items():
out[k] = self.normalize_datum(v)
return out
raise TypeError(
'{} is not msgpackable'.format(datum.__class__.__name__)) | [
"def",
"normalize_datum",
"(",
"self",
",",
"datum",
")",
":",
"if",
"datum",
"is",
"None",
":",
"return",
"datum",
"if",
"isinstance",
"(",
"datum",
",",
"self",
".",
"PACKABLE_TYPES",
")",
":",
"return",
"datum",
"if",
"isinstance",
"(",
"datum",
",",
"uuid",
".",
"UUID",
")",
":",
"datum",
"=",
"str",
"(",
"datum",
")",
"if",
"isinstance",
"(",
"datum",
",",
"bytearray",
")",
":",
"datum",
"=",
"bytes",
"(",
"datum",
")",
"if",
"isinstance",
"(",
"datum",
",",
"memoryview",
")",
":",
"datum",
"=",
"datum",
".",
"tobytes",
"(",
")",
"if",
"hasattr",
"(",
"datum",
",",
"'isoformat'",
")",
":",
"datum",
"=",
"datum",
".",
"isoformat",
"(",
")",
"if",
"isinstance",
"(",
"datum",
",",
"(",
"bytes",
",",
"str",
")",
")",
":",
"return",
"datum",
"if",
"isinstance",
"(",
"datum",
",",
"(",
"collections",
".",
"Sequence",
",",
"collections",
".",
"Set",
")",
")",
":",
"return",
"[",
"self",
".",
"normalize_datum",
"(",
"item",
")",
"for",
"item",
"in",
"datum",
"]",
"if",
"isinstance",
"(",
"datum",
",",
"collections",
".",
"Mapping",
")",
":",
"out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"datum",
".",
"items",
"(",
")",
":",
"out",
"[",
"k",
"]",
"=",
"self",
".",
"normalize_datum",
"(",
"v",
")",
"return",
"out",
"raise",
"TypeError",
"(",
"'{} is not msgpackable'",
".",
"format",
"(",
"datum",
".",
"__class__",
".",
"__name__",
")",
")"
]
| Convert `datum` into something that umsgpack likes.
:param datum: something that we want to process with umsgpack
:return: a packable version of `datum`
:raises TypeError: if `datum` cannot be packed
This message is called by :meth:`.packb` to recursively normalize
an input value before passing it to :func:`umsgpack.packb`. Values
are normalized according to the following table.
+-------------------------------+-------------------------------+
| **Value** | **MsgPack Family** |
+-------------------------------+-------------------------------+
| :data:`None` | `nil byte`_ (0xC0) |
+-------------------------------+-------------------------------+
| :data:`True` | `true byte`_ (0xC3) |
+-------------------------------+-------------------------------+
| :data:`False` | `false byte`_ (0xC2) |
+-------------------------------+-------------------------------+
| :class:`int` | `integer family`_ |
+-------------------------------+-------------------------------+
| :class:`float` | `float family`_ |
+-------------------------------+-------------------------------+
| String | `str family`_ |
+-------------------------------+-------------------------------+
| :class:`bytes` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`bytearray` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`memoryview` | `bin family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Sequence` | `array family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Set` | `array family`_ |
+-------------------------------+-------------------------------+
| :class:`collections.Mapping` | `map family`_ |
+-------------------------------+-------------------------------+
| :class:`uuid.UUID` | Converted to String |
+-------------------------------+-------------------------------+
.. _nil byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#formats-nil
.. _true byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bool-format-family
.. _false byte: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bool-format-family
.. _integer family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#int-format-family
.. _float family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#float-format-family
.. _str family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#str-format-family
.. _array family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#array-format-family
.. _map family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md
#mapping-format-family
.. _bin family: https://github.com/msgpack/msgpack/blob/
0b8f5ac67cdd130f4d4d4fe6afb839b989fdb86a/spec.md#bin-format-family | [
"Convert",
"datum",
"into",
"something",
"that",
"umsgpack",
"likes",
"."
]
| c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/transcoders.py#L150-L244 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.