id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,700 | yvesalexandre/bandicoot | bandicoot/network.py | matrix_index | def matrix_index(user):
"""
Returns the keys associated with each axis of the matrices.
The first key is always the name of the current user, followed by the
sorted names of all the correspondants.
"""
other_keys = sorted([k for k in user.network.keys() if k != user.name])
return [user.name] + other_keys | python | def matrix_index(user):
other_keys = sorted([k for k in user.network.keys() if k != user.name])
return [user.name] + other_keys | [
"def",
"matrix_index",
"(",
"user",
")",
":",
"other_keys",
"=",
"sorted",
"(",
"[",
"k",
"for",
"k",
"in",
"user",
".",
"network",
".",
"keys",
"(",
")",
"if",
"k",
"!=",
"user",
".",
"name",
"]",
")",
"return",
"[",
"user",
".",
"name",
"]",
... | Returns the keys associated with each axis of the matrices.
The first key is always the name of the current user, followed by the
sorted names of all the correspondants. | [
"Returns",
"the",
"keys",
"associated",
"with",
"each",
"axis",
"of",
"the",
"matrices",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L94-L103 |
24,701 | yvesalexandre/bandicoot | bandicoot/network.py | matrix_directed_unweighted | def matrix_directed_unweighted(user):
"""
Returns a directed, unweighted matrix where an edge exists if there is at
least one call or text.
"""
matrix = _interaction_matrix(user, interaction=None)
for a in range(len(matrix)):
for b in range(len(matrix)):
if matrix[a][b] is not None and matrix[a][b] > 0:
matrix[a][b] = 1
return matrix | python | def matrix_directed_unweighted(user):
matrix = _interaction_matrix(user, interaction=None)
for a in range(len(matrix)):
for b in range(len(matrix)):
if matrix[a][b] is not None and matrix[a][b] > 0:
matrix[a][b] = 1
return matrix | [
"def",
"matrix_directed_unweighted",
"(",
"user",
")",
":",
"matrix",
"=",
"_interaction_matrix",
"(",
"user",
",",
"interaction",
"=",
"None",
")",
"for",
"a",
"in",
"range",
"(",
"len",
"(",
"matrix",
")",
")",
":",
"for",
"b",
"in",
"range",
"(",
"l... | Returns a directed, unweighted matrix where an edge exists if there is at
least one call or text. | [
"Returns",
"a",
"directed",
"unweighted",
"matrix",
"where",
"an",
"edge",
"exists",
"if",
"there",
"is",
"at",
"least",
"one",
"call",
"or",
"text",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L124-L135 |
24,702 | yvesalexandre/bandicoot | bandicoot/network.py | matrix_undirected_weighted | def matrix_undirected_weighted(user, interaction=None):
"""
Returns an undirected, weighted matrix for call, text and call duration
where an edge exists if the relationship is reciprocated.
"""
matrix = _interaction_matrix(user, interaction=interaction)
result = [[0 for _ in range(len(matrix))] for _ in range(len(matrix))]
for a in range(len(matrix)):
for b in range(len(matrix)):
if a != b and matrix[a][b] and matrix[b][a]:
result[a][b] = matrix[a][b] + matrix[b][a]
elif matrix[a][b] is None or matrix[b][a] is None:
result[a][b] = None
else:
result[a][b] = 0
return result | python | def matrix_undirected_weighted(user, interaction=None):
matrix = _interaction_matrix(user, interaction=interaction)
result = [[0 for _ in range(len(matrix))] for _ in range(len(matrix))]
for a in range(len(matrix)):
for b in range(len(matrix)):
if a != b and matrix[a][b] and matrix[b][a]:
result[a][b] = matrix[a][b] + matrix[b][a]
elif matrix[a][b] is None or matrix[b][a] is None:
result[a][b] = None
else:
result[a][b] = 0
return result | [
"def",
"matrix_undirected_weighted",
"(",
"user",
",",
"interaction",
"=",
"None",
")",
":",
"matrix",
"=",
"_interaction_matrix",
"(",
"user",
",",
"interaction",
"=",
"interaction",
")",
"result",
"=",
"[",
"[",
"0",
"for",
"_",
"in",
"range",
"(",
"len"... | Returns an undirected, weighted matrix for call, text and call duration
where an edge exists if the relationship is reciprocated. | [
"Returns",
"an",
"undirected",
"weighted",
"matrix",
"for",
"call",
"text",
"and",
"call",
"duration",
"where",
"an",
"edge",
"exists",
"if",
"the",
"relationship",
"is",
"reciprocated",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L138-L155 |
24,703 | yvesalexandre/bandicoot | bandicoot/network.py | matrix_undirected_unweighted | def matrix_undirected_unweighted(user):
"""
Returns an undirected, unweighted matrix where an edge exists if the
relationship is reciprocated.
"""
matrix = matrix_undirected_weighted(user, interaction=None)
for a, b in combinations(range(len(matrix)), 2):
if matrix[a][b] is None or matrix[b][a] is None:
continue
if matrix[a][b] > 0 and matrix[b][a] > 0:
matrix[a][b], matrix[b][a] = 1, 1
return matrix | python | def matrix_undirected_unweighted(user):
matrix = matrix_undirected_weighted(user, interaction=None)
for a, b in combinations(range(len(matrix)), 2):
if matrix[a][b] is None or matrix[b][a] is None:
continue
if matrix[a][b] > 0 and matrix[b][a] > 0:
matrix[a][b], matrix[b][a] = 1, 1
return matrix | [
"def",
"matrix_undirected_unweighted",
"(",
"user",
")",
":",
"matrix",
"=",
"matrix_undirected_weighted",
"(",
"user",
",",
"interaction",
"=",
"None",
")",
"for",
"a",
",",
"b",
"in",
"combinations",
"(",
"range",
"(",
"len",
"(",
"matrix",
")",
")",
","... | Returns an undirected, unweighted matrix where an edge exists if the
relationship is reciprocated. | [
"Returns",
"an",
"undirected",
"unweighted",
"matrix",
"where",
"an",
"edge",
"exists",
"if",
"the",
"relationship",
"is",
"reciprocated",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L158-L171 |
24,704 | yvesalexandre/bandicoot | bandicoot/network.py | clustering_coefficient_unweighted | def clustering_coefficient_unweighted(user):
"""
The clustering coefficient of the user in the unweighted, undirected ego
network.
It is defined by counting the number of closed triplets including
the current user:
.. math::
C = \\frac{2 * \\text{closed triplets}}{ \\text{degree} \, (\\text{degree - 1})}
where ``degree`` is the degree of the current user in the network.
"""
matrix = matrix_undirected_unweighted(user)
closed_triplets = 0
for a, b in combinations(range(len(matrix)), 2):
a_b, a_c, b_c = matrix[a][b], matrix[a][0], matrix[b][0]
if a_b is None or a_c is None or b_c is None:
continue
if a_b > 0 and a_c > 0 and b_c > 0:
closed_triplets += 1.
d_ego = sum(matrix[0])
return 2 * closed_triplets / (d_ego * (d_ego - 1)) if d_ego > 1 else 0 | python | def clustering_coefficient_unweighted(user):
matrix = matrix_undirected_unweighted(user)
closed_triplets = 0
for a, b in combinations(range(len(matrix)), 2):
a_b, a_c, b_c = matrix[a][b], matrix[a][0], matrix[b][0]
if a_b is None or a_c is None or b_c is None:
continue
if a_b > 0 and a_c > 0 and b_c > 0:
closed_triplets += 1.
d_ego = sum(matrix[0])
return 2 * closed_triplets / (d_ego * (d_ego - 1)) if d_ego > 1 else 0 | [
"def",
"clustering_coefficient_unweighted",
"(",
"user",
")",
":",
"matrix",
"=",
"matrix_undirected_unweighted",
"(",
"user",
")",
"closed_triplets",
"=",
"0",
"for",
"a",
",",
"b",
"in",
"combinations",
"(",
"range",
"(",
"len",
"(",
"matrix",
")",
")",
",... | The clustering coefficient of the user in the unweighted, undirected ego
network.
It is defined by counting the number of closed triplets including
the current user:
.. math::
C = \\frac{2 * \\text{closed triplets}}{ \\text{degree} \, (\\text{degree - 1})}
where ``degree`` is the degree of the current user in the network. | [
"The",
"clustering",
"coefficient",
"of",
"the",
"user",
"in",
"the",
"unweighted",
"undirected",
"ego",
"network",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L174-L200 |
24,705 | yvesalexandre/bandicoot | bandicoot/network.py | clustering_coefficient_weighted | def clustering_coefficient_weighted(user, interaction=None):
"""
The clustering coefficient of the user's weighted, undirected network.
It is defined the same way as :meth`~bandicoot.network.clustering_coefficient_unweighted`,
except that closed triplets are weighted by the number of interactions. For
each triplet (A, B, C), we compute the geometric mean of the number of
interactions, using the undirected weighted matrix:
.. math::
weight_{abc} = (m_{ab} \; m_{bc} \; m_{ac})^{1/3}
The weight is normalized, between 0 and 1, by the maximum value in the
matrix.
"""
matrix = matrix_undirected_weighted(user, interaction=interaction)
weights = [weight for g in matrix for weight in g if weight is not None]
if len(weights) == 0:
return None
max_weight = max(weights)
triplet_weight = 0
for a, b in combinations(range(len(matrix)), 2):
a_b, a_c, b_c = matrix[a][b], matrix[a][0], matrix[b][0]
if a_b is None or a_c is None or b_c is None:
continue
if a_b and a_c and b_c:
triplet_weight += (a_b * a_c * b_c) ** (1 / 3) / max_weight
d_ego = sum(1 for i in matrix[0] if i > 0)
return 2 * triplet_weight / (d_ego * (d_ego - 1)) if d_ego > 1 else 0 | python | def clustering_coefficient_weighted(user, interaction=None):
matrix = matrix_undirected_weighted(user, interaction=interaction)
weights = [weight for g in matrix for weight in g if weight is not None]
if len(weights) == 0:
return None
max_weight = max(weights)
triplet_weight = 0
for a, b in combinations(range(len(matrix)), 2):
a_b, a_c, b_c = matrix[a][b], matrix[a][0], matrix[b][0]
if a_b is None or a_c is None or b_c is None:
continue
if a_b and a_c and b_c:
triplet_weight += (a_b * a_c * b_c) ** (1 / 3) / max_weight
d_ego = sum(1 for i in matrix[0] if i > 0)
return 2 * triplet_weight / (d_ego * (d_ego - 1)) if d_ego > 1 else 0 | [
"def",
"clustering_coefficient_weighted",
"(",
"user",
",",
"interaction",
"=",
"None",
")",
":",
"matrix",
"=",
"matrix_undirected_weighted",
"(",
"user",
",",
"interaction",
"=",
"interaction",
")",
"weights",
"=",
"[",
"weight",
"for",
"g",
"in",
"matrix",
... | The clustering coefficient of the user's weighted, undirected network.
It is defined the same way as :meth`~bandicoot.network.clustering_coefficient_unweighted`,
except that closed triplets are weighted by the number of interactions. For
each triplet (A, B, C), we compute the geometric mean of the number of
interactions, using the undirected weighted matrix:
.. math::
weight_{abc} = (m_{ab} \; m_{bc} \; m_{ac})^{1/3}
The weight is normalized, between 0 and 1, by the maximum value in the
matrix. | [
"The",
"clustering",
"coefficient",
"of",
"the",
"user",
"s",
"weighted",
"undirected",
"network",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L203-L236 |
24,706 | yvesalexandre/bandicoot | bandicoot/network.py | assortativity_indicators | def assortativity_indicators(user):
"""
Computes the assortativity of indicators.
This indicator measures the similarity of the current user with his
correspondants, for all bandicoot indicators. For each one, it calculates
the variance of the current user's value with the values for all his
correspondants:
.. math::
\\text{assortativity}(J) = \\frac{1}{n} \\sum_i^n (J_{\\text{user}} - J_{\\text{i}})^2
for the indicator :math:`J`, and all the :math:`n` correspondents.
"""
matrix = matrix_undirected_unweighted(user)
count_indicator = defaultdict(int)
total_indicator = defaultdict(int)
# Use all indicator except reporting variables and attributes
ego_indics = all(user, flatten=True)
ego_indics = {a: value for a, value in ego_indics.items()
if a != "name" and a[:11] != "reporting__" and
a[:10] != "attributes"}
for i, u_name in enumerate(matrix_index(user)):
correspondent = user.network.get(u_name, None)
# Non reciprocated edge
if correspondent is None or u_name == user.name or matrix[0][i] == 0:
continue
neighbor_indics = all(correspondent, flatten=True)
for a in ego_indics:
if ego_indics[a] is not None and neighbor_indics[a] is not None:
total_indicator[a] += 1
count_indicator[a] += (ego_indics[a] - neighbor_indics[a]) ** 2
assortativity = {}
for i in count_indicator:
assortativity[i] = count_indicator[i] / total_indicator[i]
return assortativity | python | def assortativity_indicators(user):
matrix = matrix_undirected_unweighted(user)
count_indicator = defaultdict(int)
total_indicator = defaultdict(int)
# Use all indicator except reporting variables and attributes
ego_indics = all(user, flatten=True)
ego_indics = {a: value for a, value in ego_indics.items()
if a != "name" and a[:11] != "reporting__" and
a[:10] != "attributes"}
for i, u_name in enumerate(matrix_index(user)):
correspondent = user.network.get(u_name, None)
# Non reciprocated edge
if correspondent is None or u_name == user.name or matrix[0][i] == 0:
continue
neighbor_indics = all(correspondent, flatten=True)
for a in ego_indics:
if ego_indics[a] is not None and neighbor_indics[a] is not None:
total_indicator[a] += 1
count_indicator[a] += (ego_indics[a] - neighbor_indics[a]) ** 2
assortativity = {}
for i in count_indicator:
assortativity[i] = count_indicator[i] / total_indicator[i]
return assortativity | [
"def",
"assortativity_indicators",
"(",
"user",
")",
":",
"matrix",
"=",
"matrix_undirected_unweighted",
"(",
"user",
")",
"count_indicator",
"=",
"defaultdict",
"(",
"int",
")",
"total_indicator",
"=",
"defaultdict",
"(",
"int",
")",
"# Use all indicator except repor... | Computes the assortativity of indicators.
This indicator measures the similarity of the current user with his
correspondants, for all bandicoot indicators. For each one, it calculates
the variance of the current user's value with the values for all his
correspondants:
.. math::
\\text{assortativity}(J) = \\frac{1}{n} \\sum_i^n (J_{\\text{user}} - J_{\\text{i}})^2
for the indicator :math:`J`, and all the :math:`n` correspondents. | [
"Computes",
"the",
"assortativity",
"of",
"indicators",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L239-L283 |
24,707 | yvesalexandre/bandicoot | bandicoot/network.py | assortativity_attributes | def assortativity_attributes(user):
"""
Computes the assortativity of the nominal attributes.
This indicator measures the homophily of the current user with his
correspondants, for each attributes. It returns a value between 0
(no assortativity) and 1 (all the contacts share the same value):
the percentage of contacts sharing the same value.
"""
matrix = matrix_undirected_unweighted(user)
neighbors = [k for k in user.network.keys() if k != user.name]
neighbors_attrbs = {}
for i, u_name in enumerate(matrix_index(user)):
correspondent = user.network.get(u_name, None)
if correspondent is None or u_name == user.name or matrix[0][i] == 0:
continue
if correspondent.has_attributes:
neighbors_attrbs[correspondent.name] = correspondent.attributes
assortativity = {}
for a in user.attributes:
total = sum(1 for n in neighbors if n in neighbors_attrbs and user.attributes[a] == neighbors_attrbs[n][a])
den = sum(1 for n in neighbors if n in neighbors_attrbs)
assortativity[a] = total / den if den != 0 else None
return assortativity | python | def assortativity_attributes(user):
matrix = matrix_undirected_unweighted(user)
neighbors = [k for k in user.network.keys() if k != user.name]
neighbors_attrbs = {}
for i, u_name in enumerate(matrix_index(user)):
correspondent = user.network.get(u_name, None)
if correspondent is None or u_name == user.name or matrix[0][i] == 0:
continue
if correspondent.has_attributes:
neighbors_attrbs[correspondent.name] = correspondent.attributes
assortativity = {}
for a in user.attributes:
total = sum(1 for n in neighbors if n in neighbors_attrbs and user.attributes[a] == neighbors_attrbs[n][a])
den = sum(1 for n in neighbors if n in neighbors_attrbs)
assortativity[a] = total / den if den != 0 else None
return assortativity | [
"def",
"assortativity_attributes",
"(",
"user",
")",
":",
"matrix",
"=",
"matrix_undirected_unweighted",
"(",
"user",
")",
"neighbors",
"=",
"[",
"k",
"for",
"k",
"in",
"user",
".",
"network",
".",
"keys",
"(",
")",
"if",
"k",
"!=",
"user",
".",
"name",
... | Computes the assortativity of the nominal attributes.
This indicator measures the homophily of the current user with his
correspondants, for each attributes. It returns a value between 0
(no assortativity) and 1 (all the contacts share the same value):
the percentage of contacts sharing the same value. | [
"Computes",
"the",
"assortativity",
"of",
"the",
"nominal",
"attributes",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L286-L314 |
24,708 | yvesalexandre/bandicoot | bandicoot/network.py | network_sampling | def network_sampling(n, filename, directory=None, snowball=False, user=None):
"""
Selects a few users and exports a CSV of indicators for them.
TODO: Returns the network/graph between the selected users.
Parameters
----------
n : int
Number of users to select.
filename : string
File to export to.
directory: string
Directory to select users from if using the default random selection.
snowball: starts from a specified user, iterates over neighbors, and does a
BFS until n neighbors are reached
"""
if snowball:
if user is None:
raise ValueError("Must specify a starting user from whom to initiate the snowball")
else:
users, agenda = [user], [user]
while len(agenda) > 0:
parent = agenda.pop()
dealphebetized_network = sorted(parent.network.items(), key=lambda k: random.random())
for neighbor in dealphebetized_network:
if neighbor[1] not in users and neighbor[1] is not None and len(users) < n:
users.append(neighbor[1])
if neighbor[1].network:
agenda.push(neighbor[1])
else:
files = [x for x in os.listdir(directory) if os.path.isfile(os.path.join(directory, x))]
shuffled_files = sorted(files, key=lambda k: random.random())
user_names = shuffled_files[:n]
users = [bc.read_csv(u[:-4], directory) for u in user_names]
if len(users) < n:
raise ValueError("Specified more users than records that exist, only {} records available".format(len(users)))
bc.to_csv([bc.utils.all(u) for u in users], filename) | python | def network_sampling(n, filename, directory=None, snowball=False, user=None):
if snowball:
if user is None:
raise ValueError("Must specify a starting user from whom to initiate the snowball")
else:
users, agenda = [user], [user]
while len(agenda) > 0:
parent = agenda.pop()
dealphebetized_network = sorted(parent.network.items(), key=lambda k: random.random())
for neighbor in dealphebetized_network:
if neighbor[1] not in users and neighbor[1] is not None and len(users) < n:
users.append(neighbor[1])
if neighbor[1].network:
agenda.push(neighbor[1])
else:
files = [x for x in os.listdir(directory) if os.path.isfile(os.path.join(directory, x))]
shuffled_files = sorted(files, key=lambda k: random.random())
user_names = shuffled_files[:n]
users = [bc.read_csv(u[:-4], directory) for u in user_names]
if len(users) < n:
raise ValueError("Specified more users than records that exist, only {} records available".format(len(users)))
bc.to_csv([bc.utils.all(u) for u in users], filename) | [
"def",
"network_sampling",
"(",
"n",
",",
"filename",
",",
"directory",
"=",
"None",
",",
"snowball",
"=",
"False",
",",
"user",
"=",
"None",
")",
":",
"if",
"snowball",
":",
"if",
"user",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Must specify a ... | Selects a few users and exports a CSV of indicators for them.
TODO: Returns the network/graph between the selected users.
Parameters
----------
n : int
Number of users to select.
filename : string
File to export to.
directory: string
Directory to select users from if using the default random selection.
snowball: starts from a specified user, iterates over neighbors, and does a
BFS until n neighbors are reached | [
"Selects",
"a",
"few",
"users",
"and",
"exports",
"a",
"CSV",
"of",
"indicators",
"for",
"them",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L317-L355 |
24,709 | yvesalexandre/bandicoot | bandicoot/visualization.py | export | def export(user, directory=None, warnings=True):
"""
Build a temporary directory with the visualization.
Returns the local path where files have been written.
Examples
--------
>>> bandicoot.visualization.export(U)
Successfully exported the visualization to /tmp/tmpsIyncS
"""
# Get dashboard directory
current_file = os.path.realpath(__file__)
current_path = os.path.dirname(current_file)
dashboard_path = os.path.join(current_path, 'dashboard_src')
# Create a temporary directory if needed and copy all files
if directory:
dirpath = directory
else:
dirpath = tempfile.mkdtemp()
# Copy all files except source code
copy_tree(dashboard_path + '/public', dirpath, update=1)
# Export indicators
data = user_data(user)
bc.io.to_json(data, dirpath + '/data/bc_export.json', warnings=False)
if warnings:
print("Successfully exported the visualization to %s" % dirpath)
return dirpath | python | def export(user, directory=None, warnings=True):
# Get dashboard directory
current_file = os.path.realpath(__file__)
current_path = os.path.dirname(current_file)
dashboard_path = os.path.join(current_path, 'dashboard_src')
# Create a temporary directory if needed and copy all files
if directory:
dirpath = directory
else:
dirpath = tempfile.mkdtemp()
# Copy all files except source code
copy_tree(dashboard_path + '/public', dirpath, update=1)
# Export indicators
data = user_data(user)
bc.io.to_json(data, dirpath + '/data/bc_export.json', warnings=False)
if warnings:
print("Successfully exported the visualization to %s" % dirpath)
return dirpath | [
"def",
"export",
"(",
"user",
",",
"directory",
"=",
"None",
",",
"warnings",
"=",
"True",
")",
":",
"# Get dashboard directory",
"current_file",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
"current_path",
"=",
"os",
".",
"path",
".",
... | Build a temporary directory with the visualization.
Returns the local path where files have been written.
Examples
--------
>>> bandicoot.visualization.export(U)
Successfully exported the visualization to /tmp/tmpsIyncS | [
"Build",
"a",
"temporary",
"directory",
"with",
"the",
"visualization",
".",
"Returns",
"the",
"local",
"path",
"where",
"files",
"have",
"been",
"written",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/visualization.py#L118-L151 |
24,710 | yvesalexandre/bandicoot | bandicoot/visualization.py | run | def run(user, port=4242):
"""
Build a temporary directory with a visualization and serve it over HTTP.
Examples
--------
>>> bandicoot.visualization.run(U)
Successfully exported the visualization to /tmp/tmpsIyncS
Serving bandicoot visualization at http://0.0.0.0:4242
"""
owd = os.getcwd()
dir = export(user)
os.chdir(dir)
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
try:
httpd = SocketServer.TCPServer(("", port), Handler)
print("Serving bandicoot visualization at http://0.0.0.0:%i" % port)
httpd.serve_forever()
except KeyboardInterrupt:
print("^C received, shutting down the web server")
httpd.server_close()
finally:
os.chdir(owd) | python | def run(user, port=4242):
owd = os.getcwd()
dir = export(user)
os.chdir(dir)
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
try:
httpd = SocketServer.TCPServer(("", port), Handler)
print("Serving bandicoot visualization at http://0.0.0.0:%i" % port)
httpd.serve_forever()
except KeyboardInterrupt:
print("^C received, shutting down the web server")
httpd.server_close()
finally:
os.chdir(owd) | [
"def",
"run",
"(",
"user",
",",
"port",
"=",
"4242",
")",
":",
"owd",
"=",
"os",
".",
"getcwd",
"(",
")",
"dir",
"=",
"export",
"(",
"user",
")",
"os",
".",
"chdir",
"(",
"dir",
")",
"Handler",
"=",
"SimpleHTTPServer",
".",
"SimpleHTTPRequestHandler"... | Build a temporary directory with a visualization and serve it over HTTP.
Examples
--------
>>> bandicoot.visualization.run(U)
Successfully exported the visualization to /tmp/tmpsIyncS
Serving bandicoot visualization at http://0.0.0.0:4242 | [
"Build",
"a",
"temporary",
"directory",
"with",
"a",
"visualization",
"and",
"serve",
"it",
"over",
"HTTP",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/visualization.py#L154-L178 |
24,711 | yvesalexandre/bandicoot | bandicoot/io.py | to_csv | def to_csv(objects, filename, digits=5, warnings=True):
"""
Export the flatten indicators of one or several users to CSV.
Parameters
----------
objects : list
List of objects to be exported.
filename : string
File to export to.
digits : int
Precision of floats.
Examples
--------
This function can be used to export the results of
:meth`bandicoot.utils.all`.
>>> U_1 = bc.User()
>>> U_2 = bc.User()
>>> bc.to_csv([bc.utils.all(U_1), bc.utils.all(U_2)], 'results_1_2.csv')
If you only have one object, you can simply pass it as argument:
>>> bc.to_csv(bc.utils.all(U_1), 'results_1.csv')
"""
if not isinstance(objects, list):
objects = [objects]
data = [flatten(obj) for obj in objects]
all_keys = [d for datum in data for d in datum.keys()]
field_names = sorted(set(all_keys), key=lambda x: all_keys.index(x))
with open(filename, 'w') as f:
w = csv.writer(f)
w.writerow(field_names)
def make_repr(item):
if item is None:
return None
elif isinstance(item, float):
return repr(round(item, digits))
else:
return str(item)
for row in data:
row = dict((k, make_repr(v)) for k, v in row.items())
w.writerow([make_repr(row.get(k, None)) for k in field_names])
if warnings:
print("Successfully exported {} object(s) to {}".format(len(objects),
filename)) | python | def to_csv(objects, filename, digits=5, warnings=True):
if not isinstance(objects, list):
objects = [objects]
data = [flatten(obj) for obj in objects]
all_keys = [d for datum in data for d in datum.keys()]
field_names = sorted(set(all_keys), key=lambda x: all_keys.index(x))
with open(filename, 'w') as f:
w = csv.writer(f)
w.writerow(field_names)
def make_repr(item):
if item is None:
return None
elif isinstance(item, float):
return repr(round(item, digits))
else:
return str(item)
for row in data:
row = dict((k, make_repr(v)) for k, v in row.items())
w.writerow([make_repr(row.get(k, None)) for k in field_names])
if warnings:
print("Successfully exported {} object(s) to {}".format(len(objects),
filename)) | [
"def",
"to_csv",
"(",
"objects",
",",
"filename",
",",
"digits",
"=",
"5",
",",
"warnings",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"objects",
",",
"list",
")",
":",
"objects",
"=",
"[",
"objects",
"]",
"data",
"=",
"[",
"flatten",
"... | Export the flatten indicators of one or several users to CSV.
Parameters
----------
objects : list
List of objects to be exported.
filename : string
File to export to.
digits : int
Precision of floats.
Examples
--------
This function can be used to export the results of
:meth`bandicoot.utils.all`.
>>> U_1 = bc.User()
>>> U_2 = bc.User()
>>> bc.to_csv([bc.utils.all(U_1), bc.utils.all(U_2)], 'results_1_2.csv')
If you only have one object, you can simply pass it as argument:
>>> bc.to_csv(bc.utils.all(U_1), 'results_1.csv') | [
"Export",
"the",
"flatten",
"indicators",
"of",
"one",
"or",
"several",
"users",
"to",
"CSV",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/io.py#L46-L96 |
24,712 | yvesalexandre/bandicoot | bandicoot/io.py | to_json | def to_json(objects, filename, warnings=True):
"""
Export the indicators of one or several users to JSON.
Parameters
----------
objects : list
List of objects to be exported.
filename : string
File to export to.
Examples
--------
This function can be use to export the results of
:meth`bandicoot.utils.all`.
>>> U_1 = bc.User()
>>> U_2 = bc.User()
>>> bc.to_json([bc.utils.all(U_1), bc.utils.all(U_2)], 'results_1_2.json')
If you only have one object, you can simply pass it as argument:
>>> bc.to_json(bc.utils.all(U_1), 'results_1.json')
"""
if not isinstance(objects, list):
objects = [objects]
obj_dict = OrderedDict([(obj['name'], obj) for obj in objects])
with open(filename, 'w') as f:
f.write(dumps(obj_dict, indent=4, separators=(',', ': ')))
if warnings:
print("Successfully exported {} object(s) to {}".format(len(objects),
filename)) | python | def to_json(objects, filename, warnings=True):
if not isinstance(objects, list):
objects = [objects]
obj_dict = OrderedDict([(obj['name'], obj) for obj in objects])
with open(filename, 'w') as f:
f.write(dumps(obj_dict, indent=4, separators=(',', ': ')))
if warnings:
print("Successfully exported {} object(s) to {}".format(len(objects),
filename)) | [
"def",
"to_json",
"(",
"objects",
",",
"filename",
",",
"warnings",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"objects",
",",
"list",
")",
":",
"objects",
"=",
"[",
"objects",
"]",
"obj_dict",
"=",
"OrderedDict",
"(",
"[",
"(",
"obj",
"[... | Export the indicators of one or several users to JSON.
Parameters
----------
objects : list
List of objects to be exported.
filename : string
File to export to.
Examples
--------
This function can be use to export the results of
:meth`bandicoot.utils.all`.
>>> U_1 = bc.User()
>>> U_2 = bc.User()
>>> bc.to_json([bc.utils.all(U_1), bc.utils.all(U_2)], 'results_1_2.json')
If you only have one object, you can simply pass it as argument:
>>> bc.to_json(bc.utils.all(U_1), 'results_1.json') | [
"Export",
"the",
"indicators",
"of",
"one",
"or",
"several",
"users",
"to",
"JSON",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/io.py#L99-L132 |
24,713 | yvesalexandre/bandicoot | bandicoot/io.py | _parse_record | def _parse_record(data, duration_format='seconds'):
"""
Parse a raw data dictionary and return a Record object.
"""
def _map_duration(s):
if s == '':
return None
elif duration_format.lower() == 'seconds':
return int(s)
else:
t = time.strptime(s, duration_format)
return 3600 * t.tm_hour + 60 * t.tm_min + t.tm_sec
def _map_position(data):
antenna = Position()
if 'antenna_id' in data and data['antenna_id']:
antenna.antenna = data['antenna_id']
if 'place_id' in data:
raise NameError("Use field name 'antenna_id' in input files. "
"'place_id' is deprecated.")
if 'latitude' in data and 'longitude' in data:
latitude = data['latitude']
longitude = data['longitude']
# latitude and longitude should not be empty strings.
if latitude and longitude:
antenna.location = float(latitude), float(longitude)
return antenna
return Record(interaction=data['interaction'] if data['interaction'] else None,
direction=data['direction'],
correspondent_id=data['correspondent_id'],
datetime=_tryto(
lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S"),
data['datetime']),
call_duration=_tryto(_map_duration, data['call_duration']),
position=_tryto(_map_position, data)) | python | def _parse_record(data, duration_format='seconds'):
def _map_duration(s):
if s == '':
return None
elif duration_format.lower() == 'seconds':
return int(s)
else:
t = time.strptime(s, duration_format)
return 3600 * t.tm_hour + 60 * t.tm_min + t.tm_sec
def _map_position(data):
antenna = Position()
if 'antenna_id' in data and data['antenna_id']:
antenna.antenna = data['antenna_id']
if 'place_id' in data:
raise NameError("Use field name 'antenna_id' in input files. "
"'place_id' is deprecated.")
if 'latitude' in data and 'longitude' in data:
latitude = data['latitude']
longitude = data['longitude']
# latitude and longitude should not be empty strings.
if latitude and longitude:
antenna.location = float(latitude), float(longitude)
return antenna
return Record(interaction=data['interaction'] if data['interaction'] else None,
direction=data['direction'],
correspondent_id=data['correspondent_id'],
datetime=_tryto(
lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S"),
data['datetime']),
call_duration=_tryto(_map_duration, data['call_duration']),
position=_tryto(_map_position, data)) | [
"def",
"_parse_record",
"(",
"data",
",",
"duration_format",
"=",
"'seconds'",
")",
":",
"def",
"_map_duration",
"(",
"s",
")",
":",
"if",
"s",
"==",
"''",
":",
"return",
"None",
"elif",
"duration_format",
".",
"lower",
"(",
")",
"==",
"'seconds'",
":",
... | Parse a raw data dictionary and return a Record object. | [
"Parse",
"a",
"raw",
"data",
"dictionary",
"and",
"return",
"a",
"Record",
"object",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/io.py#L147-L187 |
24,714 | yvesalexandre/bandicoot | bandicoot/io.py | filter_record | def filter_record(records):
"""
Filter records and remove items with missing or inconsistent fields
Parameters
----------
records : list
A list of Record objects
Returns
-------
records, ignored : (Record list, dict)
A tuple of filtered records, and a dictionary counting the
missings fields
"""
def scheme(r):
if r.interaction is None:
call_duration_ok = True
elif r.interaction == 'call':
call_duration_ok = isinstance(r.call_duration, (int, float))
else:
call_duration_ok = True
callandtext = r.interaction in ['call', 'text']
not_callandtext = not callandtext
return {
'interaction': r.interaction in ['call', 'text', 'gps', None],
'direction': (not_callandtext and r.direction is None) or r.direction in ['in', 'out'],
'correspondent_id': not_callandtext or (r.correspondent_id not in [None, '']),
'datetime': isinstance(r.datetime, datetime),
'call_duration': call_duration_ok,
'location': callandtext or r.position.type() is not None
}
ignored = OrderedDict([
('all', 0),
('interaction', 0),
('direction', 0),
('correspondent_id', 0),
('datetime', 0),
('call_duration', 0),
('location', 0),
])
bad_records = []
def _filter(records):
for r in records:
valid = True
for key, valid_key in scheme(r).items():
if not valid_key:
ignored[key] += 1
bad_records.append(r)
# Not breaking, to count all fields with errors
valid = False
if valid:
yield r
else:
ignored['all'] += 1
return list(_filter(records)), ignored, bad_records | python | def filter_record(records):
def scheme(r):
if r.interaction is None:
call_duration_ok = True
elif r.interaction == 'call':
call_duration_ok = isinstance(r.call_duration, (int, float))
else:
call_duration_ok = True
callandtext = r.interaction in ['call', 'text']
not_callandtext = not callandtext
return {
'interaction': r.interaction in ['call', 'text', 'gps', None],
'direction': (not_callandtext and r.direction is None) or r.direction in ['in', 'out'],
'correspondent_id': not_callandtext or (r.correspondent_id not in [None, '']),
'datetime': isinstance(r.datetime, datetime),
'call_duration': call_duration_ok,
'location': callandtext or r.position.type() is not None
}
ignored = OrderedDict([
('all', 0),
('interaction', 0),
('direction', 0),
('correspondent_id', 0),
('datetime', 0),
('call_duration', 0),
('location', 0),
])
bad_records = []
def _filter(records):
for r in records:
valid = True
for key, valid_key in scheme(r).items():
if not valid_key:
ignored[key] += 1
bad_records.append(r)
# Not breaking, to count all fields with errors
valid = False
if valid:
yield r
else:
ignored['all'] += 1
return list(_filter(records)), ignored, bad_records | [
"def",
"filter_record",
"(",
"records",
")",
":",
"def",
"scheme",
"(",
"r",
")",
":",
"if",
"r",
".",
"interaction",
"is",
"None",
":",
"call_duration_ok",
"=",
"True",
"elif",
"r",
".",
"interaction",
"==",
"'call'",
":",
"call_duration_ok",
"=",
"isin... | Filter records and remove items with missing or inconsistent fields
Parameters
----------
records : list
A list of Record objects
Returns
-------
records, ignored : (Record list, dict)
A tuple of filtered records, and a dictionary counting the
missings fields | [
"Filter",
"records",
"and",
"remove",
"items",
"with",
"missing",
"or",
"inconsistent",
"fields"
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/io.py#L204-L269 |
24,715 | yvesalexandre/bandicoot | bandicoot/io.py | read_csv | def read_csv(user_id, records_path, antennas_path=None, attributes_path=None,
recharges_path=None, network=False, duration_format='seconds',
describe=True, warnings=True, errors=False, drop_duplicates=False):
"""
Load user records from a CSV file.
Parameters
----------
user_id : str
ID of the user (filename)
records_path : str
Path of the directory all the user files.
antennas_path : str, optional
Path of the CSV file containing (place_id, latitude, longitude) values.
This allows antennas to be mapped to their locations.
recharges_path : str, optional
Path of the directory containing recharges files
(``datetime, amount, balance, retailer_id`` CSV file).
antennas_path : str, optional
Path of the CSV file containing (place_id, latitude, longitude) values.
This allows antennas to be mapped to their locations.
network : bool, optional
If network is True, bandicoot loads the network of the user's
correspondants from the same path. Defaults to False.
duration_format : str, default is 'seconds'
Allows reading records with call duration specified in other formats
than seconds. Options are 'seconds' or any format such as '%H:%M:%S',
'%M%S', etc.
describe : boolean
If describe is True, it will print a description of the loaded user
to the standard output.
errors : boolean
If errors is True, returns a tuple (user, errors), where user is the
user object and errors are the records which could not be loaded.
drop_duplicates : boolean
If drop_duplicates, remove "duplicated records" (same correspondants,
direction, date and time). Not activated by default.
Examples
--------
>>> user = bandicoot.read_csv('sample_records', '.')
>>> print len(user.records)
10
>>> user = bandicoot.read_csv('sample_records', 'samples', 'sample_places.csv')
>>> print len(user.antennas)
5
>>> user = bandicoot.read_csv('sample_records', '.', None, 'sample_attributes.csv')
>>> print user.attributes['age']
25
Notes
-----
- The csv files can be single, or double quoted if needed.
- Empty cells are filled with ``None``. For example, if the column
``call_duration`` is empty for one record, its value will be ``None``.
Other values such as ``"N/A"``, ``"None"``, ``"null"`` will be
considered as a text.
"""
antennas = None
if antennas_path is not None:
try:
with open(antennas_path, 'r') as csv_file:
reader = csv.DictReader(csv_file)
antennas = dict((d['antenna_id'], (float(d['latitude']),
float(d['longitude'])))
for d in reader)
except IOError:
pass
user_records = os.path.join(records_path, user_id + '.csv')
with open(user_records, 'r') as csv_file:
reader = csv.DictReader(csv_file)
records = [_parse_record(r, duration_format) for r in reader]
attributes = None
if attributes_path is not None:
user_attributes = os.path.join(attributes_path, user_id + '.csv')
attributes = _load_attributes(user_attributes)
recharges = None
if recharges_path is not None:
user_recharges = os.path.join(recharges_path, user_id + '.csv')
recharges = _load_recharges(user_recharges)
user, bad_records = load(user_id, records, antennas, attributes, recharges,
antennas_path, attributes_path, recharges_path,
describe=False, warnings=warnings,
drop_duplicates=drop_duplicates)
# Loads the network
if network is True:
user.network = _read_network(user, records_path, attributes_path,
read_csv, antennas_path, warnings,
drop_duplicates=drop_duplicates)
user.recompute_missing_neighbors()
if describe:
user.describe()
if errors:
return user, bad_records
return user | python | def read_csv(user_id, records_path, antennas_path=None, attributes_path=None,
recharges_path=None, network=False, duration_format='seconds',
describe=True, warnings=True, errors=False, drop_duplicates=False):
antennas = None
if antennas_path is not None:
try:
with open(antennas_path, 'r') as csv_file:
reader = csv.DictReader(csv_file)
antennas = dict((d['antenna_id'], (float(d['latitude']),
float(d['longitude'])))
for d in reader)
except IOError:
pass
user_records = os.path.join(records_path, user_id + '.csv')
with open(user_records, 'r') as csv_file:
reader = csv.DictReader(csv_file)
records = [_parse_record(r, duration_format) for r in reader]
attributes = None
if attributes_path is not None:
user_attributes = os.path.join(attributes_path, user_id + '.csv')
attributes = _load_attributes(user_attributes)
recharges = None
if recharges_path is not None:
user_recharges = os.path.join(recharges_path, user_id + '.csv')
recharges = _load_recharges(user_recharges)
user, bad_records = load(user_id, records, antennas, attributes, recharges,
antennas_path, attributes_path, recharges_path,
describe=False, warnings=warnings,
drop_duplicates=drop_duplicates)
# Loads the network
if network is True:
user.network = _read_network(user, records_path, attributes_path,
read_csv, antennas_path, warnings,
drop_duplicates=drop_duplicates)
user.recompute_missing_neighbors()
if describe:
user.describe()
if errors:
return user, bad_records
return user | [
"def",
"read_csv",
"(",
"user_id",
",",
"records_path",
",",
"antennas_path",
"=",
"None",
",",
"attributes_path",
"=",
"None",
",",
"recharges_path",
"=",
"None",
",",
"network",
"=",
"False",
",",
"duration_format",
"=",
"'seconds'",
",",
"describe",
"=",
... | Load user records from a CSV file.
Parameters
----------
user_id : str
ID of the user (filename)
records_path : str
Path of the directory all the user files.
antennas_path : str, optional
Path of the CSV file containing (place_id, latitude, longitude) values.
This allows antennas to be mapped to their locations.
recharges_path : str, optional
Path of the directory containing recharges files
(``datetime, amount, balance, retailer_id`` CSV file).
antennas_path : str, optional
Path of the CSV file containing (place_id, latitude, longitude) values.
This allows antennas to be mapped to their locations.
network : bool, optional
If network is True, bandicoot loads the network of the user's
correspondants from the same path. Defaults to False.
duration_format : str, default is 'seconds'
Allows reading records with call duration specified in other formats
than seconds. Options are 'seconds' or any format such as '%H:%M:%S',
'%M%S', etc.
describe : boolean
If describe is True, it will print a description of the loaded user
to the standard output.
errors : boolean
If errors is True, returns a tuple (user, errors), where user is the
user object and errors are the records which could not be loaded.
drop_duplicates : boolean
If drop_duplicates, remove "duplicated records" (same correspondants,
direction, date and time). Not activated by default.
Examples
--------
>>> user = bandicoot.read_csv('sample_records', '.')
>>> print len(user.records)
10
>>> user = bandicoot.read_csv('sample_records', 'samples', 'sample_places.csv')
>>> print len(user.antennas)
5
>>> user = bandicoot.read_csv('sample_records', '.', None, 'sample_attributes.csv')
>>> print user.attributes['age']
25
Notes
-----
- The csv files can be single, or double quoted if needed.
- Empty cells are filled with ``None``. For example, if the column
``call_duration`` is empty for one record, its value will be ``None``.
Other values such as ``"N/A"``, ``"None"``, ``"null"`` will be
considered as a text. | [
"Load",
"user",
"records",
"from",
"a",
"CSV",
"file",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/io.py#L488-L604 |
24,716 | yvesalexandre/bandicoot | bandicoot/individual.py | interevent_time | def interevent_time(records):
"""
The interevent time between two records of the user.
"""
inter_events = pairwise(r.datetime for r in records)
inter = [(new - old).total_seconds() for old, new in inter_events]
return summary_stats(inter) | python | def interevent_time(records):
inter_events = pairwise(r.datetime for r in records)
inter = [(new - old).total_seconds() for old, new in inter_events]
return summary_stats(inter) | [
"def",
"interevent_time",
"(",
"records",
")",
":",
"inter_events",
"=",
"pairwise",
"(",
"r",
".",
"datetime",
"for",
"r",
"in",
"records",
")",
"inter",
"=",
"[",
"(",
"new",
"-",
"old",
")",
".",
"total_seconds",
"(",
")",
"for",
"old",
",",
"new"... | The interevent time between two records of the user. | [
"The",
"interevent",
"time",
"between",
"two",
"records",
"of",
"the",
"user",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L36-L43 |
24,717 | yvesalexandre/bandicoot | bandicoot/individual.py | number_of_contacts | def number_of_contacts(records, direction=None, more=0):
"""
The number of contacts the user interacted with.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
more : int, default is 0
Counts only contacts with more than this number of interactions.
"""
if direction is None:
counter = Counter(r.correspondent_id for r in records)
else:
counter = Counter(r.correspondent_id for r in records if r.direction == direction)
return sum(1 for d in counter.values() if d > more) | python | def number_of_contacts(records, direction=None, more=0):
if direction is None:
counter = Counter(r.correspondent_id for r in records)
else:
counter = Counter(r.correspondent_id for r in records if r.direction == direction)
return sum(1 for d in counter.values() if d > more) | [
"def",
"number_of_contacts",
"(",
"records",
",",
"direction",
"=",
"None",
",",
"more",
"=",
"0",
")",
":",
"if",
"direction",
"is",
"None",
":",
"counter",
"=",
"Counter",
"(",
"r",
".",
"correspondent_id",
"for",
"r",
"in",
"records",
")",
"else",
"... | The number of contacts the user interacted with.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
more : int, default is 0
Counts only contacts with more than this number of interactions. | [
"The",
"number",
"of",
"contacts",
"the",
"user",
"interacted",
"with",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L47-L63 |
24,718 | yvesalexandre/bandicoot | bandicoot/individual.py | entropy_of_contacts | def entropy_of_contacts(records, normalize=False):
"""
The entropy of the user's contacts.
Parameters
----------
normalize: boolean, default is False
Returns a normalized entropy between 0 and 1.
"""
counter = Counter(r.correspondent_id for r in records)
raw_entropy = entropy(counter.values())
n = len(counter)
if normalize and n > 1:
return raw_entropy / math.log(n)
else:
return raw_entropy | python | def entropy_of_contacts(records, normalize=False):
counter = Counter(r.correspondent_id for r in records)
raw_entropy = entropy(counter.values())
n = len(counter)
if normalize and n > 1:
return raw_entropy / math.log(n)
else:
return raw_entropy | [
"def",
"entropy_of_contacts",
"(",
"records",
",",
"normalize",
"=",
"False",
")",
":",
"counter",
"=",
"Counter",
"(",
"r",
".",
"correspondent_id",
"for",
"r",
"in",
"records",
")",
"raw_entropy",
"=",
"entropy",
"(",
"counter",
".",
"values",
"(",
")",
... | The entropy of the user's contacts.
Parameters
----------
normalize: boolean, default is False
Returns a normalized entropy between 0 and 1. | [
"The",
"entropy",
"of",
"the",
"user",
"s",
"contacts",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L67-L84 |
24,719 | yvesalexandre/bandicoot | bandicoot/individual.py | interactions_per_contact | def interactions_per_contact(records, direction=None):
"""
The number of interactions a user had with each of its contacts.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
"""
if direction is None:
counter = Counter(r.correspondent_id for r in records)
else:
counter = Counter(r.correspondent_id for r in records
if r.direction == direction)
return summary_stats(counter.values()) | python | def interactions_per_contact(records, direction=None):
if direction is None:
counter = Counter(r.correspondent_id for r in records)
else:
counter = Counter(r.correspondent_id for r in records
if r.direction == direction)
return summary_stats(counter.values()) | [
"def",
"interactions_per_contact",
"(",
"records",
",",
"direction",
"=",
"None",
")",
":",
"if",
"direction",
"is",
"None",
":",
"counter",
"=",
"Counter",
"(",
"r",
".",
"correspondent_id",
"for",
"r",
"in",
"records",
")",
"else",
":",
"counter",
"=",
... | The number of interactions a user had with each of its contacts.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing. | [
"The",
"number",
"of",
"interactions",
"a",
"user",
"had",
"with",
"each",
"of",
"its",
"contacts",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L88-L103 |
24,720 | yvesalexandre/bandicoot | bandicoot/individual.py | percent_initiated_interactions | def percent_initiated_interactions(records, user):
"""
The percentage of calls initiated by the user.
"""
if len(records) == 0:
return 0
initiated = sum(1 for r in records if r.direction == 'out')
return initiated / len(records) | python | def percent_initiated_interactions(records, user):
if len(records) == 0:
return 0
initiated = sum(1 for r in records if r.direction == 'out')
return initiated / len(records) | [
"def",
"percent_initiated_interactions",
"(",
"records",
",",
"user",
")",
":",
"if",
"len",
"(",
"records",
")",
"==",
"0",
":",
"return",
"0",
"initiated",
"=",
"sum",
"(",
"1",
"for",
"r",
"in",
"records",
"if",
"r",
".",
"direction",
"==",
"'out'",... | The percentage of calls initiated by the user. | [
"The",
"percentage",
"of",
"calls",
"initiated",
"by",
"the",
"user",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L107-L115 |
24,721 | yvesalexandre/bandicoot | bandicoot/individual.py | percent_nocturnal | def percent_nocturnal(records, user):
"""
The percentage of interactions the user had at night.
By default, nights are 7pm-7am. Nightimes can be set in
``User.night_start`` and ``User.night_end``.
"""
if len(records) == 0:
return 0
if user.night_start < user.night_end:
night_filter = lambda d: user.night_end > d.time() > user.night_start
else:
night_filter = lambda d: not(user.night_end < d.time() < user.night_start)
return sum(1 for r in records if night_filter(r.datetime)) / len(records) | python | def percent_nocturnal(records, user):
if len(records) == 0:
return 0
if user.night_start < user.night_end:
night_filter = lambda d: user.night_end > d.time() > user.night_start
else:
night_filter = lambda d: not(user.night_end < d.time() < user.night_start)
return sum(1 for r in records if night_filter(r.datetime)) / len(records) | [
"def",
"percent_nocturnal",
"(",
"records",
",",
"user",
")",
":",
"if",
"len",
"(",
"records",
")",
"==",
"0",
":",
"return",
"0",
"if",
"user",
".",
"night_start",
"<",
"user",
".",
"night_end",
":",
"night_filter",
"=",
"lambda",
"d",
":",
"user",
... | The percentage of interactions the user had at night.
By default, nights are 7pm-7am. Nightimes can be set in
``User.night_start`` and ``User.night_end``. | [
"The",
"percentage",
"of",
"interactions",
"the",
"user",
"had",
"at",
"night",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L119-L134 |
24,722 | yvesalexandre/bandicoot | bandicoot/individual.py | call_duration | def call_duration(records, direction=None):
"""
The duration of the user's calls.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
"""
if direction is None:
call_durations = [r.call_duration for r in records]
else:
call_durations = [r.call_duration for r in records if r.direction == direction]
return summary_stats(call_durations) | python | def call_duration(records, direction=None):
if direction is None:
call_durations = [r.call_duration for r in records]
else:
call_durations = [r.call_duration for r in records if r.direction == direction]
return summary_stats(call_durations) | [
"def",
"call_duration",
"(",
"records",
",",
"direction",
"=",
"None",
")",
":",
"if",
"direction",
"is",
"None",
":",
"call_durations",
"=",
"[",
"r",
".",
"call_duration",
"for",
"r",
"in",
"records",
"]",
"else",
":",
"call_durations",
"=",
"[",
"r",
... | The duration of the user's calls.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing. | [
"The",
"duration",
"of",
"the",
"user",
"s",
"calls",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L138-L153 |
24,723 | yvesalexandre/bandicoot | bandicoot/individual.py | _conversations | def _conversations(group, delta=datetime.timedelta(hours=1)):
"""
Group texts into conversations. The function returns an iterator over
records grouped by conversations.
See :ref:`Using bandicoot <conversations-label>` for a definition of
conversations.
A conversation begins when one person sends a text-message to the other and
ends when one of them makes a phone call or there is no activity between
them for an hour.
"""
last_time = None
results = []
for g in group:
if last_time is None or g.datetime - last_time < delta:
if g.interaction == 'text':
results.append(g)
# A call always ends a conversation
else:
if len(results) != 0:
yield results
results = []
else:
if len(results) != 0:
yield results
if g.interaction == 'call':
results = []
else:
results = [g]
last_time = g.datetime
if len(results) != 0:
yield results | python | def _conversations(group, delta=datetime.timedelta(hours=1)):
last_time = None
results = []
for g in group:
if last_time is None or g.datetime - last_time < delta:
if g.interaction == 'text':
results.append(g)
# A call always ends a conversation
else:
if len(results) != 0:
yield results
results = []
else:
if len(results) != 0:
yield results
if g.interaction == 'call':
results = []
else:
results = [g]
last_time = g.datetime
if len(results) != 0:
yield results | [
"def",
"_conversations",
"(",
"group",
",",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"1",
")",
")",
":",
"last_time",
"=",
"None",
"results",
"=",
"[",
"]",
"for",
"g",
"in",
"group",
":",
"if",
"last_time",
"is",
"None",
"or",
... | Group texts into conversations. The function returns an iterator over
records grouped by conversations.
See :ref:`Using bandicoot <conversations-label>` for a definition of
conversations.
A conversation begins when one person sends a text-message to the other and
ends when one of them makes a phone call or there is no activity between
them for an hour. | [
"Group",
"texts",
"into",
"conversations",
".",
"The",
"function",
"returns",
"an",
"iterator",
"over",
"records",
"grouped",
"by",
"conversations",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L156-L194 |
24,724 | yvesalexandre/bandicoot | bandicoot/individual.py | percent_initiated_conversations | def percent_initiated_conversations(records):
"""
The percentage of conversations that have been initiated by the user.
Each call and each text conversation is weighted as a single interaction.
See :ref:`Using bandicoot <conversations-label>` for a definition of
conversations.
"""
interactions = defaultdict(list)
for r in records:
interactions[r.correspondent_id].append(r)
def _percent_initiated(grouped):
mapped = [(1 if conv[0].direction == 'out' else 0, 1)
for conv in _conversations(grouped)]
return mapped
all_couples = [sublist for i in interactions.values()
for sublist in _percent_initiated(i)]
if len(all_couples) == 0:
init, total = 0, 0
else:
init, total = list(map(sum, list(zip(*all_couples))))
return init / total if total != 0 else 0 | python | def percent_initiated_conversations(records):
interactions = defaultdict(list)
for r in records:
interactions[r.correspondent_id].append(r)
def _percent_initiated(grouped):
mapped = [(1 if conv[0].direction == 'out' else 0, 1)
for conv in _conversations(grouped)]
return mapped
all_couples = [sublist for i in interactions.values()
for sublist in _percent_initiated(i)]
if len(all_couples) == 0:
init, total = 0, 0
else:
init, total = list(map(sum, list(zip(*all_couples))))
return init / total if total != 0 else 0 | [
"def",
"percent_initiated_conversations",
"(",
"records",
")",
":",
"interactions",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"r",
"in",
"records",
":",
"interactions",
"[",
"r",
".",
"correspondent_id",
"]",
".",
"append",
"(",
"r",
")",
"def",
"_percent... | The percentage of conversations that have been initiated by the user.
Each call and each text conversation is weighted as a single interaction.
See :ref:`Using bandicoot <conversations-label>` for a definition of
conversations. | [
"The",
"percentage",
"of",
"conversations",
"that",
"have",
"been",
"initiated",
"by",
"the",
"user",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L290-L316 |
24,725 | yvesalexandre/bandicoot | bandicoot/individual.py | active_days | def active_days(records):
"""
The number of days during which the user was active. A user is considered
active if he sends a text, receives a text, initiates a call, receives a
call, or has a mobility point.
"""
days = set(r.datetime.date() for r in records)
return len(days) | python | def active_days(records):
days = set(r.datetime.date() for r in records)
return len(days) | [
"def",
"active_days",
"(",
"records",
")",
":",
"days",
"=",
"set",
"(",
"r",
".",
"datetime",
".",
"date",
"(",
")",
"for",
"r",
"in",
"records",
")",
"return",
"len",
"(",
"days",
")"
] | The number of days during which the user was active. A user is considered
active if he sends a text, receives a text, initiates a call, receives a
call, or has a mobility point. | [
"The",
"number",
"of",
"days",
"during",
"which",
"the",
"user",
"was",
"active",
".",
"A",
"user",
"is",
"considered",
"active",
"if",
"he",
"sends",
"a",
"text",
"receives",
"a",
"text",
"initiates",
"a",
"call",
"receives",
"a",
"call",
"or",
"has",
... | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L320-L327 |
24,726 | yvesalexandre/bandicoot | bandicoot/individual.py | percent_pareto_interactions | def percent_pareto_interactions(records, percentage=0.8):
"""
The percentage of user's contacts that account for 80% of its interactions.
"""
if len(records) == 0:
return None
user_count = Counter(r.correspondent_id for r in records)
target = int(math.ceil(sum(user_count.values()) * percentage))
user_sort = sorted(user_count.keys(), key=lambda x: user_count[x])
while target > 0 and len(user_sort) > 0:
user_id = user_sort.pop()
target -= user_count[user_id]
return (len(user_count) - len(user_sort)) / len(records) | python | def percent_pareto_interactions(records, percentage=0.8):
if len(records) == 0:
return None
user_count = Counter(r.correspondent_id for r in records)
target = int(math.ceil(sum(user_count.values()) * percentage))
user_sort = sorted(user_count.keys(), key=lambda x: user_count[x])
while target > 0 and len(user_sort) > 0:
user_id = user_sort.pop()
target -= user_count[user_id]
return (len(user_count) - len(user_sort)) / len(records) | [
"def",
"percent_pareto_interactions",
"(",
"records",
",",
"percentage",
"=",
"0.8",
")",
":",
"if",
"len",
"(",
"records",
")",
"==",
"0",
":",
"return",
"None",
"user_count",
"=",
"Counter",
"(",
"r",
".",
"correspondent_id",
"for",
"r",
"in",
"records",... | The percentage of user's contacts that account for 80% of its interactions. | [
"The",
"percentage",
"of",
"user",
"s",
"contacts",
"that",
"account",
"for",
"80%",
"of",
"its",
"interactions",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L331-L347 |
24,727 | yvesalexandre/bandicoot | bandicoot/individual.py | number_of_interactions | def number_of_interactions(records, direction=None):
"""
The number of interactions.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
"""
if direction is None:
return len(records)
else:
return len([r for r in records if r.direction == direction]) | python | def number_of_interactions(records, direction=None):
if direction is None:
return len(records)
else:
return len([r for r in records if r.direction == direction]) | [
"def",
"number_of_interactions",
"(",
"records",
",",
"direction",
"=",
"None",
")",
":",
"if",
"direction",
"is",
"None",
":",
"return",
"len",
"(",
"records",
")",
"else",
":",
"return",
"len",
"(",
"[",
"r",
"for",
"r",
"in",
"records",
"if",
"r",
... | The number of interactions.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing. | [
"The",
"number",
"of",
"interactions",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L409-L422 |
24,728 | yvesalexandre/bandicoot | bandicoot/weekmatrix.py | to_csv | def to_csv(weekmatrices, filename, digits=5):
"""
Exports a list of week-matrices to a specified filename in the CSV format.
Parameters
----------
weekmatrices : list
The week-matrices to export.
filename : string
Path for the exported CSV file.
"""
with open(filename, 'w') as f:
w = csv.writer(f, lineterminator='\n')
w.writerow(['year_week', 'channel', 'weekday', 'section', 'value'])
def make_repr(item):
if item is None:
return None
elif isinstance(item, float):
return repr(round(item, digits))
else:
return str(item)
for row in weekmatrices:
w.writerow([make_repr(item) for item in row]) | python | def to_csv(weekmatrices, filename, digits=5):
with open(filename, 'w') as f:
w = csv.writer(f, lineterminator='\n')
w.writerow(['year_week', 'channel', 'weekday', 'section', 'value'])
def make_repr(item):
if item is None:
return None
elif isinstance(item, float):
return repr(round(item, digits))
else:
return str(item)
for row in weekmatrices:
w.writerow([make_repr(item) for item in row]) | [
"def",
"to_csv",
"(",
"weekmatrices",
",",
"filename",
",",
"digits",
"=",
"5",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"w",
"=",
"csv",
".",
"writer",
"(",
"f",
",",
"lineterminator",
"=",
"'\\n'",
")",
"w",
"... | Exports a list of week-matrices to a specified filename in the CSV format.
Parameters
----------
weekmatrices : list
The week-matrices to export.
filename : string
Path for the exported CSV file. | [
"Exports",
"a",
"list",
"of",
"week",
"-",
"matrices",
"to",
"a",
"specified",
"filename",
"in",
"the",
"CSV",
"format",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/weekmatrix.py#L105-L130 |
24,729 | yvesalexandre/bandicoot | bandicoot/weekmatrix.py | read_csv | def read_csv(filename):
"""
Read a list of week-matrices from a CSV file.
"""
with open(filename, 'r') as f:
r = csv.reader(f)
next(r) # remove header
wm = list(r)
# remove header and convert to numeric
for i, row in enumerate(wm):
row[1:4] = map(int, row[1:4])
row[4] = float(row[4])
return wm | python | def read_csv(filename):
with open(filename, 'r') as f:
r = csv.reader(f)
next(r) # remove header
wm = list(r)
# remove header and convert to numeric
for i, row in enumerate(wm):
row[1:4] = map(int, row[1:4])
row[4] = float(row[4])
return wm | [
"def",
"read_csv",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"r",
"=",
"csv",
".",
"reader",
"(",
"f",
")",
"next",
"(",
"r",
")",
"# remove header",
"wm",
"=",
"list",
"(",
"r",
")",
"# remove h... | Read a list of week-matrices from a CSV file. | [
"Read",
"a",
"list",
"of",
"week",
"-",
"matrices",
"from",
"a",
"CSV",
"file",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/weekmatrix.py#L133-L148 |
24,730 | yvesalexandre/bandicoot | bandicoot/weekmatrix.py | _extract_list_from_generator | def _extract_list_from_generator(generator):
"""
Iterates over a generator to extract all the objects and add them to a list.
Useful when the objects have to be used multiple times.
"""
extracted = []
for i in generator:
extracted.append(list(i))
return extracted | python | def _extract_list_from_generator(generator):
extracted = []
for i in generator:
extracted.append(list(i))
return extracted | [
"def",
"_extract_list_from_generator",
"(",
"generator",
")",
":",
"extracted",
"=",
"[",
"]",
"for",
"i",
"in",
"generator",
":",
"extracted",
".",
"append",
"(",
"list",
"(",
"i",
")",
")",
"return",
"extracted"
] | Iterates over a generator to extract all the objects and add them to a list.
Useful when the objects have to be used multiple times. | [
"Iterates",
"over",
"a",
"generator",
"to",
"extract",
"all",
"the",
"objects",
"and",
"add",
"them",
"to",
"a",
"list",
".",
"Useful",
"when",
"the",
"objects",
"have",
"to",
"be",
"used",
"multiple",
"times",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/weekmatrix.py#L310-L319 |
24,731 | yvesalexandre/bandicoot | bandicoot/weekmatrix.py | _seconds_to_section_split | def _seconds_to_section_split(record, sections):
"""
Finds the seconds to the next section from the datetime of a record.
"""
next_section = sections[
bisect_right(sections, _find_weektime(record.datetime))] * 60
return next_section - _find_weektime(record.datetime, time_type='sec') | python | def _seconds_to_section_split(record, sections):
next_section = sections[
bisect_right(sections, _find_weektime(record.datetime))] * 60
return next_section - _find_weektime(record.datetime, time_type='sec') | [
"def",
"_seconds_to_section_split",
"(",
"record",
",",
"sections",
")",
":",
"next_section",
"=",
"sections",
"[",
"bisect_right",
"(",
"sections",
",",
"_find_weektime",
"(",
"record",
".",
"datetime",
")",
")",
"]",
"*",
"60",
"return",
"next_section",
"-",... | Finds the seconds to the next section from the datetime of a record. | [
"Finds",
"the",
"seconds",
"to",
"the",
"next",
"section",
"from",
"the",
"datetime",
"of",
"a",
"record",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/weekmatrix.py#L322-L329 |
24,732 | yvesalexandre/bandicoot | bandicoot/helper/stops.py | get_neighbors | def get_neighbors(distance_matrix, source, eps):
"""
Given a matrix of distance between couples of points,
return the list of every point closer than eps from a certain point.
"""
return [dest for dest, distance in enumerate(distance_matrix[source]) if distance < eps] | python | def get_neighbors(distance_matrix, source, eps):
return [dest for dest, distance in enumerate(distance_matrix[source]) if distance < eps] | [
"def",
"get_neighbors",
"(",
"distance_matrix",
",",
"source",
",",
"eps",
")",
":",
"return",
"[",
"dest",
"for",
"dest",
",",
"distance",
"in",
"enumerate",
"(",
"distance_matrix",
"[",
"source",
"]",
")",
"if",
"distance",
"<",
"eps",
"]"
] | Given a matrix of distance between couples of points,
return the list of every point closer than eps from a certain point. | [
"Given",
"a",
"matrix",
"of",
"distance",
"between",
"couples",
"of",
"points",
"return",
"the",
"list",
"of",
"every",
"point",
"closer",
"than",
"eps",
"from",
"a",
"certain",
"point",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/stops.py#L37-L43 |
24,733 | yvesalexandre/bandicoot | bandicoot/helper/stops.py | fix_location | def fix_location(records, max_elapsed_seconds=300):
"""
Update position of all records based on the position of
the closest GPS record.
.. note:: Use this function when call and text records are missing a
location, but you have access to accurate GPS traces.
"""
groups = itertools.groupby(records, lambda r: r.direction)
groups = [(interaction, list(g)) for interaction, g in groups]
def tdist(t1, t2):
return abs((t1 - t2).total_seconds())
for i, (interaction, g) in enumerate(groups):
if interaction == 'in':
continue
prev_gps = groups[i-1][1][-1]
next_gps = groups[i+1][1][0]
for r in g:
if tdist(r.datetime, prev_gps.datetime) <= max_elapsed_seconds:
r.position = prev_gps.position
elif tdist(r.datetime, next_gps.datetime) <= max_elapsed_seconds:
r.position = next_gps.position | python | def fix_location(records, max_elapsed_seconds=300):
groups = itertools.groupby(records, lambda r: r.direction)
groups = [(interaction, list(g)) for interaction, g in groups]
def tdist(t1, t2):
return abs((t1 - t2).total_seconds())
for i, (interaction, g) in enumerate(groups):
if interaction == 'in':
continue
prev_gps = groups[i-1][1][-1]
next_gps = groups[i+1][1][0]
for r in g:
if tdist(r.datetime, prev_gps.datetime) <= max_elapsed_seconds:
r.position = prev_gps.position
elif tdist(r.datetime, next_gps.datetime) <= max_elapsed_seconds:
r.position = next_gps.position | [
"def",
"fix_location",
"(",
"records",
",",
"max_elapsed_seconds",
"=",
"300",
")",
":",
"groups",
"=",
"itertools",
".",
"groupby",
"(",
"records",
",",
"lambda",
"r",
":",
"r",
".",
"direction",
")",
"groups",
"=",
"[",
"(",
"interaction",
",",
"list",... | Update position of all records based on the position of
the closest GPS record.
.. note:: Use this function when call and text records are missing a
location, but you have access to accurate GPS traces. | [
"Update",
"position",
"of",
"all",
"records",
"based",
"on",
"the",
"position",
"of",
"the",
"closest",
"GPS",
"record",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/stops.py#L174-L200 |
24,734 | wbond/certvalidator | certvalidator/ocsp_client.py | fetch | def fetch(cert, issuer, hash_algo='sha1', nonce=True, user_agent=None, timeout=10):
"""
Fetches an OCSP response for a certificate
:param cert:
An asn1cyrpto.x509.Certificate object to get an OCSP reponse for
:param issuer:
An asn1crypto.x509.Certificate object that is the issuer of cert
:param hash_algo:
A unicode string of "sha1" or "sha256"
:param nonce:
A boolean - if the nonce extension should be used to prevent replay
attacks
:param user_agent:
The HTTP user agent to use when requesting the OCSP response. If None,
a default is used in the format "certvalidation 1.0.0".
:param timeout:
The number of seconds after which an HTTP request should timeout
:raises:
urllib.error.URLError/urllib2.URLError - when a URL/HTTP error occurs
socket.error - when a socket error occurs
:return:
An asn1crypto.ocsp.OCSPResponse object
"""
if not isinstance(cert, x509.Certificate):
raise TypeError('cert must be an instance of asn1crypto.x509.Certificate, not %s' % type_name(cert))
if not isinstance(issuer, x509.Certificate):
raise TypeError('issuer must be an instance of asn1crypto.x509.Certificate, not %s' % type_name(issuer))
if hash_algo not in set(['sha1', 'sha256']):
raise ValueError('hash_algo must be one of "sha1", "sha256", not %s' % repr(hash_algo))
if not isinstance(nonce, bool):
raise TypeError('nonce must be a bool, not %s' % type_name(nonce))
if user_agent is None:
user_agent = 'certvalidator %s' % __version__
elif not isinstance(user_agent, str_cls):
raise TypeError('user_agent must be a unicode string, not %s' % type_name(user_agent))
cert_id = ocsp.CertId({
'hash_algorithm': algos.DigestAlgorithm({'algorithm': hash_algo}),
'issuer_name_hash': getattr(cert.issuer, hash_algo),
'issuer_key_hash': getattr(issuer.public_key, hash_algo),
'serial_number': cert.serial_number,
})
request = ocsp.Request({
'req_cert': cert_id,
})
tbs_request = ocsp.TBSRequest({
'request_list': ocsp.Requests([request]),
})
if nonce:
nonce_extension = ocsp.TBSRequestExtension({
'extn_id': 'nonce',
'critical': False,
'extn_value': core.OctetString(core.OctetString(os.urandom(16)).dump())
})
tbs_request['request_extensions'] = ocsp.TBSRequestExtensions([nonce_extension])
ocsp_request = ocsp.OCSPRequest({
'tbs_request': tbs_request,
})
last_e = None
for ocsp_url in cert.ocsp_urls:
try:
request = Request(ocsp_url)
request.add_header('Accept', 'application/ocsp-response')
request.add_header('Content-Type', 'application/ocsp-request')
request.add_header('User-Agent', user_agent)
response = urlopen(request, ocsp_request.dump(), timeout)
ocsp_response = ocsp.OCSPResponse.load(response.read())
request_nonce = ocsp_request.nonce_value
response_nonce = ocsp_response.nonce_value
if request_nonce and response_nonce and request_nonce.native != response_nonce.native:
raise errors.OCSPValidationError(
'Unable to verify OCSP response since the request and response nonces do not match'
)
return ocsp_response
except (URLError) as e:
last_e = e
raise last_e | python | def fetch(cert, issuer, hash_algo='sha1', nonce=True, user_agent=None, timeout=10):
if not isinstance(cert, x509.Certificate):
raise TypeError('cert must be an instance of asn1crypto.x509.Certificate, not %s' % type_name(cert))
if not isinstance(issuer, x509.Certificate):
raise TypeError('issuer must be an instance of asn1crypto.x509.Certificate, not %s' % type_name(issuer))
if hash_algo not in set(['sha1', 'sha256']):
raise ValueError('hash_algo must be one of "sha1", "sha256", not %s' % repr(hash_algo))
if not isinstance(nonce, bool):
raise TypeError('nonce must be a bool, not %s' % type_name(nonce))
if user_agent is None:
user_agent = 'certvalidator %s' % __version__
elif not isinstance(user_agent, str_cls):
raise TypeError('user_agent must be a unicode string, not %s' % type_name(user_agent))
cert_id = ocsp.CertId({
'hash_algorithm': algos.DigestAlgorithm({'algorithm': hash_algo}),
'issuer_name_hash': getattr(cert.issuer, hash_algo),
'issuer_key_hash': getattr(issuer.public_key, hash_algo),
'serial_number': cert.serial_number,
})
request = ocsp.Request({
'req_cert': cert_id,
})
tbs_request = ocsp.TBSRequest({
'request_list': ocsp.Requests([request]),
})
if nonce:
nonce_extension = ocsp.TBSRequestExtension({
'extn_id': 'nonce',
'critical': False,
'extn_value': core.OctetString(core.OctetString(os.urandom(16)).dump())
})
tbs_request['request_extensions'] = ocsp.TBSRequestExtensions([nonce_extension])
ocsp_request = ocsp.OCSPRequest({
'tbs_request': tbs_request,
})
last_e = None
for ocsp_url in cert.ocsp_urls:
try:
request = Request(ocsp_url)
request.add_header('Accept', 'application/ocsp-response')
request.add_header('Content-Type', 'application/ocsp-request')
request.add_header('User-Agent', user_agent)
response = urlopen(request, ocsp_request.dump(), timeout)
ocsp_response = ocsp.OCSPResponse.load(response.read())
request_nonce = ocsp_request.nonce_value
response_nonce = ocsp_response.nonce_value
if request_nonce and response_nonce and request_nonce.native != response_nonce.native:
raise errors.OCSPValidationError(
'Unable to verify OCSP response since the request and response nonces do not match'
)
return ocsp_response
except (URLError) as e:
last_e = e
raise last_e | [
"def",
"fetch",
"(",
"cert",
",",
"issuer",
",",
"hash_algo",
"=",
"'sha1'",
",",
"nonce",
"=",
"True",
",",
"user_agent",
"=",
"None",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"not",
"isinstance",
"(",
"cert",
",",
"x509",
".",
"Certificate",
")",... | Fetches an OCSP response for a certificate
:param cert:
An asn1cyrpto.x509.Certificate object to get an OCSP reponse for
:param issuer:
An asn1crypto.x509.Certificate object that is the issuer of cert
:param hash_algo:
A unicode string of "sha1" or "sha256"
:param nonce:
A boolean - if the nonce extension should be used to prevent replay
attacks
:param user_agent:
The HTTP user agent to use when requesting the OCSP response. If None,
a default is used in the format "certvalidation 1.0.0".
:param timeout:
The number of seconds after which an HTTP request should timeout
:raises:
urllib.error.URLError/urllib2.URLError - when a URL/HTTP error occurs
socket.error - when a socket error occurs
:return:
An asn1crypto.ocsp.OCSPResponse object | [
"Fetches",
"an",
"OCSP",
"response",
"for",
"a",
"certificate"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/ocsp_client.py#L14-L109 |
24,735 | wbond/certvalidator | certvalidator/registry.py | CertificateRegistry._walk_issuers | def _walk_issuers(self, path, paths, failed_paths):
"""
Recursively looks through the list of known certificates for the issuer
of the certificate specified, stopping once the certificate in question
is one contained within the CA certs list
:param path:
A ValidationPath object representing the current traversal of
possible paths
:param paths:
A list of completed ValidationPath objects. This is mutated as
results are found.
:param failed_paths:
A list of certvalidator.path.ValidationPath objects that failed due
to no matching issuer before reaching a certificate from the CA
certs list
"""
if path.first.signature in self._ca_lookup:
paths.append(path)
return
new_branches = 0
for issuer in self._possible_issuers(path.first):
try:
self._walk_issuers(path.copy().prepend(issuer), paths, failed_paths)
new_branches += 1
except (DuplicateCertificateError):
pass
if not new_branches:
failed_paths.append(path) | python | def _walk_issuers(self, path, paths, failed_paths):
if path.first.signature in self._ca_lookup:
paths.append(path)
return
new_branches = 0
for issuer in self._possible_issuers(path.first):
try:
self._walk_issuers(path.copy().prepend(issuer), paths, failed_paths)
new_branches += 1
except (DuplicateCertificateError):
pass
if not new_branches:
failed_paths.append(path) | [
"def",
"_walk_issuers",
"(",
"self",
",",
"path",
",",
"paths",
",",
"failed_paths",
")",
":",
"if",
"path",
".",
"first",
".",
"signature",
"in",
"self",
".",
"_ca_lookup",
":",
"paths",
".",
"append",
"(",
"path",
")",
"return",
"new_branches",
"=",
... | Recursively looks through the list of known certificates for the issuer
of the certificate specified, stopping once the certificate in question
is one contained within the CA certs list
:param path:
A ValidationPath object representing the current traversal of
possible paths
:param paths:
A list of completed ValidationPath objects. This is mutated as
results are found.
:param failed_paths:
A list of certvalidator.path.ValidationPath objects that failed due
to no matching issuer before reaching a certificate from the CA
certs list | [
"Recursively",
"looks",
"through",
"the",
"list",
"of",
"known",
"certificates",
"for",
"the",
"issuer",
"of",
"the",
"certificate",
"specified",
"stopping",
"once",
"the",
"certificate",
"in",
"question",
"is",
"one",
"contained",
"within",
"the",
"CA",
"certs"... | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/registry.py#L325-L358 |
24,736 | wbond/certvalidator | certvalidator/registry.py | CertificateRegistry._possible_issuers | def _possible_issuers(self, cert):
"""
Returns a generator that will list all possible issuers for the cert
:param cert:
An asn1crypto.x509.Certificate object to find the issuer of
"""
issuer_hashable = cert.issuer.hashable
if issuer_hashable not in self._subject_map:
return
for issuer in self._subject_map[issuer_hashable]:
# Info from the authority key identifier extension can be used to
# eliminate possible options when multiple keys with the same
# subject exist, such as during a transition, or with cross-signing.
if cert.authority_key_identifier and issuer.key_identifier:
if cert.authority_key_identifier != issuer.key_identifier:
continue
elif cert.authority_issuer_serial:
if cert.authority_issuer_serial != issuer.issuer_serial:
continue
yield issuer | python | def _possible_issuers(self, cert):
issuer_hashable = cert.issuer.hashable
if issuer_hashable not in self._subject_map:
return
for issuer in self._subject_map[issuer_hashable]:
# Info from the authority key identifier extension can be used to
# eliminate possible options when multiple keys with the same
# subject exist, such as during a transition, or with cross-signing.
if cert.authority_key_identifier and issuer.key_identifier:
if cert.authority_key_identifier != issuer.key_identifier:
continue
elif cert.authority_issuer_serial:
if cert.authority_issuer_serial != issuer.issuer_serial:
continue
yield issuer | [
"def",
"_possible_issuers",
"(",
"self",
",",
"cert",
")",
":",
"issuer_hashable",
"=",
"cert",
".",
"issuer",
".",
"hashable",
"if",
"issuer_hashable",
"not",
"in",
"self",
".",
"_subject_map",
":",
"return",
"for",
"issuer",
"in",
"self",
".",
"_subject_ma... | Returns a generator that will list all possible issuers for the cert
:param cert:
An asn1crypto.x509.Certificate object to find the issuer of | [
"Returns",
"a",
"generator",
"that",
"will",
"list",
"all",
"possible",
"issuers",
"for",
"the",
"cert"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/registry.py#L360-L383 |
24,737 | wbond/certvalidator | certvalidator/path.py | ValidationPath.find_issuer | def find_issuer(self, cert):
"""
Return the issuer of the cert specified, as defined by this path
:param cert:
An asn1crypto.x509.Certificate object to get the issuer of
:raises:
LookupError - when the issuer of the certificate could not be found
:return:
An asn1crypto.x509.Certificate object of the issuer
"""
for entry in self:
if entry.subject == cert.issuer:
if entry.key_identifier and cert.authority_key_identifier:
if entry.key_identifier == cert.authority_key_identifier:
return entry
else:
return entry
raise LookupError('Unable to find the issuer of the certificate specified') | python | def find_issuer(self, cert):
for entry in self:
if entry.subject == cert.issuer:
if entry.key_identifier and cert.authority_key_identifier:
if entry.key_identifier == cert.authority_key_identifier:
return entry
else:
return entry
raise LookupError('Unable to find the issuer of the certificate specified') | [
"def",
"find_issuer",
"(",
"self",
",",
"cert",
")",
":",
"for",
"entry",
"in",
"self",
":",
"if",
"entry",
".",
"subject",
"==",
"cert",
".",
"issuer",
":",
"if",
"entry",
".",
"key_identifier",
"and",
"cert",
".",
"authority_key_identifier",
":",
"if",... | Return the issuer of the cert specified, as defined by this path
:param cert:
An asn1crypto.x509.Certificate object to get the issuer of
:raises:
LookupError - when the issuer of the certificate could not be found
:return:
An asn1crypto.x509.Certificate object of the issuer | [
"Return",
"the",
"issuer",
"of",
"the",
"cert",
"specified",
"as",
"defined",
"by",
"this",
"path"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/path.py#L47-L69 |
24,738 | wbond/certvalidator | certvalidator/path.py | ValidationPath.truncate_to | def truncate_to(self, cert):
"""
Remove all certificates in the path after the cert specified
:param cert:
An asn1crypto.x509.Certificate object to find
:raises:
LookupError - when the certificate could not be found
:return:
The current ValidationPath object, for chaining
"""
cert_index = None
for index, entry in enumerate(self):
if entry.issuer_serial == cert.issuer_serial:
cert_index = index
break
if cert_index is None:
raise LookupError('Unable to find the certificate specified')
while len(self) > cert_index + 1:
self.pop()
return self | python | def truncate_to(self, cert):
cert_index = None
for index, entry in enumerate(self):
if entry.issuer_serial == cert.issuer_serial:
cert_index = index
break
if cert_index is None:
raise LookupError('Unable to find the certificate specified')
while len(self) > cert_index + 1:
self.pop()
return self | [
"def",
"truncate_to",
"(",
"self",
",",
"cert",
")",
":",
"cert_index",
"=",
"None",
"for",
"index",
",",
"entry",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"entry",
".",
"issuer_serial",
"==",
"cert",
".",
"issuer_serial",
":",
"cert_index",
"=",
... | Remove all certificates in the path after the cert specified
:param cert:
An asn1crypto.x509.Certificate object to find
:raises:
LookupError - when the certificate could not be found
:return:
The current ValidationPath object, for chaining | [
"Remove",
"all",
"certificates",
"in",
"the",
"path",
"after",
"the",
"cert",
"specified"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/path.py#L71-L97 |
24,739 | wbond/certvalidator | certvalidator/path.py | ValidationPath.truncate_to_issuer | def truncate_to_issuer(self, cert):
"""
Remove all certificates in the path after the issuer of the cert
specified, as defined by this path
:param cert:
An asn1crypto.x509.Certificate object to find the issuer of
:raises:
LookupError - when the issuer of the certificate could not be found
:return:
The current ValidationPath object, for chaining
"""
issuer_index = None
for index, entry in enumerate(self):
if entry.subject == cert.issuer:
if entry.key_identifier and cert.authority_key_identifier:
if entry.key_identifier == cert.authority_key_identifier:
issuer_index = index
break
else:
issuer_index = index
break
if issuer_index is None:
raise LookupError('Unable to find the issuer of the certificate specified')
while len(self) > issuer_index + 1:
self.pop()
return self | python | def truncate_to_issuer(self, cert):
issuer_index = None
for index, entry in enumerate(self):
if entry.subject == cert.issuer:
if entry.key_identifier and cert.authority_key_identifier:
if entry.key_identifier == cert.authority_key_identifier:
issuer_index = index
break
else:
issuer_index = index
break
if issuer_index is None:
raise LookupError('Unable to find the issuer of the certificate specified')
while len(self) > issuer_index + 1:
self.pop()
return self | [
"def",
"truncate_to_issuer",
"(",
"self",
",",
"cert",
")",
":",
"issuer_index",
"=",
"None",
"for",
"index",
",",
"entry",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"entry",
".",
"subject",
"==",
"cert",
".",
"issuer",
":",
"if",
"entry",
".",
... | Remove all certificates in the path after the issuer of the cert
specified, as defined by this path
:param cert:
An asn1crypto.x509.Certificate object to find the issuer of
:raises:
LookupError - when the issuer of the certificate could not be found
:return:
The current ValidationPath object, for chaining | [
"Remove",
"all",
"certificates",
"in",
"the",
"path",
"after",
"the",
"issuer",
"of",
"the",
"cert",
"specified",
"as",
"defined",
"by",
"this",
"path"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/path.py#L99-L131 |
24,740 | wbond/certvalidator | certvalidator/path.py | ValidationPath.copy | def copy(self):
"""
Creates a copy of this path
:return:
A ValidationPath object
"""
copy = self.__class__()
copy._certs = self._certs[:]
copy._cert_hashes = self._cert_hashes.copy()
return copy | python | def copy(self):
copy = self.__class__()
copy._certs = self._certs[:]
copy._cert_hashes = self._cert_hashes.copy()
return copy | [
"def",
"copy",
"(",
"self",
")",
":",
"copy",
"=",
"self",
".",
"__class__",
"(",
")",
"copy",
".",
"_certs",
"=",
"self",
".",
"_certs",
"[",
":",
"]",
"copy",
".",
"_cert_hashes",
"=",
"self",
".",
"_cert_hashes",
".",
"copy",
"(",
")",
"return",... | Creates a copy of this path
:return:
A ValidationPath object | [
"Creates",
"a",
"copy",
"of",
"this",
"path"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/path.py#L133-L144 |
24,741 | wbond/certvalidator | certvalidator/path.py | ValidationPath.pop | def pop(self):
"""
Removes the last certificate from the path
:return:
The current ValidationPath object, for chaining
"""
last_cert = self._certs.pop()
self._cert_hashes.remove(last_cert.issuer_serial)
return self | python | def pop(self):
last_cert = self._certs.pop()
self._cert_hashes.remove(last_cert.issuer_serial)
return self | [
"def",
"pop",
"(",
"self",
")",
":",
"last_cert",
"=",
"self",
".",
"_certs",
".",
"pop",
"(",
")",
"self",
".",
"_cert_hashes",
".",
"remove",
"(",
"last_cert",
".",
"issuer_serial",
")",
"return",
"self"
] | Removes the last certificate from the path
:return:
The current ValidationPath object, for chaining | [
"Removes",
"the",
"last",
"certificate",
"from",
"the",
"path"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/path.py#L146-L157 |
24,742 | wbond/certvalidator | certvalidator/crl_client.py | fetch | def fetch(cert, use_deltas=True, user_agent=None, timeout=10):
"""
Fetches the CRLs for a certificate
:param cert:
An asn1cyrpto.x509.Certificate object to get the CRL for
:param use_deltas:
A boolean indicating if delta CRLs should be fetched
:param user_agent:
The HTTP user agent to use when requesting the CRL. If None,
a default is used in the format "certvalidation 1.0.0".
:param timeout:
The number of seconds after which an HTTP request should timeout
:raises:
urllib.error.URLError/urllib2.URLError - when a URL/HTTP error occurs
socket.error - when a socket error occurs
:return:
A list asn1crypto.crl.CertificateList objects
"""
if not isinstance(cert, x509.Certificate):
raise TypeError('cert must be an instance of asn1crypto.x509.Certificate, not %s' % type_name(cert))
if user_agent is None:
user_agent = 'certvalidator %s' % __version__
elif not isinstance(user_agent, str_cls):
raise TypeError('user_agent must be a unicode string, not %s' % type_name(user_agent))
output = []
sources = cert.crl_distribution_points
if use_deltas:
sources.extend(cert.delta_crl_distribution_points)
for distribution_point in sources:
url = distribution_point.url
output.append(_grab_crl(user_agent, url, timeout))
return output | python | def fetch(cert, use_deltas=True, user_agent=None, timeout=10):
if not isinstance(cert, x509.Certificate):
raise TypeError('cert must be an instance of asn1crypto.x509.Certificate, not %s' % type_name(cert))
if user_agent is None:
user_agent = 'certvalidator %s' % __version__
elif not isinstance(user_agent, str_cls):
raise TypeError('user_agent must be a unicode string, not %s' % type_name(user_agent))
output = []
sources = cert.crl_distribution_points
if use_deltas:
sources.extend(cert.delta_crl_distribution_points)
for distribution_point in sources:
url = distribution_point.url
output.append(_grab_crl(user_agent, url, timeout))
return output | [
"def",
"fetch",
"(",
"cert",
",",
"use_deltas",
"=",
"True",
",",
"user_agent",
"=",
"None",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"not",
"isinstance",
"(",
"cert",
",",
"x509",
".",
"Certificate",
")",
":",
"raise",
"TypeError",
"(",
"'cert must ... | Fetches the CRLs for a certificate
:param cert:
An asn1cyrpto.x509.Certificate object to get the CRL for
:param use_deltas:
A boolean indicating if delta CRLs should be fetched
:param user_agent:
The HTTP user agent to use when requesting the CRL. If None,
a default is used in the format "certvalidation 1.0.0".
:param timeout:
The number of seconds after which an HTTP request should timeout
:raises:
urllib.error.URLError/urllib2.URLError - when a URL/HTTP error occurs
socket.error - when a socket error occurs
:return:
A list asn1crypto.crl.CertificateList objects | [
"Fetches",
"the",
"CRLs",
"for",
"a",
"certificate"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/crl_client.py#L11-L54 |
24,743 | wbond/certvalidator | certvalidator/crl_client.py | _grab_crl | def _grab_crl(user_agent, url, timeout):
"""
Fetches a CRL and parses it
:param user_agent:
A unicode string of the user agent to use when fetching the URL
:param url:
A unicode string of the URL to fetch the CRL from
:param timeout:
The number of seconds after which an HTTP request should timeout
:return:
An asn1crypto.crl.CertificateList object
"""
request = Request(url)
request.add_header('Accept', 'application/pkix-crl')
request.add_header('User-Agent', user_agent)
response = urlopen(request, None, timeout)
data = response.read()
if pem.detect(data):
_, _, data = pem.unarmor(data)
return crl.CertificateList.load(data) | python | def _grab_crl(user_agent, url, timeout):
request = Request(url)
request.add_header('Accept', 'application/pkix-crl')
request.add_header('User-Agent', user_agent)
response = urlopen(request, None, timeout)
data = response.read()
if pem.detect(data):
_, _, data = pem.unarmor(data)
return crl.CertificateList.load(data) | [
"def",
"_grab_crl",
"(",
"user_agent",
",",
"url",
",",
"timeout",
")",
":",
"request",
"=",
"Request",
"(",
"url",
")",
"request",
".",
"add_header",
"(",
"'Accept'",
",",
"'application/pkix-crl'",
")",
"request",
".",
"add_header",
"(",
"'User-Agent'",
","... | Fetches a CRL and parses it
:param user_agent:
A unicode string of the user agent to use when fetching the URL
:param url:
A unicode string of the URL to fetch the CRL from
:param timeout:
The number of seconds after which an HTTP request should timeout
:return:
An asn1crypto.crl.CertificateList object | [
"Fetches",
"a",
"CRL",
"and",
"parses",
"it"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/crl_client.py#L57-L80 |
24,744 | wbond/certvalidator | certvalidator/crl_client.py | fetch_certs | def fetch_certs(certificate_list, user_agent=None, timeout=10):
"""
Fetches certificates from the authority information access extension of
an asn1crypto.crl.CertificateList object and places them into the
cert registry.
:param certificate_list:
An asn1crypto.crl.CertificateList object
:param user_agent:
The HTTP user agent to use when requesting the CRL. If None,
a default is used in the format "certvalidation 1.0.0".
:param timeout:
The number of seconds after which an HTTP request should timeout
:raises:
urllib.error.URLError/urllib2.URLError - when a URL/HTTP error occurs
socket.error - when a socket error occurs
:return:
A list of any asn1crypto.x509.Certificate objects that were fetched
"""
output = []
if user_agent is None:
user_agent = 'certvalidator %s' % __version__
elif not isinstance(user_agent, str_cls):
raise TypeError('user_agent must be a unicode string, not %s' % type_name(user_agent))
for url in certificate_list.issuer_cert_urls:
request = Request(url)
request.add_header('Accept', 'application/pkix-cert,application/pkcs7-mime')
request.add_header('User-Agent', user_agent)
response = urlopen(request, None, timeout)
content_type = response.headers['Content-Type'].strip()
response_data = response.read()
if content_type == 'application/pkix-cert':
output.append(x509.Certificate.load(response_data))
elif content_type == 'application/pkcs7-mime':
signed_data = cms.SignedData.load(response_data)
if isinstance(signed_data['certificates'], cms.CertificateSet):
for cert_choice in signed_data['certificates']:
if cert_choice.name == 'certificate':
output.append(cert_choice.chosen)
else:
raise ValueError('Unknown content type of %s when fetching issuer certificate for CRL' % repr(content_type))
return output | python | def fetch_certs(certificate_list, user_agent=None, timeout=10):
output = []
if user_agent is None:
user_agent = 'certvalidator %s' % __version__
elif not isinstance(user_agent, str_cls):
raise TypeError('user_agent must be a unicode string, not %s' % type_name(user_agent))
for url in certificate_list.issuer_cert_urls:
request = Request(url)
request.add_header('Accept', 'application/pkix-cert,application/pkcs7-mime')
request.add_header('User-Agent', user_agent)
response = urlopen(request, None, timeout)
content_type = response.headers['Content-Type'].strip()
response_data = response.read()
if content_type == 'application/pkix-cert':
output.append(x509.Certificate.load(response_data))
elif content_type == 'application/pkcs7-mime':
signed_data = cms.SignedData.load(response_data)
if isinstance(signed_data['certificates'], cms.CertificateSet):
for cert_choice in signed_data['certificates']:
if cert_choice.name == 'certificate':
output.append(cert_choice.chosen)
else:
raise ValueError('Unknown content type of %s when fetching issuer certificate for CRL' % repr(content_type))
return output | [
"def",
"fetch_certs",
"(",
"certificate_list",
",",
"user_agent",
"=",
"None",
",",
"timeout",
"=",
"10",
")",
":",
"output",
"=",
"[",
"]",
"if",
"user_agent",
"is",
"None",
":",
"user_agent",
"=",
"'certvalidator %s'",
"%",
"__version__",
"elif",
"not",
... | Fetches certificates from the authority information access extension of
an asn1crypto.crl.CertificateList object and places them into the
cert registry.
:param certificate_list:
An asn1crypto.crl.CertificateList object
:param user_agent:
The HTTP user agent to use when requesting the CRL. If None,
a default is used in the format "certvalidation 1.0.0".
:param timeout:
The number of seconds after which an HTTP request should timeout
:raises:
urllib.error.URLError/urllib2.URLError - when a URL/HTTP error occurs
socket.error - when a socket error occurs
:return:
A list of any asn1crypto.x509.Certificate objects that were fetched | [
"Fetches",
"certificates",
"from",
"the",
"authority",
"information",
"access",
"extension",
"of",
"an",
"asn1crypto",
".",
"crl",
".",
"CertificateList",
"object",
"and",
"places",
"them",
"into",
"the",
"cert",
"registry",
"."
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/crl_client.py#L83-L135 |
24,745 | wbond/certvalidator | certvalidator/__init__.py | CertificateValidator.validate_usage | def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False):
"""
Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
:param key_usage:
A set of unicode strings of the required key usage purposes. Valid
values include:
- "digital_signature"
- "non_repudiation"
- "key_encipherment"
- "data_encipherment"
- "key_agreement"
- "key_cert_sign"
- "crl_sign"
- "encipher_only"
- "decipher_only"
:param extended_key_usage:
A set of unicode strings of the required extended key usage
purposes. These must be either dotted number OIDs, or one of the
following extended key usage purposes:
- "server_auth"
- "client_auth"
- "code_signing"
- "email_protection"
- "ipsec_end_system"
- "ipsec_tunnel"
- "ipsec_user"
- "time_stamping"
- "ocsp_signing"
- "wireless_access_points"
An example of a dotted number OID:
- "1.3.6.1.5.5.7.3.1"
:param extended_optional:
A bool - if the extended_key_usage extension may be ommited and still
considered valid
:raises:
certvalidator.errors.PathValidationError - when an error occurs validating the path
certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified
:return:
A certvalidator.path.ValidationPath object of the validated
certificate validation path
"""
self._validate_path()
validate_usage(
self._context,
self._certificate,
key_usage,
extended_key_usage,
extended_optional
)
return self._path | python | def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False):
self._validate_path()
validate_usage(
self._context,
self._certificate,
key_usage,
extended_key_usage,
extended_optional
)
return self._path | [
"def",
"validate_usage",
"(",
"self",
",",
"key_usage",
",",
"extended_key_usage",
"=",
"None",
",",
"extended_optional",
"=",
"False",
")",
":",
"self",
".",
"_validate_path",
"(",
")",
"validate_usage",
"(",
"self",
".",
"_context",
",",
"self",
".",
"_cer... | Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
:param key_usage:
A set of unicode strings of the required key usage purposes. Valid
values include:
- "digital_signature"
- "non_repudiation"
- "key_encipherment"
- "data_encipherment"
- "key_agreement"
- "key_cert_sign"
- "crl_sign"
- "encipher_only"
- "decipher_only"
:param extended_key_usage:
A set of unicode strings of the required extended key usage
purposes. These must be either dotted number OIDs, or one of the
following extended key usage purposes:
- "server_auth"
- "client_auth"
- "code_signing"
- "email_protection"
- "ipsec_end_system"
- "ipsec_tunnel"
- "ipsec_user"
- "time_stamping"
- "ocsp_signing"
- "wireless_access_points"
An example of a dotted number OID:
- "1.3.6.1.5.5.7.3.1"
:param extended_optional:
A bool - if the extended_key_usage extension may be ommited and still
considered valid
:raises:
certvalidator.errors.PathValidationError - when an error occurs validating the path
certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified
:return:
A certvalidator.path.ValidationPath object of the validated
certificate validation path | [
"Validates",
"the",
"certificate",
"path",
"and",
"that",
"the",
"certificate",
"is",
"valid",
"for",
"the",
"key",
"usage",
"and",
"extended",
"key",
"usage",
"purposes",
"specified",
"."
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/__init__.py#L140-L201 |
24,746 | wbond/certvalidator | certvalidator/__init__.py | CertificateValidator.validate_tls | def validate_tls(self, hostname):
"""
Validates the certificate path, that the certificate is valid for
the hostname provided and that the certificate is valid for the purpose
of a TLS connection.
:param hostname:
A unicode string of the TLS server hostname
:raises:
certvalidator.errors.PathValidationError - when an error occurs validating the path
certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname
:return:
A certvalidator.path.ValidationPath object of the validated
certificate validation path
"""
self._validate_path()
validate_tls_hostname(self._context, self._certificate, hostname)
return self._path | python | def validate_tls(self, hostname):
self._validate_path()
validate_tls_hostname(self._context, self._certificate, hostname)
return self._path | [
"def",
"validate_tls",
"(",
"self",
",",
"hostname",
")",
":",
"self",
".",
"_validate_path",
"(",
")",
"validate_tls_hostname",
"(",
"self",
".",
"_context",
",",
"self",
".",
"_certificate",
",",
"hostname",
")",
"return",
"self",
".",
"_path"
] | Validates the certificate path, that the certificate is valid for
the hostname provided and that the certificate is valid for the purpose
of a TLS connection.
:param hostname:
A unicode string of the TLS server hostname
:raises:
certvalidator.errors.PathValidationError - when an error occurs validating the path
certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname
:return:
A certvalidator.path.ValidationPath object of the validated
certificate validation path | [
"Validates",
"the",
"certificate",
"path",
"that",
"the",
"certificate",
"is",
"valid",
"for",
"the",
"hostname",
"provided",
"and",
"that",
"the",
"certificate",
"is",
"valid",
"for",
"the",
"purpose",
"of",
"a",
"TLS",
"connection",
"."
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/__init__.py#L203-L224 |
24,747 | wbond/certvalidator | certvalidator/context.py | ValidationContext.crls | def crls(self):
"""
A list of all cached asn1crypto.crl.CertificateList objects
"""
if not self._allow_fetching:
return self._crls
output = []
for issuer_serial in self._fetched_crls:
output.extend(self._fetched_crls[issuer_serial])
return output | python | def crls(self):
if not self._allow_fetching:
return self._crls
output = []
for issuer_serial in self._fetched_crls:
output.extend(self._fetched_crls[issuer_serial])
return output | [
"def",
"crls",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_allow_fetching",
":",
"return",
"self",
".",
"_crls",
"output",
"=",
"[",
"]",
"for",
"issuer_serial",
"in",
"self",
".",
"_fetched_crls",
":",
"output",
".",
"extend",
"(",
"self",
".",... | A list of all cached asn1crypto.crl.CertificateList objects | [
"A",
"list",
"of",
"all",
"cached",
"asn1crypto",
".",
"crl",
".",
"CertificateList",
"objects"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/context.py#L367-L378 |
24,748 | wbond/certvalidator | certvalidator/context.py | ValidationContext.ocsps | def ocsps(self):
"""
A list of all cached asn1crypto.ocsp.OCSPResponse objects
"""
if not self._allow_fetching:
return self._ocsps
output = []
for issuer_serial in self._fetched_ocsps:
output.extend(self._fetched_ocsps[issuer_serial])
return output | python | def ocsps(self):
if not self._allow_fetching:
return self._ocsps
output = []
for issuer_serial in self._fetched_ocsps:
output.extend(self._fetched_ocsps[issuer_serial])
return output | [
"def",
"ocsps",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_allow_fetching",
":",
"return",
"self",
".",
"_ocsps",
"output",
"=",
"[",
"]",
"for",
"issuer_serial",
"in",
"self",
".",
"_fetched_ocsps",
":",
"output",
".",
"extend",
"(",
"self",
"... | A list of all cached asn1crypto.ocsp.OCSPResponse objects | [
"A",
"list",
"of",
"all",
"cached",
"asn1crypto",
".",
"ocsp",
".",
"OCSPResponse",
"objects"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/context.py#L381-L392 |
24,749 | wbond/certvalidator | certvalidator/context.py | ValidationContext._extract_ocsp_certs | def _extract_ocsp_certs(self, ocsp_response):
"""
Extracts any certificates included with an OCSP response and adds them
to the certificate registry
:param ocsp_response:
An asn1crypto.ocsp.OCSPResponse object to look for certs inside of
"""
status = ocsp_response['response_status'].native
if status == 'successful':
response_bytes = ocsp_response['response_bytes']
if response_bytes['response_type'].native == 'basic_ocsp_response':
response = response_bytes['response'].parsed
if response['certs']:
for other_cert in response['certs']:
if self.certificate_registry.add_other_cert(other_cert):
self._revocation_certs[other_cert.issuer_serial] = other_cert | python | def _extract_ocsp_certs(self, ocsp_response):
status = ocsp_response['response_status'].native
if status == 'successful':
response_bytes = ocsp_response['response_bytes']
if response_bytes['response_type'].native == 'basic_ocsp_response':
response = response_bytes['response'].parsed
if response['certs']:
for other_cert in response['certs']:
if self.certificate_registry.add_other_cert(other_cert):
self._revocation_certs[other_cert.issuer_serial] = other_cert | [
"def",
"_extract_ocsp_certs",
"(",
"self",
",",
"ocsp_response",
")",
":",
"status",
"=",
"ocsp_response",
"[",
"'response_status'",
"]",
".",
"native",
"if",
"status",
"==",
"'successful'",
":",
"response_bytes",
"=",
"ocsp_response",
"[",
"'response_bytes'",
"]"... | Extracts any certificates included with an OCSP response and adds them
to the certificate registry
:param ocsp_response:
An asn1crypto.ocsp.OCSPResponse object to look for certs inside of | [
"Extracts",
"any",
"certificates",
"included",
"with",
"an",
"OCSP",
"response",
"and",
"adds",
"them",
"to",
"the",
"certificate",
"registry"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/context.py#L516-L533 |
24,750 | wbond/certvalidator | certvalidator/context.py | ValidationContext.check_validation | def check_validation(self, cert):
"""
Checks to see if a certificate has been validated, and if so, returns
the ValidationPath used to validate it.
:param cert:
An asn1crypto.x509.Certificate object
:return:
None if not validated, or a certvalidator.path.ValidationPath
object of the validation path
"""
# CA certs are automatically trusted since they are from the trust list
if self.certificate_registry.is_ca(cert) and cert.signature not in self._validate_map:
self._validate_map[cert.signature] = ValidationPath(cert)
return self._validate_map.get(cert.signature) | python | def check_validation(self, cert):
# CA certs are automatically trusted since they are from the trust list
if self.certificate_registry.is_ca(cert) and cert.signature not in self._validate_map:
self._validate_map[cert.signature] = ValidationPath(cert)
return self._validate_map.get(cert.signature) | [
"def",
"check_validation",
"(",
"self",
",",
"cert",
")",
":",
"# CA certs are automatically trusted since they are from the trust list",
"if",
"self",
".",
"certificate_registry",
".",
"is_ca",
"(",
"cert",
")",
"and",
"cert",
".",
"signature",
"not",
"in",
"self",
... | Checks to see if a certificate has been validated, and if so, returns
the ValidationPath used to validate it.
:param cert:
An asn1crypto.x509.Certificate object
:return:
None if not validated, or a certvalidator.path.ValidationPath
object of the validation path | [
"Checks",
"to",
"see",
"if",
"a",
"certificate",
"has",
"been",
"validated",
"and",
"if",
"so",
"returns",
"the",
"ValidationPath",
"used",
"to",
"validate",
"it",
"."
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/context.py#L550-L567 |
24,751 | wbond/certvalidator | certvalidator/context.py | ValidationContext.clear_validation | def clear_validation(self, cert):
"""
Clears the record that a certificate has been validated
:param cert:
An ans1crypto.x509.Certificate object
"""
if cert.signature in self._validate_map:
del self._validate_map[cert.signature] | python | def clear_validation(self, cert):
if cert.signature in self._validate_map:
del self._validate_map[cert.signature] | [
"def",
"clear_validation",
"(",
"self",
",",
"cert",
")",
":",
"if",
"cert",
".",
"signature",
"in",
"self",
".",
"_validate_map",
":",
"del",
"self",
".",
"_validate_map",
"[",
"cert",
".",
"signature",
"]"
] | Clears the record that a certificate has been validated
:param cert:
An ans1crypto.x509.Certificate object | [
"Clears",
"the",
"record",
"that",
"a",
"certificate",
"has",
"been",
"validated"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/context.py#L569-L578 |
24,752 | wbond/certvalidator | certvalidator/validate.py | _find_cert_in_list | def _find_cert_in_list(cert, issuer, certificate_list, crl_issuer):
"""
Looks for a cert in the list of revoked certificates
:param cert:
An asn1crypto.x509.Certificate object of the cert being checked
:param issuer:
An asn1crypto.x509.Certificate object of the cert issuer
:param certificate_list:
An ans1crypto.crl.CertificateList object to look in for the cert
:param crl_issuer:
An asn1crypto.x509.Certificate object of the CRL issuer
:return:
A tuple of (None, None) if not present, otherwise a tuple of
(asn1crypto.x509.Time object, asn1crypto.crl.CRLReason object)
representing the date/time the object was revoked and why
"""
revoked_certificates = certificate_list['tbs_cert_list']['revoked_certificates']
cert_serial = cert.serial_number
issuer_name = issuer.subject
known_extensions = set([
'crl_reason',
'hold_instruction_code',
'invalidity_date',
'certificate_issuer'
])
last_issuer_name = crl_issuer.subject
for revoked_cert in revoked_certificates:
# If any unknown critical extensions, the entry can not be used
if revoked_cert.critical_extensions - known_extensions:
raise NotImplementedError()
if revoked_cert.issuer_name and revoked_cert.issuer_name != last_issuer_name:
last_issuer_name = revoked_cert.issuer_name
if last_issuer_name != issuer_name:
continue
if revoked_cert['user_certificate'].native != cert_serial:
continue
if not revoked_cert.crl_reason_value:
crl_reason = crl.CRLReason('unspecified')
else:
crl_reason = revoked_cert.crl_reason_value
return (revoked_cert['revocation_date'], crl_reason)
return (None, None) | python | def _find_cert_in_list(cert, issuer, certificate_list, crl_issuer):
revoked_certificates = certificate_list['tbs_cert_list']['revoked_certificates']
cert_serial = cert.serial_number
issuer_name = issuer.subject
known_extensions = set([
'crl_reason',
'hold_instruction_code',
'invalidity_date',
'certificate_issuer'
])
last_issuer_name = crl_issuer.subject
for revoked_cert in revoked_certificates:
# If any unknown critical extensions, the entry can not be used
if revoked_cert.critical_extensions - known_extensions:
raise NotImplementedError()
if revoked_cert.issuer_name and revoked_cert.issuer_name != last_issuer_name:
last_issuer_name = revoked_cert.issuer_name
if last_issuer_name != issuer_name:
continue
if revoked_cert['user_certificate'].native != cert_serial:
continue
if not revoked_cert.crl_reason_value:
crl_reason = crl.CRLReason('unspecified')
else:
crl_reason = revoked_cert.crl_reason_value
return (revoked_cert['revocation_date'], crl_reason)
return (None, None) | [
"def",
"_find_cert_in_list",
"(",
"cert",
",",
"issuer",
",",
"certificate_list",
",",
"crl_issuer",
")",
":",
"revoked_certificates",
"=",
"certificate_list",
"[",
"'tbs_cert_list'",
"]",
"[",
"'revoked_certificates'",
"]",
"cert_serial",
"=",
"cert",
".",
"serial_... | Looks for a cert in the list of revoked certificates
:param cert:
An asn1crypto.x509.Certificate object of the cert being checked
:param issuer:
An asn1crypto.x509.Certificate object of the cert issuer
:param certificate_list:
An ans1crypto.crl.CertificateList object to look in for the cert
:param crl_issuer:
An asn1crypto.x509.Certificate object of the CRL issuer
:return:
A tuple of (None, None) if not present, otherwise a tuple of
(asn1crypto.x509.Time object, asn1crypto.crl.CRLReason object)
representing the date/time the object was revoked and why | [
"Looks",
"for",
"a",
"cert",
"in",
"the",
"list",
"of",
"revoked",
"certificates"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/validate.py#L1784-L1839 |
24,753 | wbond/certvalidator | certvalidator/validate.py | PolicyTreeRoot.add_child | def add_child(self, valid_policy, qualifier_set, expected_policy_set):
"""
Creates a new PolicyTreeNode as a child of this node
:param valid_policy:
A unicode string of a policy name or OID
:param qualifier_set:
An instance of asn1crypto.x509.PolicyQualifierInfos
:param expected_policy_set:
A set of unicode strings containing policy names or OIDs
"""
child = PolicyTreeNode(valid_policy, qualifier_set, expected_policy_set)
child.parent = self
self.children.append(child) | python | def add_child(self, valid_policy, qualifier_set, expected_policy_set):
child = PolicyTreeNode(valid_policy, qualifier_set, expected_policy_set)
child.parent = self
self.children.append(child) | [
"def",
"add_child",
"(",
"self",
",",
"valid_policy",
",",
"qualifier_set",
",",
"expected_policy_set",
")",
":",
"child",
"=",
"PolicyTreeNode",
"(",
"valid_policy",
",",
"qualifier_set",
",",
"expected_policy_set",
")",
"child",
".",
"parent",
"=",
"self",
"se... | Creates a new PolicyTreeNode as a child of this node
:param valid_policy:
A unicode string of a policy name or OID
:param qualifier_set:
An instance of asn1crypto.x509.PolicyQualifierInfos
:param expected_policy_set:
A set of unicode strings containing policy names or OIDs | [
"Creates",
"a",
"new",
"PolicyTreeNode",
"as",
"a",
"child",
"of",
"this",
"node"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/validate.py#L1871-L1887 |
24,754 | wbond/certvalidator | certvalidator/validate.py | PolicyTreeRoot.at_depth | def at_depth(self, depth):
"""
Returns a generator yielding all nodes in the tree at a specific depth
:param depth:
An integer >= 0 of the depth of nodes to yield
:return:
A generator yielding PolicyTreeNode objects
"""
for child in list(self.children):
if depth == 0:
yield child
else:
for grandchild in child.at_depth(depth - 1):
yield grandchild | python | def at_depth(self, depth):
for child in list(self.children):
if depth == 0:
yield child
else:
for grandchild in child.at_depth(depth - 1):
yield grandchild | [
"def",
"at_depth",
"(",
"self",
",",
"depth",
")",
":",
"for",
"child",
"in",
"list",
"(",
"self",
".",
"children",
")",
":",
"if",
"depth",
"==",
"0",
":",
"yield",
"child",
"else",
":",
"for",
"grandchild",
"in",
"child",
".",
"at_depth",
"(",
"d... | Returns a generator yielding all nodes in the tree at a specific depth
:param depth:
An integer >= 0 of the depth of nodes to yield
:return:
A generator yielding PolicyTreeNode objects | [
"Returns",
"a",
"generator",
"yielding",
"all",
"nodes",
"in",
"the",
"tree",
"at",
"a",
"specific",
"depth"
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/validate.py#L1899-L1915 |
24,755 | wbond/certvalidator | certvalidator/validate.py | PolicyTreeRoot.walk_up | def walk_up(self, depth):
"""
Returns a generator yielding all nodes in the tree at a specific depth,
or above. Yields nodes starting with leaves and traversing up to the
root.
:param depth:
An integer >= 0 of the depth of nodes to walk up from
:return:
A generator yielding PolicyTreeNode objects
"""
for child in list(self.children):
if depth != 0:
for grandchild in child.walk_up(depth - 1):
yield grandchild
yield child | python | def walk_up(self, depth):
for child in list(self.children):
if depth != 0:
for grandchild in child.walk_up(depth - 1):
yield grandchild
yield child | [
"def",
"walk_up",
"(",
"self",
",",
"depth",
")",
":",
"for",
"child",
"in",
"list",
"(",
"self",
".",
"children",
")",
":",
"if",
"depth",
"!=",
"0",
":",
"for",
"grandchild",
"in",
"child",
".",
"walk_up",
"(",
"depth",
"-",
"1",
")",
":",
"yie... | Returns a generator yielding all nodes in the tree at a specific depth,
or above. Yields nodes starting with leaves and traversing up to the
root.
:param depth:
An integer >= 0 of the depth of nodes to walk up from
:return:
A generator yielding PolicyTreeNode objects | [
"Returns",
"a",
"generator",
"yielding",
"all",
"nodes",
"in",
"the",
"tree",
"at",
"a",
"specific",
"depth",
"or",
"above",
".",
"Yields",
"nodes",
"starting",
"with",
"leaves",
"and",
"traversing",
"up",
"to",
"the",
"root",
"."
] | c62233a713bcc36963e9d82323ec8d84f8e01485 | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/validate.py#L1917-L1934 |
24,756 | aio-libs/aiomcache | aiomcache/pool.py | MemcachePool.clear | def clear(self):
"""Clear pool connections."""
while not self._pool.empty():
conn = yield from self._pool.get()
self._do_close(conn) | python | def clear(self):
while not self._pool.empty():
conn = yield from self._pool.get()
self._do_close(conn) | [
"def",
"clear",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_pool",
".",
"empty",
"(",
")",
":",
"conn",
"=",
"yield",
"from",
"self",
".",
"_pool",
".",
"get",
"(",
")",
"self",
".",
"_do_close",
"(",
"conn",
")"
] | Clear pool connections. | [
"Clear",
"pool",
"connections",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/pool.py#L23-L27 |
24,757 | aio-libs/aiomcache | aiomcache/pool.py | MemcachePool.acquire | def acquire(self):
"""Acquire connection from the pool, or spawn new one
if pool maxsize permits.
:return: ``tuple`` (reader, writer)
"""
while self.size() == 0 or self.size() < self._minsize:
_conn = yield from self._create_new_conn()
if _conn is None:
break
self._pool.put_nowait(_conn)
conn = None
while not conn:
_conn = yield from self._pool.get()
if _conn.reader.at_eof() or _conn.reader.exception():
self._do_close(_conn)
conn = yield from self._create_new_conn()
else:
conn = _conn
self._in_use.add(conn)
return conn | python | def acquire(self):
while self.size() == 0 or self.size() < self._minsize:
_conn = yield from self._create_new_conn()
if _conn is None:
break
self._pool.put_nowait(_conn)
conn = None
while not conn:
_conn = yield from self._pool.get()
if _conn.reader.at_eof() or _conn.reader.exception():
self._do_close(_conn)
conn = yield from self._create_new_conn()
else:
conn = _conn
self._in_use.add(conn)
return conn | [
"def",
"acquire",
"(",
"self",
")",
":",
"while",
"self",
".",
"size",
"(",
")",
"==",
"0",
"or",
"self",
".",
"size",
"(",
")",
"<",
"self",
".",
"_minsize",
":",
"_conn",
"=",
"yield",
"from",
"self",
".",
"_create_new_conn",
"(",
")",
"if",
"_... | Acquire connection from the pool, or spawn new one
if pool maxsize permits.
:return: ``tuple`` (reader, writer) | [
"Acquire",
"connection",
"from",
"the",
"pool",
"or",
"spawn",
"new",
"one",
"if",
"pool",
"maxsize",
"permits",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/pool.py#L34-L56 |
24,758 | aio-libs/aiomcache | aiomcache/pool.py | MemcachePool.release | def release(self, conn):
"""Releases connection back to the pool.
:param conn: ``namedtuple`` (reader, writer)
"""
self._in_use.remove(conn)
if conn.reader.at_eof() or conn.reader.exception():
self._do_close(conn)
else:
self._pool.put_nowait(conn) | python | def release(self, conn):
self._in_use.remove(conn)
if conn.reader.at_eof() or conn.reader.exception():
self._do_close(conn)
else:
self._pool.put_nowait(conn) | [
"def",
"release",
"(",
"self",
",",
"conn",
")",
":",
"self",
".",
"_in_use",
".",
"remove",
"(",
"conn",
")",
"if",
"conn",
".",
"reader",
".",
"at_eof",
"(",
")",
"or",
"conn",
".",
"reader",
".",
"exception",
"(",
")",
":",
"self",
".",
"_do_c... | Releases connection back to the pool.
:param conn: ``namedtuple`` (reader, writer) | [
"Releases",
"connection",
"back",
"to",
"the",
"pool",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/pool.py#L58-L67 |
24,759 | aio-libs/aiomcache | aiomcache/client.py | Client.get | def get(self, conn, key, default=None):
"""Gets a single value from the server.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, is the data for this specified key.
"""
values, _ = yield from self._multi_get(conn, key)
return values.get(key, default) | python | def get(self, conn, key, default=None):
values, _ = yield from self._multi_get(conn, key)
return values.get(key, default) | [
"def",
"get",
"(",
"self",
",",
"conn",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"values",
",",
"_",
"=",
"yield",
"from",
"self",
".",
"_multi_get",
"(",
"conn",
",",
"key",
")",
"return",
"values",
".",
"get",
"(",
"key",
",",
"defaul... | Gets a single value from the server.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, is the data for this specified key. | [
"Gets",
"a",
"single",
"value",
"from",
"the",
"server",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L142-L150 |
24,760 | aio-libs/aiomcache | aiomcache/client.py | Client.gets | def gets(self, conn, key, default=None):
"""Gets a single value from the server together with the cas token.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, ``bytes tuple with the value and the cas
"""
values, cas_tokens = yield from self._multi_get(
conn, key, with_cas=True)
return values.get(key, default), cas_tokens.get(key) | python | def gets(self, conn, key, default=None):
values, cas_tokens = yield from self._multi_get(
conn, key, with_cas=True)
return values.get(key, default), cas_tokens.get(key) | [
"def",
"gets",
"(",
"self",
",",
"conn",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"values",
",",
"cas_tokens",
"=",
"yield",
"from",
"self",
".",
"_multi_get",
"(",
"conn",
",",
"key",
",",
"with_cas",
"=",
"True",
")",
"return",
"values",
... | Gets a single value from the server together with the cas token.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, ``bytes tuple with the value and the cas | [
"Gets",
"a",
"single",
"value",
"from",
"the",
"server",
"together",
"with",
"the",
"cas",
"token",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L153-L162 |
24,761 | aio-libs/aiomcache | aiomcache/client.py | Client.multi_get | def multi_get(self, conn, *keys):
"""Takes a list of keys and returns a list of values.
:param keys: ``list`` keys for the item being fetched.
:return: ``list`` of values for the specified keys.
:raises:``ValidationException``, ``ClientException``,
and socket errors
"""
values, _ = yield from self._multi_get(conn, *keys)
return tuple(values.get(key) for key in keys) | python | def multi_get(self, conn, *keys):
values, _ = yield from self._multi_get(conn, *keys)
return tuple(values.get(key) for key in keys) | [
"def",
"multi_get",
"(",
"self",
",",
"conn",
",",
"*",
"keys",
")",
":",
"values",
",",
"_",
"=",
"yield",
"from",
"self",
".",
"_multi_get",
"(",
"conn",
",",
"*",
"keys",
")",
"return",
"tuple",
"(",
"values",
".",
"get",
"(",
"key",
")",
"for... | Takes a list of keys and returns a list of values.
:param keys: ``list`` keys for the item being fetched.
:return: ``list`` of values for the specified keys.
:raises:``ValidationException``, ``ClientException``,
and socket errors | [
"Takes",
"a",
"list",
"of",
"keys",
"and",
"returns",
"a",
"list",
"of",
"values",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L165-L174 |
24,762 | aio-libs/aiomcache | aiomcache/client.py | Client.stats | def stats(self, conn, args=None):
"""Runs a stats command on the server."""
# req - stats [additional args]\r\n
# resp - STAT <name> <value>\r\n (one per result)
# END\r\n
if args is None:
args = b''
conn.writer.write(b''.join((b'stats ', args, b'\r\n')))
result = {}
resp = yield from conn.reader.readline()
while resp != b'END\r\n':
terms = resp.split()
if len(terms) == 2 and terms[0] == b'STAT':
result[terms[1]] = None
elif len(terms) == 3 and terms[0] == b'STAT':
result[terms[1]] = terms[2]
elif len(terms) >= 3 and terms[0] == b'STAT':
result[terms[1]] = b' '.join(terms[2:])
else:
raise ClientException('stats failed', resp)
resp = yield from conn.reader.readline()
return result | python | def stats(self, conn, args=None):
# req - stats [additional args]\r\n
# resp - STAT <name> <value>\r\n (one per result)
# END\r\n
if args is None:
args = b''
conn.writer.write(b''.join((b'stats ', args, b'\r\n')))
result = {}
resp = yield from conn.reader.readline()
while resp != b'END\r\n':
terms = resp.split()
if len(terms) == 2 and terms[0] == b'STAT':
result[terms[1]] = None
elif len(terms) == 3 and terms[0] == b'STAT':
result[terms[1]] = terms[2]
elif len(terms) >= 3 and terms[0] == b'STAT':
result[terms[1]] = b' '.join(terms[2:])
else:
raise ClientException('stats failed', resp)
resp = yield from conn.reader.readline()
return result | [
"def",
"stats",
"(",
"self",
",",
"conn",
",",
"args",
"=",
"None",
")",
":",
"# req - stats [additional args]\\r\\n",
"# resp - STAT <name> <value>\\r\\n (one per result)",
"# END\\r\\n",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"b''",
"conn",
".",
"wr... | Runs a stats command on the server. | [
"Runs",
"a",
"stats",
"command",
"on",
"the",
"server",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L177-L204 |
24,763 | aio-libs/aiomcache | aiomcache/client.py | Client.append | def append(self, conn, key, value, exptime=0):
"""Add data to an existing key after existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
flags = 0 # TODO: fix when exception removed
return (yield from self._storage_command(
conn, b'append', key, value, flags, exptime)) | python | def append(self, conn, key, value, exptime=0):
flags = 0 # TODO: fix when exception removed
return (yield from self._storage_command(
conn, b'append', key, value, flags, exptime)) | [
"def",
"append",
"(",
"self",
",",
"conn",
",",
"key",
",",
"value",
",",
"exptime",
"=",
"0",
")",
":",
"flags",
"=",
"0",
"# TODO: fix when exception removed",
"return",
"(",
"yield",
"from",
"self",
".",
"_storage_command",
"(",
"conn",
",",
"b'append'"... | Add data to an existing key after existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success. | [
"Add",
"data",
"to",
"an",
"existing",
"key",
"after",
"existing",
"data"
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L305-L316 |
24,764 | aio-libs/aiomcache | aiomcache/client.py | Client.prepend | def prepend(self, conn, key, value, exptime=0):
"""Add data to an existing key before existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
flags = 0 # TODO: fix when exception removed
return (yield from self._storage_command(
conn, b'prepend', key, value, flags, exptime)) | python | def prepend(self, conn, key, value, exptime=0):
flags = 0 # TODO: fix when exception removed
return (yield from self._storage_command(
conn, b'prepend', key, value, flags, exptime)) | [
"def",
"prepend",
"(",
"self",
",",
"conn",
",",
"key",
",",
"value",
",",
"exptime",
"=",
"0",
")",
":",
"flags",
"=",
"0",
"# TODO: fix when exception removed",
"return",
"(",
"yield",
"from",
"self",
".",
"_storage_command",
"(",
"conn",
",",
"b'prepend... | Add data to an existing key before existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success. | [
"Add",
"data",
"to",
"an",
"existing",
"key",
"before",
"existing",
"data"
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L319-L330 |
24,765 | aio-libs/aiomcache | aiomcache/client.py | Client.incr | def incr(self, conn, key, increment=1):
"""Command is used to change data for some item in-place,
incrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param increment: ``int``, is the amount by which the client
wants to increase the item.
:return: ``int``, new value of the item's data,
after the increment or ``None`` to indicate the item with
this value was not found
"""
assert self._validate_key(key)
resp = yield from self._incr_decr(
conn, b'incr', key, increment)
return resp | python | def incr(self, conn, key, increment=1):
assert self._validate_key(key)
resp = yield from self._incr_decr(
conn, b'incr', key, increment)
return resp | [
"def",
"incr",
"(",
"self",
",",
"conn",
",",
"key",
",",
"increment",
"=",
"1",
")",
":",
"assert",
"self",
".",
"_validate_key",
"(",
"key",
")",
"resp",
"=",
"yield",
"from",
"self",
".",
"_incr_decr",
"(",
"conn",
",",
"b'incr'",
",",
"key",
",... | Command is used to change data for some item in-place,
incrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param increment: ``int``, is the amount by which the client
wants to increase the item.
:return: ``int``, new value of the item's data,
after the increment or ``None`` to indicate the item with
this value was not found | [
"Command",
"is",
"used",
"to",
"change",
"data",
"for",
"some",
"item",
"in",
"-",
"place",
"incrementing",
"it",
".",
"The",
"data",
"for",
"the",
"item",
"is",
"treated",
"as",
"decimal",
"representation",
"of",
"a",
"64",
"-",
"bit",
"unsigned",
"inte... | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L343-L359 |
24,766 | aio-libs/aiomcache | aiomcache/client.py | Client.decr | def decr(self, conn, key, decrement=1):
"""Command is used to change data for some item in-place,
decrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param decrement: ``int``, is the amount by which the client
wants to decrease the item.
:return: ``int`` new value of the item's data,
after the increment or ``None`` to indicate the item with
this value was not found
"""
assert self._validate_key(key)
resp = yield from self._incr_decr(
conn, b'decr', key, decrement)
return resp | python | def decr(self, conn, key, decrement=1):
assert self._validate_key(key)
resp = yield from self._incr_decr(
conn, b'decr', key, decrement)
return resp | [
"def",
"decr",
"(",
"self",
",",
"conn",
",",
"key",
",",
"decrement",
"=",
"1",
")",
":",
"assert",
"self",
".",
"_validate_key",
"(",
"key",
")",
"resp",
"=",
"yield",
"from",
"self",
".",
"_incr_decr",
"(",
"conn",
",",
"b'decr'",
",",
"key",
",... | Command is used to change data for some item in-place,
decrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param decrement: ``int``, is the amount by which the client
wants to decrease the item.
:return: ``int`` new value of the item's data,
after the increment or ``None`` to indicate the item with
this value was not found | [
"Command",
"is",
"used",
"to",
"change",
"data",
"for",
"some",
"item",
"in",
"-",
"place",
"decrementing",
"it",
".",
"The",
"data",
"for",
"the",
"item",
"is",
"treated",
"as",
"decimal",
"representation",
"of",
"a",
"64",
"-",
"bit",
"unsigned",
"inte... | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L362-L378 |
24,767 | aio-libs/aiomcache | aiomcache/client.py | Client.touch | def touch(self, conn, key, exptime):
"""The command is used to update the expiration time of
an existing item without fetching it.
:param key: ``bytes``, is the key to update expiration time
:param exptime: ``int``, is expiration time. This replaces the existing
expiration time.
:return: ``bool``, True in case of success.
"""
assert self._validate_key(key)
_cmd = b' '.join([b'touch', key, str(exptime).encode('utf-8')])
cmd = _cmd + b'\r\n'
resp = yield from self._execute_simple_command(conn, cmd)
if resp not in (const.TOUCHED, const.NOT_FOUND):
raise ClientException('Memcached touch failed', resp)
return resp == const.TOUCHED | python | def touch(self, conn, key, exptime):
assert self._validate_key(key)
_cmd = b' '.join([b'touch', key, str(exptime).encode('utf-8')])
cmd = _cmd + b'\r\n'
resp = yield from self._execute_simple_command(conn, cmd)
if resp not in (const.TOUCHED, const.NOT_FOUND):
raise ClientException('Memcached touch failed', resp)
return resp == const.TOUCHED | [
"def",
"touch",
"(",
"self",
",",
"conn",
",",
"key",
",",
"exptime",
")",
":",
"assert",
"self",
".",
"_validate_key",
"(",
"key",
")",
"_cmd",
"=",
"b' '",
".",
"join",
"(",
"[",
"b'touch'",
",",
"key",
",",
"str",
"(",
"exptime",
")",
".",
"en... | The command is used to update the expiration time of
an existing item without fetching it.
:param key: ``bytes``, is the key to update expiration time
:param exptime: ``int``, is expiration time. This replaces the existing
expiration time.
:return: ``bool``, True in case of success. | [
"The",
"command",
"is",
"used",
"to",
"update",
"the",
"expiration",
"time",
"of",
"an",
"existing",
"item",
"without",
"fetching",
"it",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L381-L397 |
24,768 | aio-libs/aiomcache | aiomcache/client.py | Client.version | def version(self, conn):
"""Current version of the server.
:return: ``bytes``, memcached version for current the server.
"""
command = b'version\r\n'
response = yield from self._execute_simple_command(
conn, command)
if not response.startswith(const.VERSION):
raise ClientException('Memcached version failed', response)
version, number = response.split()
return number | python | def version(self, conn):
command = b'version\r\n'
response = yield from self._execute_simple_command(
conn, command)
if not response.startswith(const.VERSION):
raise ClientException('Memcached version failed', response)
version, number = response.split()
return number | [
"def",
"version",
"(",
"self",
",",
"conn",
")",
":",
"command",
"=",
"b'version\\r\\n'",
"response",
"=",
"yield",
"from",
"self",
".",
"_execute_simple_command",
"(",
"conn",
",",
"command",
")",
"if",
"not",
"response",
".",
"startswith",
"(",
"const",
... | Current version of the server.
:return: ``bytes``, memcached version for current the server. | [
"Current",
"version",
"of",
"the",
"server",
"."
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L400-L412 |
24,769 | aio-libs/aiomcache | aiomcache/client.py | Client.flush_all | def flush_all(self, conn):
"""Its effect is to invalidate all existing items immediately"""
command = b'flush_all\r\n'
response = yield from self._execute_simple_command(
conn, command)
if const.OK != response:
raise ClientException('Memcached flush_all failed', response) | python | def flush_all(self, conn):
command = b'flush_all\r\n'
response = yield from self._execute_simple_command(
conn, command)
if const.OK != response:
raise ClientException('Memcached flush_all failed', response) | [
"def",
"flush_all",
"(",
"self",
",",
"conn",
")",
":",
"command",
"=",
"b'flush_all\\r\\n'",
"response",
"=",
"yield",
"from",
"self",
".",
"_execute_simple_command",
"(",
"conn",
",",
"command",
")",
"if",
"const",
".",
"OK",
"!=",
"response",
":",
"rais... | Its effect is to invalidate all existing items immediately | [
"Its",
"effect",
"is",
"to",
"invalidate",
"all",
"existing",
"items",
"immediately"
] | 75d44b201aea91bc2856b10940922d5ebfbfcd7b | https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L415-L422 |
24,770 | python273/telegraph | telegraph/api.py | Telegraph.create_account | def create_account(self, short_name, author_name=None, author_url=None,
replace_token=True):
""" Create a new Telegraph account
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
Displayed to the user above the "Edit/Publish"
button on Telegra.ph, other users don't see this name
:param author_name: Default author name used when creating new articles
:param author_url: Default profile link, opened when users click on the
author's name below the title. Can be any link,
not necessarily to a Telegram profile or channels
:param replace_token: Replaces current token to a new user's token
"""
response = self._telegraph.method('createAccount', values={
'short_name': short_name,
'author_name': author_name,
'author_url': author_url
})
if replace_token:
self._telegraph.access_token = response.get('access_token')
return response | python | def create_account(self, short_name, author_name=None, author_url=None,
replace_token=True):
response = self._telegraph.method('createAccount', values={
'short_name': short_name,
'author_name': author_name,
'author_url': author_url
})
if replace_token:
self._telegraph.access_token = response.get('access_token')
return response | [
"def",
"create_account",
"(",
"self",
",",
"short_name",
",",
"author_name",
"=",
"None",
",",
"author_url",
"=",
"None",
",",
"replace_token",
"=",
"True",
")",
":",
"response",
"=",
"self",
".",
"_telegraph",
".",
"method",
"(",
"'createAccount'",
",",
"... | Create a new Telegraph account
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
Displayed to the user above the "Edit/Publish"
button on Telegra.ph, other users don't see this name
:param author_name: Default author name used when creating new articles
:param author_url: Default profile link, opened when users click on the
author's name below the title. Can be any link,
not necessarily to a Telegram profile or channels
:param replace_token: Replaces current token to a new user's token | [
"Create",
"a",
"new",
"Telegraph",
"account"
] | 6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc | https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L57-L84 |
24,771 | python273/telegraph | telegraph/api.py | Telegraph.edit_account_info | def edit_account_info(self, short_name=None, author_name=None,
author_url=None):
""" Update information about a Telegraph account.
Pass only the parameters that you want to edit
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
Displayed to the user above the "Edit/Publish"
button on Telegra.ph, other users don't see this name
:param author_name: Default author name used when creating new articles
:param author_url: Default profile link, opened when users click on the
author's name below the title. Can be any link,
not necessarily to a Telegram profile or channels
"""
return self._telegraph.method('editAccountInfo', values={
'short_name': short_name,
'author_name': author_name,
'author_url': author_url
}) | python | def edit_account_info(self, short_name=None, author_name=None,
author_url=None):
return self._telegraph.method('editAccountInfo', values={
'short_name': short_name,
'author_name': author_name,
'author_url': author_url
}) | [
"def",
"edit_account_info",
"(",
"self",
",",
"short_name",
"=",
"None",
",",
"author_name",
"=",
"None",
",",
"author_url",
"=",
"None",
")",
":",
"return",
"self",
".",
"_telegraph",
".",
"method",
"(",
"'editAccountInfo'",
",",
"values",
"=",
"{",
"'sho... | Update information about a Telegraph account.
Pass only the parameters that you want to edit
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
Displayed to the user above the "Edit/Publish"
button on Telegra.ph, other users don't see this name
:param author_name: Default author name used when creating new articles
:param author_url: Default profile link, opened when users click on the
author's name below the title. Can be any link,
not necessarily to a Telegram profile or channels | [
"Update",
"information",
"about",
"a",
"Telegraph",
"account",
".",
"Pass",
"only",
"the",
"parameters",
"that",
"you",
"want",
"to",
"edit"
] | 6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc | https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L86-L107 |
24,772 | python273/telegraph | telegraph/api.py | Telegraph.revoke_access_token | def revoke_access_token(self):
""" Revoke access_token and generate a new one, for example,
if the user would like to reset all connected sessions, or
you have reasons to believe the token was compromised.
On success, returns dict with new access_token and auth_url fields
"""
response = self._telegraph.method('revokeAccessToken')
self._telegraph.access_token = response.get('access_token')
return response | python | def revoke_access_token(self):
response = self._telegraph.method('revokeAccessToken')
self._telegraph.access_token = response.get('access_token')
return response | [
"def",
"revoke_access_token",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_telegraph",
".",
"method",
"(",
"'revokeAccessToken'",
")",
"self",
".",
"_telegraph",
".",
"access_token",
"=",
"response",
".",
"get",
"(",
"'access_token'",
")",
"return",
... | Revoke access_token and generate a new one, for example,
if the user would like to reset all connected sessions, or
you have reasons to believe the token was compromised.
On success, returns dict with new access_token and auth_url fields | [
"Revoke",
"access_token",
"and",
"generate",
"a",
"new",
"one",
"for",
"example",
"if",
"the",
"user",
"would",
"like",
"to",
"reset",
"all",
"connected",
"sessions",
"or",
"you",
"have",
"reasons",
"to",
"believe",
"the",
"token",
"was",
"compromised",
".",... | 6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc | https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L109-L120 |
24,773 | python273/telegraph | telegraph/api.py | Telegraph.get_page | def get_page(self, path, return_content=True, return_html=True):
""" Get a Telegraph page
:param path: Path to the Telegraph page (in the format Title-12-31,
i.e. everything that comes after https://telegra.ph/)
:param return_content: If true, content field will be returned
:param return_html: If true, returns HTML instead of Nodes list
"""
response = self._telegraph.method('getPage', path=path, values={
'return_content': return_content
})
if return_content and return_html:
response['content'] = nodes_to_html(response['content'])
return response | python | def get_page(self, path, return_content=True, return_html=True):
response = self._telegraph.method('getPage', path=path, values={
'return_content': return_content
})
if return_content and return_html:
response['content'] = nodes_to_html(response['content'])
return response | [
"def",
"get_page",
"(",
"self",
",",
"path",
",",
"return_content",
"=",
"True",
",",
"return_html",
"=",
"True",
")",
":",
"response",
"=",
"self",
".",
"_telegraph",
".",
"method",
"(",
"'getPage'",
",",
"path",
"=",
"path",
",",
"values",
"=",
"{",
... | Get a Telegraph page
:param path: Path to the Telegraph page (in the format Title-12-31,
i.e. everything that comes after https://telegra.ph/)
:param return_content: If true, content field will be returned
:param return_html: If true, returns HTML instead of Nodes list | [
"Get",
"a",
"Telegraph",
"page"
] | 6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc | https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L122-L139 |
24,774 | python273/telegraph | telegraph/api.py | Telegraph.create_page | def create_page(self, title, content=None, html_content=None,
author_name=None, author_url=None, return_content=False):
""" Create a new Telegraph page
:param title: Page title
:param content: Content in nodes list format (see doc)
:param html_content: Content in HTML format
:param author_name: Author name, displayed below the article's title
:param author_url: Profile link, opened when users click on
the author's name below the title
:param return_content: If true, a content field will be returned
"""
if content is None:
content = html_to_nodes(html_content)
content_json = json.dumps(content)
return self._telegraph.method('createPage', values={
'title': title,
'author_name': author_name,
'author_url': author_url,
'content': content_json,
'return_content': return_content
}) | python | def create_page(self, title, content=None, html_content=None,
author_name=None, author_url=None, return_content=False):
if content is None:
content = html_to_nodes(html_content)
content_json = json.dumps(content)
return self._telegraph.method('createPage', values={
'title': title,
'author_name': author_name,
'author_url': author_url,
'content': content_json,
'return_content': return_content
}) | [
"def",
"create_page",
"(",
"self",
",",
"title",
",",
"content",
"=",
"None",
",",
"html_content",
"=",
"None",
",",
"author_name",
"=",
"None",
",",
"author_url",
"=",
"None",
",",
"return_content",
"=",
"False",
")",
":",
"if",
"content",
"is",
"None",... | Create a new Telegraph page
:param title: Page title
:param content: Content in nodes list format (see doc)
:param html_content: Content in HTML format
:param author_name: Author name, displayed below the article's title
:param author_url: Profile link, opened when users click on
the author's name below the title
:param return_content: If true, a content field will be returned | [
"Create",
"a",
"new",
"Telegraph",
"page"
] | 6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc | https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L141-L170 |
24,775 | python273/telegraph | telegraph/api.py | Telegraph.get_account_info | def get_account_info(self, fields=None):
""" Get information about a Telegraph account
:param fields: List of account fields to return. Available fields:
short_name, author_name, author_url, auth_url, page_count
Default: [“short_name”,“author_name”,“author_url”]
"""
return self._telegraph.method('getAccountInfo', {
'fields': json.dumps(fields) if fields else None
}) | python | def get_account_info(self, fields=None):
return self._telegraph.method('getAccountInfo', {
'fields': json.dumps(fields) if fields else None
}) | [
"def",
"get_account_info",
"(",
"self",
",",
"fields",
"=",
"None",
")",
":",
"return",
"self",
".",
"_telegraph",
".",
"method",
"(",
"'getAccountInfo'",
",",
"{",
"'fields'",
":",
"json",
".",
"dumps",
"(",
"fields",
")",
"if",
"fields",
"else",
"None"... | Get information about a Telegraph account
:param fields: List of account fields to return. Available fields:
short_name, author_name, author_url, auth_url, page_count
Default: [“short_name”,“author_name”,“author_url”] | [
"Get",
"information",
"about",
"a",
"Telegraph",
"account"
] | 6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc | https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L205-L216 |
24,776 | python273/telegraph | telegraph/api.py | Telegraph.get_views | def get_views(self, path, year=None, month=None, day=None, hour=None):
""" Get the number of views for a Telegraph article
:param path: Path to the Telegraph page
:param year: Required if month is passed. If passed, the number of
page views for the requested year will be returned
:param month: Required if day is passed. If passed, the number of
page views for the requested month will be returned
:param day: Required if hour is passed. If passed, the number of
page views for the requested day will be returned
:param hour: If passed, the number of page views for
the requested hour will be returned
"""
return self._telegraph.method('getViews', path=path, values={
'year': year,
'month': month,
'day': day,
'hour': hour
}) | python | def get_views(self, path, year=None, month=None, day=None, hour=None):
return self._telegraph.method('getViews', path=path, values={
'year': year,
'month': month,
'day': day,
'hour': hour
}) | [
"def",
"get_views",
"(",
"self",
",",
"path",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
",",
"hour",
"=",
"None",
")",
":",
"return",
"self",
".",
"_telegraph",
".",
"method",
"(",
"'getViews'",
",",
"path",
"=",... | Get the number of views for a Telegraph article
:param path: Path to the Telegraph page
:param year: Required if month is passed. If passed, the number of
page views for the requested year will be returned
:param month: Required if day is passed. If passed, the number of
page views for the requested month will be returned
:param day: Required if hour is passed. If passed, the number of
page views for the requested day will be returned
:param hour: If passed, the number of page views for
the requested hour will be returned | [
"Get",
"the",
"number",
"of",
"views",
"for",
"a",
"Telegraph",
"article"
] | 6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc | https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/api.py#L234-L257 |
24,777 | python273/telegraph | telegraph/upload.py | upload_file | def upload_file(f):
""" Upload file to Telegra.ph's servers. Returns a list of links.
Allowed only .jpg, .jpeg, .png, .gif and .mp4 files.
:param f: filename or file-like object.
:type f: file, str or list
"""
with FilesOpener(f) as files:
response = requests.post(
'https://telegra.ph/upload',
files=files
).json()
if isinstance(response, list):
error = response[0].get('error')
else:
error = response.get('error')
if error:
raise TelegraphException(error)
return [i['src'] for i in response] | python | def upload_file(f):
with FilesOpener(f) as files:
response = requests.post(
'https://telegra.ph/upload',
files=files
).json()
if isinstance(response, list):
error = response[0].get('error')
else:
error = response.get('error')
if error:
raise TelegraphException(error)
return [i['src'] for i in response] | [
"def",
"upload_file",
"(",
"f",
")",
":",
"with",
"FilesOpener",
"(",
"f",
")",
"as",
"files",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"'https://telegra.ph/upload'",
",",
"files",
"=",
"files",
")",
".",
"json",
"(",
")",
"if",
"isinstance",
... | Upload file to Telegra.ph's servers. Returns a list of links.
Allowed only .jpg, .jpeg, .png, .gif and .mp4 files.
:param f: filename or file-like object.
:type f: file, str or list | [
"Upload",
"file",
"to",
"Telegra",
".",
"ph",
"s",
"servers",
".",
"Returns",
"a",
"list",
"of",
"links",
".",
"Allowed",
"only",
".",
"jpg",
".",
"jpeg",
".",
"png",
".",
"gif",
"and",
".",
"mp4",
"files",
"."
] | 6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc | https://github.com/python273/telegraph/blob/6d45cd6bbae4fdbd85b48ce32626f3c66e9e5ddc/telegraph/upload.py#L8-L29 |
24,778 | wq/django-natural-keys | natural_keys/models.py | NaturalKeyModelManager.get_by_natural_key | def get_by_natural_key(self, *args):
"""
Return the object corresponding to the provided natural key.
(This is a generic implementation of the standard Django function)
"""
kwargs = self.natural_key_kwargs(*args)
# Since kwargs already has __ lookups in it, we could just do this:
# return self.get(**kwargs)
# But, we should call each related model's get_by_natural_key in case
# it's been overridden
for name, rel_to in self.model.get_natural_key_info():
if not rel_to:
continue
# Extract natural key for related object
nested_key = extract_nested_key(kwargs, rel_to, name)
if nested_key:
# Update kwargs with related object
try:
kwargs[name] = rel_to.objects.get_by_natural_key(
*nested_key
)
except rel_to.DoesNotExist:
# If related object doesn't exist, assume this one doesn't
raise self.model.DoesNotExist()
else:
kwargs[name] = None
return self.get(**kwargs) | python | def get_by_natural_key(self, *args):
kwargs = self.natural_key_kwargs(*args)
# Since kwargs already has __ lookups in it, we could just do this:
# return self.get(**kwargs)
# But, we should call each related model's get_by_natural_key in case
# it's been overridden
for name, rel_to in self.model.get_natural_key_info():
if not rel_to:
continue
# Extract natural key for related object
nested_key = extract_nested_key(kwargs, rel_to, name)
if nested_key:
# Update kwargs with related object
try:
kwargs[name] = rel_to.objects.get_by_natural_key(
*nested_key
)
except rel_to.DoesNotExist:
# If related object doesn't exist, assume this one doesn't
raise self.model.DoesNotExist()
else:
kwargs[name] = None
return self.get(**kwargs) | [
"def",
"get_by_natural_key",
"(",
"self",
",",
"*",
"args",
")",
":",
"kwargs",
"=",
"self",
".",
"natural_key_kwargs",
"(",
"*",
"args",
")",
"# Since kwargs already has __ lookups in it, we could just do this:",
"# return self.get(**kwargs)",
"# But, we should call each rel... | Return the object corresponding to the provided natural key.
(This is a generic implementation of the standard Django function) | [
"Return",
"the",
"object",
"corresponding",
"to",
"the",
"provided",
"natural",
"key",
"."
] | f6bd6baf848e709ae9920b259a3ad1a6be8af615 | https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L38-L70 |
24,779 | wq/django-natural-keys | natural_keys/models.py | NaturalKeyModelManager.create_by_natural_key | def create_by_natural_key(self, *args):
"""
Create a new object from the provided natural key values. If the
natural key contains related objects, recursively get or create them by
their natural keys.
"""
kwargs = self.natural_key_kwargs(*args)
for name, rel_to in self.model.get_natural_key_info():
if not rel_to:
continue
nested_key = extract_nested_key(kwargs, rel_to, name)
# Automatically create any related objects as needed
if nested_key:
kwargs[name], is_new = (
rel_to.objects.get_or_create_by_natural_key(*nested_key)
)
else:
kwargs[name] = None
return self.create(**kwargs) | python | def create_by_natural_key(self, *args):
kwargs = self.natural_key_kwargs(*args)
for name, rel_to in self.model.get_natural_key_info():
if not rel_to:
continue
nested_key = extract_nested_key(kwargs, rel_to, name)
# Automatically create any related objects as needed
if nested_key:
kwargs[name], is_new = (
rel_to.objects.get_or_create_by_natural_key(*nested_key)
)
else:
kwargs[name] = None
return self.create(**kwargs) | [
"def",
"create_by_natural_key",
"(",
"self",
",",
"*",
"args",
")",
":",
"kwargs",
"=",
"self",
".",
"natural_key_kwargs",
"(",
"*",
"args",
")",
"for",
"name",
",",
"rel_to",
"in",
"self",
".",
"model",
".",
"get_natural_key_info",
"(",
")",
":",
"if",
... | Create a new object from the provided natural key values. If the
natural key contains related objects, recursively get or create them by
their natural keys. | [
"Create",
"a",
"new",
"object",
"from",
"the",
"provided",
"natural",
"key",
"values",
".",
"If",
"the",
"natural",
"key",
"contains",
"related",
"objects",
"recursively",
"get",
"or",
"create",
"them",
"by",
"their",
"natural",
"keys",
"."
] | f6bd6baf848e709ae9920b259a3ad1a6be8af615 | https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L72-L91 |
24,780 | wq/django-natural-keys | natural_keys/models.py | NaturalKeyModelManager.get_or_create_by_natural_key | def get_or_create_by_natural_key(self, *args):
"""
get_or_create + get_by_natural_key
"""
try:
return self.get_by_natural_key(*args), False
except self.model.DoesNotExist:
return self.create_by_natural_key(*args), True | python | def get_or_create_by_natural_key(self, *args):
try:
return self.get_by_natural_key(*args), False
except self.model.DoesNotExist:
return self.create_by_natural_key(*args), True | [
"def",
"get_or_create_by_natural_key",
"(",
"self",
",",
"*",
"args",
")",
":",
"try",
":",
"return",
"self",
".",
"get_by_natural_key",
"(",
"*",
"args",
")",
",",
"False",
"except",
"self",
".",
"model",
".",
"DoesNotExist",
":",
"return",
"self",
".",
... | get_or_create + get_by_natural_key | [
"get_or_create",
"+",
"get_by_natural_key"
] | f6bd6baf848e709ae9920b259a3ad1a6be8af615 | https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L93-L100 |
24,781 | wq/django-natural-keys | natural_keys/models.py | NaturalKeyModelManager.resolve_keys | def resolve_keys(self, keys, auto_create=False):
"""
Resolve the list of given keys into objects, if possible.
Returns a mapping and a success indicator.
"""
resolved = {}
success = True
for key in keys:
if auto_create:
resolved[key] = self.find(*key)
else:
try:
resolved[key] = self.get_by_natural_key(*key)
except self.model.DoesNotExist:
success = False
resolved[key] = None
return resolved, success | python | def resolve_keys(self, keys, auto_create=False):
resolved = {}
success = True
for key in keys:
if auto_create:
resolved[key] = self.find(*key)
else:
try:
resolved[key] = self.get_by_natural_key(*key)
except self.model.DoesNotExist:
success = False
resolved[key] = None
return resolved, success | [
"def",
"resolve_keys",
"(",
"self",
",",
"keys",
",",
"auto_create",
"=",
"False",
")",
":",
"resolved",
"=",
"{",
"}",
"success",
"=",
"True",
"for",
"key",
"in",
"keys",
":",
"if",
"auto_create",
":",
"resolved",
"[",
"key",
"]",
"=",
"self",
".",
... | Resolve the list of given keys into objects, if possible.
Returns a mapping and a success indicator. | [
"Resolve",
"the",
"list",
"of",
"given",
"keys",
"into",
"objects",
"if",
"possible",
".",
"Returns",
"a",
"mapping",
"and",
"a",
"success",
"indicator",
"."
] | f6bd6baf848e709ae9920b259a3ad1a6be8af615 | https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L117-L133 |
24,782 | wq/django-natural-keys | natural_keys/models.py | NaturalKeyModel.get_natural_key_info | def get_natural_key_info(cls):
"""
Derive natural key from first unique_together definition, noting which
fields are related objects vs. regular fields.
"""
fields = cls.get_natural_key_def()
info = []
for name in fields:
field = cls._meta.get_field(name)
rel_to = None
if hasattr(field, 'rel'):
rel_to = field.rel.to if field.rel else None
elif hasattr(field, 'remote_field'):
if field.remote_field:
rel_to = field.remote_field.model
else:
rel_to = None
info.append((name, rel_to))
return info | python | def get_natural_key_info(cls):
fields = cls.get_natural_key_def()
info = []
for name in fields:
field = cls._meta.get_field(name)
rel_to = None
if hasattr(field, 'rel'):
rel_to = field.rel.to if field.rel else None
elif hasattr(field, 'remote_field'):
if field.remote_field:
rel_to = field.remote_field.model
else:
rel_to = None
info.append((name, rel_to))
return info | [
"def",
"get_natural_key_info",
"(",
"cls",
")",
":",
"fields",
"=",
"cls",
".",
"get_natural_key_def",
"(",
")",
"info",
"=",
"[",
"]",
"for",
"name",
"in",
"fields",
":",
"field",
"=",
"cls",
".",
"_meta",
".",
"get_field",
"(",
"name",
")",
"rel_to",... | Derive natural key from first unique_together definition, noting which
fields are related objects vs. regular fields. | [
"Derive",
"natural",
"key",
"from",
"first",
"unique_together",
"definition",
"noting",
"which",
"fields",
"are",
"related",
"objects",
"vs",
".",
"regular",
"fields",
"."
] | f6bd6baf848e709ae9920b259a3ad1a6be8af615 | https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L144-L162 |
24,783 | wq/django-natural-keys | natural_keys/models.py | NaturalKeyModel.get_natural_key_fields | def get_natural_key_fields(cls):
"""
Determine actual natural key field list, incorporating the natural keys
of related objects as needed.
"""
natural_key = []
for name, rel_to in cls.get_natural_key_info():
if not rel_to:
natural_key.append(name)
else:
nested_key = rel_to.get_natural_key_fields()
natural_key.extend([
name + '__' + nname
for nname in nested_key
])
return natural_key | python | def get_natural_key_fields(cls):
natural_key = []
for name, rel_to in cls.get_natural_key_info():
if not rel_to:
natural_key.append(name)
else:
nested_key = rel_to.get_natural_key_fields()
natural_key.extend([
name + '__' + nname
for nname in nested_key
])
return natural_key | [
"def",
"get_natural_key_fields",
"(",
"cls",
")",
":",
"natural_key",
"=",
"[",
"]",
"for",
"name",
",",
"rel_to",
"in",
"cls",
".",
"get_natural_key_info",
"(",
")",
":",
"if",
"not",
"rel_to",
":",
"natural_key",
".",
"append",
"(",
"name",
")",
"else"... | Determine actual natural key field list, incorporating the natural keys
of related objects as needed. | [
"Determine",
"actual",
"natural",
"key",
"field",
"list",
"incorporating",
"the",
"natural",
"keys",
"of",
"related",
"objects",
"as",
"needed",
"."
] | f6bd6baf848e709ae9920b259a3ad1a6be8af615 | https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L177-L192 |
24,784 | wq/django-natural-keys | natural_keys/models.py | NaturalKeyModel.natural_key | def natural_key(self):
"""
Return the natural key for this object.
(This is a generic implementation of the standard Django function)
"""
# Recursively extract properties from related objects if needed
vals = [reduce(getattr, name.split('__'), self)
for name in self.get_natural_key_fields()]
return vals | python | def natural_key(self):
# Recursively extract properties from related objects if needed
vals = [reduce(getattr, name.split('__'), self)
for name in self.get_natural_key_fields()]
return vals | [
"def",
"natural_key",
"(",
"self",
")",
":",
"# Recursively extract properties from related objects if needed",
"vals",
"=",
"[",
"reduce",
"(",
"getattr",
",",
"name",
".",
"split",
"(",
"'__'",
")",
",",
"self",
")",
"for",
"name",
"in",
"self",
".",
"get_na... | Return the natural key for this object.
(This is a generic implementation of the standard Django function) | [
"Return",
"the",
"natural",
"key",
"for",
"this",
"object",
"."
] | f6bd6baf848e709ae9920b259a3ad1a6be8af615 | https://github.com/wq/django-natural-keys/blob/f6bd6baf848e709ae9920b259a3ad1a6be8af615/natural_keys/models.py#L194-L203 |
24,785 | SystemRDL/systemrdl-compiler | systemrdl/messages.py | SourceRef.derive_coordinates | def derive_coordinates(self):
"""
Depending on the compilation source, some members of the SourceRef
object may be incomplete.
Calling this function performs the necessary derivations to complete the
object.
"""
if self._coordinates_resolved:
# Coordinates were already resolved. Skip
return
if self.seg_map is not None:
# Translate coordinates
self.start, self.filename, include_ref = self.seg_map.derive_source_offset(self.start)
self.end, end_filename, _ = self.seg_map.derive_source_offset(self.end, is_end=True)
else:
end_filename = self.filename
line_start = 0
lineno = 1
file_pos = 0
# Skip deriving end coordinate if selection spans multiple files
if self.filename != end_filename:
get_end = False
elif self.end is None:
get_end = False
else:
get_end = True
if (self.filename is not None) and (self.start is not None):
with open(self.filename, 'r', newline='', encoding='utf_8') as fp:
while True:
line_text = fp.readline()
file_pos += len(line_text)
if line_text == "":
break
if (self.start_line is None) and (self.start < file_pos):
self.start_line = lineno
self.start_col = self.start - line_start
self.start_line_text = line_text.rstrip("\n").rstrip("\r")
if not get_end:
break
if get_end and (self.end_line is None) and (self.end < file_pos):
self.end_line = lineno
self.end_col = self.end - line_start
break
lineno += 1
line_start = file_pos
# If no end coordinate was derived, just do a single char selection
if not get_end:
self.end_line = self.start_line
self.end_col = self.start_col
self.end = self.start
self._coordinates_resolved = True | python | def derive_coordinates(self):
if self._coordinates_resolved:
# Coordinates were already resolved. Skip
return
if self.seg_map is not None:
# Translate coordinates
self.start, self.filename, include_ref = self.seg_map.derive_source_offset(self.start)
self.end, end_filename, _ = self.seg_map.derive_source_offset(self.end, is_end=True)
else:
end_filename = self.filename
line_start = 0
lineno = 1
file_pos = 0
# Skip deriving end coordinate if selection spans multiple files
if self.filename != end_filename:
get_end = False
elif self.end is None:
get_end = False
else:
get_end = True
if (self.filename is not None) and (self.start is not None):
with open(self.filename, 'r', newline='', encoding='utf_8') as fp:
while True:
line_text = fp.readline()
file_pos += len(line_text)
if line_text == "":
break
if (self.start_line is None) and (self.start < file_pos):
self.start_line = lineno
self.start_col = self.start - line_start
self.start_line_text = line_text.rstrip("\n").rstrip("\r")
if not get_end:
break
if get_end and (self.end_line is None) and (self.end < file_pos):
self.end_line = lineno
self.end_col = self.end - line_start
break
lineno += 1
line_start = file_pos
# If no end coordinate was derived, just do a single char selection
if not get_end:
self.end_line = self.start_line
self.end_col = self.start_col
self.end = self.start
self._coordinates_resolved = True | [
"def",
"derive_coordinates",
"(",
"self",
")",
":",
"if",
"self",
".",
"_coordinates_resolved",
":",
"# Coordinates were already resolved. Skip",
"return",
"if",
"self",
".",
"seg_map",
"is",
"not",
"None",
":",
"# Translate coordinates",
"self",
".",
"start",
",",
... | Depending on the compilation source, some members of the SourceRef
object may be incomplete.
Calling this function performs the necessary derivations to complete the
object. | [
"Depending",
"on",
"the",
"compilation",
"source",
"some",
"members",
"of",
"the",
"SourceRef",
"object",
"may",
"be",
"incomplete",
".",
"Calling",
"this",
"function",
"performs",
"the",
"necessary",
"derivations",
"to",
"complete",
"the",
"object",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/messages.py#L108-L171 |
24,786 | SystemRDL/systemrdl-compiler | systemrdl/messages.py | MessagePrinter.format_message | def format_message(self, severity, text, src_ref):
"""
Formats the message prior to emitting it.
Parameters
----------
severity: :class:`Severity`
Message severity.
text: str
Body of message
src_ref: :class:`SourceRef`
Reference to source context object
Returns
-------
list
List of strings for each line of the message
"""
lines = []
if severity >= Severity.ERROR:
color = Fore.RED
elif severity >= Severity.WARNING:
color = Fore.YELLOW
else:
color = Fore.GREEN
if src_ref is None:
# No message context available
lines.append(
color + Style.BRIGHT + severity.name.lower() + ": " + Style.RESET_ALL + text
)
return lines
src_ref.derive_coordinates()
if (src_ref.start_line is not None) and (src_ref.start_col is not None):
# Start line and column is known
lines.append(
Fore.WHITE + Style.BRIGHT
+ "%s:%d:%d: " % (src_ref.filename, src_ref.start_line, src_ref.start_col)
+ color + severity.name.lower() + ": "
+ Style.RESET_ALL
+ text
)
elif src_ref.start_line is not None:
# Only line number is known
lines.append(
Fore.WHITE + Style.BRIGHT
+ "%s:%d: " % (src_ref.filename, src_ref.start_line)
+ color + severity.name.lower() + ": "
+ Style.RESET_ALL
+ text
)
else:
# Only filename is known
lines.append(
Fore.WHITE + Style.BRIGHT
+ "%s: " % src_ref.filename
+ color + severity.name.lower() + ": "
+ Style.RESET_ALL
+ text
)
# If src_ref highlights a span within a single line of text, print it
if (src_ref.start_line is not None) and (src_ref.end_line is not None):
if src_ref.start_line != src_ref.end_line:
# multi-line reference
# Select remainder of the line
width = len(src_ref.start_line_text) - src_ref.start_col
lines.append(
src_ref.start_line_text[:src_ref.start_col]
+ color + Style.BRIGHT
+ src_ref.start_line_text[src_ref.start_col:]
+ Style.RESET_ALL
)
lines.append(
" "*src_ref.start_col
+ color + Style.BRIGHT
+ "^"*width
+ Style.RESET_ALL
)
else:
# Single line
width = src_ref.end_col - src_ref.start_col + 1
lines.append(
src_ref.start_line_text[:src_ref.start_col]
+ color + Style.BRIGHT
+ src_ref.start_line_text[src_ref.start_col : src_ref.end_col+1]
+ Style.RESET_ALL
+ src_ref.start_line_text[src_ref.end_col+1:]
)
lines.append(
" "*src_ref.start_col
+ color + Style.BRIGHT
+ "^"*width
+ Style.RESET_ALL
)
return lines | python | def format_message(self, severity, text, src_ref):
lines = []
if severity >= Severity.ERROR:
color = Fore.RED
elif severity >= Severity.WARNING:
color = Fore.YELLOW
else:
color = Fore.GREEN
if src_ref is None:
# No message context available
lines.append(
color + Style.BRIGHT + severity.name.lower() + ": " + Style.RESET_ALL + text
)
return lines
src_ref.derive_coordinates()
if (src_ref.start_line is not None) and (src_ref.start_col is not None):
# Start line and column is known
lines.append(
Fore.WHITE + Style.BRIGHT
+ "%s:%d:%d: " % (src_ref.filename, src_ref.start_line, src_ref.start_col)
+ color + severity.name.lower() + ": "
+ Style.RESET_ALL
+ text
)
elif src_ref.start_line is not None:
# Only line number is known
lines.append(
Fore.WHITE + Style.BRIGHT
+ "%s:%d: " % (src_ref.filename, src_ref.start_line)
+ color + severity.name.lower() + ": "
+ Style.RESET_ALL
+ text
)
else:
# Only filename is known
lines.append(
Fore.WHITE + Style.BRIGHT
+ "%s: " % src_ref.filename
+ color + severity.name.lower() + ": "
+ Style.RESET_ALL
+ text
)
# If src_ref highlights a span within a single line of text, print it
if (src_ref.start_line is not None) and (src_ref.end_line is not None):
if src_ref.start_line != src_ref.end_line:
# multi-line reference
# Select remainder of the line
width = len(src_ref.start_line_text) - src_ref.start_col
lines.append(
src_ref.start_line_text[:src_ref.start_col]
+ color + Style.BRIGHT
+ src_ref.start_line_text[src_ref.start_col:]
+ Style.RESET_ALL
)
lines.append(
" "*src_ref.start_col
+ color + Style.BRIGHT
+ "^"*width
+ Style.RESET_ALL
)
else:
# Single line
width = src_ref.end_col - src_ref.start_col + 1
lines.append(
src_ref.start_line_text[:src_ref.start_col]
+ color + Style.BRIGHT
+ src_ref.start_line_text[src_ref.start_col : src_ref.end_col+1]
+ Style.RESET_ALL
+ src_ref.start_line_text[src_ref.end_col+1:]
)
lines.append(
" "*src_ref.start_col
+ color + Style.BRIGHT
+ "^"*width
+ Style.RESET_ALL
)
return lines | [
"def",
"format_message",
"(",
"self",
",",
"severity",
",",
"text",
",",
"src_ref",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"severity",
">=",
"Severity",
".",
"ERROR",
":",
"color",
"=",
"Fore",
".",
"RED",
"elif",
"severity",
">=",
"Severity",
".",
... | Formats the message prior to emitting it.
Parameters
----------
severity: :class:`Severity`
Message severity.
text: str
Body of message
src_ref: :class:`SourceRef`
Reference to source context object
Returns
-------
list
List of strings for each line of the message | [
"Formats",
"the",
"message",
"prior",
"to",
"emitting",
"it",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/messages.py#L240-L344 |
24,787 | SystemRDL/systemrdl-compiler | systemrdl/messages.py | MessagePrinter.emit_message | def emit_message(self, lines):
"""
Emit message.
Default printer emits messages to stderr
Parameters
----------
lines: list
List of strings containing each line of the message
"""
for line in lines:
print(line, file=sys.stderr) | python | def emit_message(self, lines):
for line in lines:
print(line, file=sys.stderr) | [
"def",
"emit_message",
"(",
"self",
",",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"print",
"(",
"line",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | Emit message.
Default printer emits messages to stderr
Parameters
----------
lines: list
List of strings containing each line of the message | [
"Emit",
"message",
".",
"Default",
"printer",
"emits",
"messages",
"to",
"stderr"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/messages.py#L347-L359 |
24,788 | SystemRDL/systemrdl-compiler | systemrdl/core/parameter.py | Parameter.get_value | def get_value(self):
"""
Evaluate self.expr to get the parameter's value
"""
if (self._value is None) and (self.expr is not None):
self._value = self.expr.get_value()
return self._value | python | def get_value(self):
if (self._value is None) and (self.expr is not None):
self._value = self.expr.get_value()
return self._value | [
"def",
"get_value",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_value",
"is",
"None",
")",
"and",
"(",
"self",
".",
"expr",
"is",
"not",
"None",
")",
":",
"self",
".",
"_value",
"=",
"self",
".",
"expr",
".",
"get_value",
"(",
")",
"return",... | Evaluate self.expr to get the parameter's value | [
"Evaluate",
"self",
".",
"expr",
"to",
"get",
"the",
"parameter",
"s",
"value"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/parameter.py#L17-L24 |
24,789 | SystemRDL/systemrdl-compiler | systemrdl/core/expressions.py | is_castable | def is_castable(src, dst):
"""
Check if src type can be cast to dst type
"""
if ((src in [int, bool]) or rdltypes.is_user_enum(src)) and (dst in [int, bool]):
# Pure numeric or enum can be cast to a numeric
return True
elif (src == rdltypes.ArrayPlaceholder) and (dst == rdltypes.ArrayPlaceholder):
# Check that array element types also match
if src.element_type is None:
# indeterminate array type. Is castable
return True
elif src.element_type == dst.element_type:
return True
else:
return False
elif rdltypes.is_user_struct(dst):
# Structs can be assigned their derived counterparts - aka their subclasses
return issubclass(src, dst)
elif dst == rdltypes.PropertyReference:
return issubclass(src, rdltypes.PropertyReference)
elif src == dst:
return True
else:
return False | python | def is_castable(src, dst):
if ((src in [int, bool]) or rdltypes.is_user_enum(src)) and (dst in [int, bool]):
# Pure numeric or enum can be cast to a numeric
return True
elif (src == rdltypes.ArrayPlaceholder) and (dst == rdltypes.ArrayPlaceholder):
# Check that array element types also match
if src.element_type is None:
# indeterminate array type. Is castable
return True
elif src.element_type == dst.element_type:
return True
else:
return False
elif rdltypes.is_user_struct(dst):
# Structs can be assigned their derived counterparts - aka their subclasses
return issubclass(src, dst)
elif dst == rdltypes.PropertyReference:
return issubclass(src, rdltypes.PropertyReference)
elif src == dst:
return True
else:
return False | [
"def",
"is_castable",
"(",
"src",
",",
"dst",
")",
":",
"if",
"(",
"(",
"src",
"in",
"[",
"int",
",",
"bool",
"]",
")",
"or",
"rdltypes",
".",
"is_user_enum",
"(",
"src",
")",
")",
"and",
"(",
"dst",
"in",
"[",
"int",
",",
"bool",
"]",
")",
"... | Check if src type can be cast to dst type | [
"Check",
"if",
"src",
"type",
"can",
"be",
"cast",
"to",
"dst",
"type"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/expressions.py#L1193-L1217 |
24,790 | SystemRDL/systemrdl-compiler | systemrdl/core/expressions.py | InstRef.predict_type | def predict_type(self):
"""
Traverse the ref_elements path and determine the component type being
referenced.
Also do some checks on the array indexes
"""
current_comp = self.ref_root
for name, array_suffixes, name_src_ref in self.ref_elements:
# find instance
current_comp = current_comp.get_child_by_name(name)
if current_comp is None:
# Not found!
self.msg.fatal(
"Could not resolve hierarchical reference to '%s'" % name,
name_src_ref
)
# Do type-check in array suffixes
for array_suffix in array_suffixes:
array_suffix.predict_type()
# Check array suffixes
if (isinstance(current_comp, comp.AddressableComponent)) and current_comp.is_array:
# is an array
if len(array_suffixes) != len(current_comp.array_dimensions):
self.msg.fatal(
"Incompatible number of index dimensions after '%s'. Expected %d, found %d."
% (name, len(current_comp.array_dimensions), len(array_suffixes)),
name_src_ref
)
elif array_suffixes:
# Has array suffixes. Check if compatible with referenced component
self.msg.fatal(
"Unable to index non-array component '%s'" % name,
name_src_ref
)
return type(current_comp) | python | def predict_type(self):
current_comp = self.ref_root
for name, array_suffixes, name_src_ref in self.ref_elements:
# find instance
current_comp = current_comp.get_child_by_name(name)
if current_comp is None:
# Not found!
self.msg.fatal(
"Could not resolve hierarchical reference to '%s'" % name,
name_src_ref
)
# Do type-check in array suffixes
for array_suffix in array_suffixes:
array_suffix.predict_type()
# Check array suffixes
if (isinstance(current_comp, comp.AddressableComponent)) and current_comp.is_array:
# is an array
if len(array_suffixes) != len(current_comp.array_dimensions):
self.msg.fatal(
"Incompatible number of index dimensions after '%s'. Expected %d, found %d."
% (name, len(current_comp.array_dimensions), len(array_suffixes)),
name_src_ref
)
elif array_suffixes:
# Has array suffixes. Check if compatible with referenced component
self.msg.fatal(
"Unable to index non-array component '%s'" % name,
name_src_ref
)
return type(current_comp) | [
"def",
"predict_type",
"(",
"self",
")",
":",
"current_comp",
"=",
"self",
".",
"ref_root",
"for",
"name",
",",
"array_suffixes",
",",
"name_src_ref",
"in",
"self",
".",
"ref_elements",
":",
"# find instance",
"current_comp",
"=",
"current_comp",
".",
"get_child... | Traverse the ref_elements path and determine the component type being
referenced.
Also do some checks on the array indexes | [
"Traverse",
"the",
"ref_elements",
"path",
"and",
"determine",
"the",
"component",
"type",
"being",
"referenced",
".",
"Also",
"do",
"some",
"checks",
"on",
"the",
"array",
"indexes"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/expressions.py#L1063-L1101 |
24,791 | SystemRDL/systemrdl-compiler | systemrdl/core/expressions.py | InstRef.get_value | def get_value(self, eval_width=None):
"""
Build a resolved ComponentRef container that describes the relative path
"""
resolved_ref_elements = []
for name, array_suffixes, name_src_ref in self.ref_elements:
idx_list = [ suffix.get_value() for suffix in array_suffixes ]
resolved_ref_elements.append((name, idx_list, name_src_ref))
# Create container
cref = rdltypes.ComponentRef(self.ref_root, resolved_ref_elements)
return cref | python | def get_value(self, eval_width=None):
resolved_ref_elements = []
for name, array_suffixes, name_src_ref in self.ref_elements:
idx_list = [ suffix.get_value() for suffix in array_suffixes ]
resolved_ref_elements.append((name, idx_list, name_src_ref))
# Create container
cref = rdltypes.ComponentRef(self.ref_root, resolved_ref_elements)
return cref | [
"def",
"get_value",
"(",
"self",
",",
"eval_width",
"=",
"None",
")",
":",
"resolved_ref_elements",
"=",
"[",
"]",
"for",
"name",
",",
"array_suffixes",
",",
"name_src_ref",
"in",
"self",
".",
"ref_elements",
":",
"idx_list",
"=",
"[",
"suffix",
".",
"get_... | Build a resolved ComponentRef container that describes the relative path | [
"Build",
"a",
"resolved",
"ComponentRef",
"container",
"that",
"describes",
"the",
"relative",
"path"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/expressions.py#L1103-L1117 |
24,792 | SystemRDL/systemrdl-compiler | systemrdl/core/expressions.py | PropRef.predict_type | def predict_type(self):
"""
Predict the type of the inst_ref, and make sure the property being
referenced is allowed
"""
inst_type = self.inst_ref.predict_type()
if self.prop_ref_type.allowed_inst_type != inst_type:
self.msg.fatal(
"'%s' is not a valid property of instance" % self.prop_ref_type.get_name(),
self.src_ref
)
return self.prop_ref_type | python | def predict_type(self):
inst_type = self.inst_ref.predict_type()
if self.prop_ref_type.allowed_inst_type != inst_type:
self.msg.fatal(
"'%s' is not a valid property of instance" % self.prop_ref_type.get_name(),
self.src_ref
)
return self.prop_ref_type | [
"def",
"predict_type",
"(",
"self",
")",
":",
"inst_type",
"=",
"self",
".",
"inst_ref",
".",
"predict_type",
"(",
")",
"if",
"self",
".",
"prop_ref_type",
".",
"allowed_inst_type",
"!=",
"inst_type",
":",
"self",
".",
"msg",
".",
"fatal",
"(",
"\"'%s' is ... | Predict the type of the inst_ref, and make sure the property being
referenced is allowed | [
"Predict",
"the",
"type",
"of",
"the",
"inst_ref",
"and",
"make",
"sure",
"the",
"property",
"being",
"referenced",
"is",
"allowed"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/expressions.py#L1129-L1142 |
24,793 | SystemRDL/systemrdl-compiler | systemrdl/node.py | get_group_node_size | def get_group_node_size(node):
"""
Shared getter for AddrmapNode and RegfileNode's "size" property
"""
# After structural placement, children are sorted
if( not node.inst.children
or (not isinstance(node.inst.children[-1], comp.AddressableComponent))
):
# No addressable child exists.
return 0
# Current node's size is based on last child
last_child_node = Node._factory(node.inst.children[-1], node.env, node)
return(
last_child_node.inst.addr_offset
+ last_child_node.total_size
) | python | def get_group_node_size(node):
# After structural placement, children are sorted
if( not node.inst.children
or (not isinstance(node.inst.children[-1], comp.AddressableComponent))
):
# No addressable child exists.
return 0
# Current node's size is based on last child
last_child_node = Node._factory(node.inst.children[-1], node.env, node)
return(
last_child_node.inst.addr_offset
+ last_child_node.total_size
) | [
"def",
"get_group_node_size",
"(",
"node",
")",
":",
"# After structural placement, children are sorted",
"if",
"(",
"not",
"node",
".",
"inst",
".",
"children",
"or",
"(",
"not",
"isinstance",
"(",
"node",
".",
"inst",
".",
"children",
"[",
"-",
"1",
"]",
"... | Shared getter for AddrmapNode and RegfileNode's "size" property | [
"Shared",
"getter",
"for",
"AddrmapNode",
"and",
"RegfileNode",
"s",
"size",
"property"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L810-L826 |
24,794 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.add_derived_property | def add_derived_property(cls, getter_function, name=None):
"""
Register a user-defined derived property
Parameters
----------
getter_function : function
Function that fetches the result of the user-defined derived property
name : str
Derived property name
If unassigned, will default to the function's name
"""
if name is None:
name = getter_function.__name__
mp = property(fget=getter_function)
setattr(cls, name, mp) | python | def add_derived_property(cls, getter_function, name=None):
if name is None:
name = getter_function.__name__
mp = property(fget=getter_function)
setattr(cls, name, mp) | [
"def",
"add_derived_property",
"(",
"cls",
",",
"getter_function",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"getter_function",
".",
"__name__",
"mp",
"=",
"property",
"(",
"fget",
"=",
"getter_function",
")",
"setat... | Register a user-defined derived property
Parameters
----------
getter_function : function
Function that fetches the result of the user-defined derived property
name : str
Derived property name
If unassigned, will default to the function's name | [
"Register",
"a",
"user",
"-",
"defined",
"derived",
"property"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L55-L71 |
24,795 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.children | def children(self, unroll=False, skip_not_present=True):
"""
Returns an iterator that provides nodes for all immediate children of
this component.
Parameters
----------
unroll : bool
If True, any children that are arrays are unrolled.
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
Yields
------
:class:`~Node`
All immediate children
"""
for child_inst in self.inst.children:
if skip_not_present:
# Check if property ispresent == False
if not child_inst.properties.get('ispresent', True):
# ispresent was explicitly set to False. Skip it
continue
if unroll and isinstance(child_inst, comp.AddressableComponent) and child_inst.is_array:
# Unroll the array
range_list = [range(n) for n in child_inst.array_dimensions]
for idxs in itertools.product(*range_list):
N = Node._factory(child_inst, self.env, self)
N.current_idx = idxs # pylint: disable=attribute-defined-outside-init
yield N
else:
yield Node._factory(child_inst, self.env, self) | python | def children(self, unroll=False, skip_not_present=True):
for child_inst in self.inst.children:
if skip_not_present:
# Check if property ispresent == False
if not child_inst.properties.get('ispresent', True):
# ispresent was explicitly set to False. Skip it
continue
if unroll and isinstance(child_inst, comp.AddressableComponent) and child_inst.is_array:
# Unroll the array
range_list = [range(n) for n in child_inst.array_dimensions]
for idxs in itertools.product(*range_list):
N = Node._factory(child_inst, self.env, self)
N.current_idx = idxs # pylint: disable=attribute-defined-outside-init
yield N
else:
yield Node._factory(child_inst, self.env, self) | [
"def",
"children",
"(",
"self",
",",
"unroll",
"=",
"False",
",",
"skip_not_present",
"=",
"True",
")",
":",
"for",
"child_inst",
"in",
"self",
".",
"inst",
".",
"children",
":",
"if",
"skip_not_present",
":",
"# Check if property ispresent == False",
"if",
"n... | Returns an iterator that provides nodes for all immediate children of
this component.
Parameters
----------
unroll : bool
If True, any children that are arrays are unrolled.
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
Yields
------
:class:`~Node`
All immediate children | [
"Returns",
"an",
"iterator",
"that",
"provides",
"nodes",
"for",
"all",
"immediate",
"children",
"of",
"this",
"component",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L74-L107 |
24,796 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.descendants | def descendants(self, unroll=False, skip_not_present=True, in_post_order=False):
"""
Returns an iterator that provides nodes for all descendants of this
component.
Parameters
----------
unroll : bool
If True, any children that are arrays are unrolled.
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
in_post_order : bool
If True, descendants are walked using post-order traversal
(children first) rather than the default pre-order traversal
(parents first).
Yields
------
:class:`~Node`
All descendant nodes of this component
"""
for child in self.children(unroll, skip_not_present):
if in_post_order:
yield from child.descendants(unroll, skip_not_present, in_post_order)
yield child
if not in_post_order:
yield from child.descendants(unroll, skip_not_present, in_post_order) | python | def descendants(self, unroll=False, skip_not_present=True, in_post_order=False):
for child in self.children(unroll, skip_not_present):
if in_post_order:
yield from child.descendants(unroll, skip_not_present, in_post_order)
yield child
if not in_post_order:
yield from child.descendants(unroll, skip_not_present, in_post_order) | [
"def",
"descendants",
"(",
"self",
",",
"unroll",
"=",
"False",
",",
"skip_not_present",
"=",
"True",
",",
"in_post_order",
"=",
"False",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
"(",
"unroll",
",",
"skip_not_present",
")",
":",
"if",
"in... | Returns an iterator that provides nodes for all descendants of this
component.
Parameters
----------
unroll : bool
If True, any children that are arrays are unrolled.
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
in_post_order : bool
If True, descendants are walked using post-order traversal
(children first) rather than the default pre-order traversal
(parents first).
Yields
------
:class:`~Node`
All descendant nodes of this component | [
"Returns",
"an",
"iterator",
"that",
"provides",
"nodes",
"for",
"all",
"descendants",
"of",
"this",
"component",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L110-L140 |
24,797 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.signals | def signals(self, skip_not_present=True):
"""
Returns an iterator that provides nodes for all immediate signals of
this component.
Parameters
----------
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
Yields
------
:class:`~SignalNode`
All signals in this component
"""
for child in self.children(skip_not_present=skip_not_present):
if isinstance(child, SignalNode):
yield child | python | def signals(self, skip_not_present=True):
for child in self.children(skip_not_present=skip_not_present):
if isinstance(child, SignalNode):
yield child | [
"def",
"signals",
"(",
"self",
",",
"skip_not_present",
"=",
"True",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
"(",
"skip_not_present",
"=",
"skip_not_present",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"SignalNode",
")",
":",
"yield"... | Returns an iterator that provides nodes for all immediate signals of
this component.
Parameters
----------
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
Yields
------
:class:`~SignalNode`
All signals in this component | [
"Returns",
"an",
"iterator",
"that",
"provides",
"nodes",
"for",
"all",
"immediate",
"signals",
"of",
"this",
"component",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L143-L160 |
24,798 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.fields | def fields(self, skip_not_present=True):
"""
Returns an iterator that provides nodes for all immediate fields of
this component.
Parameters
----------
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
Yields
------
:class:`~FieldNode`
All fields in this component
"""
for child in self.children(skip_not_present=skip_not_present):
if isinstance(child, FieldNode):
yield child | python | def fields(self, skip_not_present=True):
for child in self.children(skip_not_present=skip_not_present):
if isinstance(child, FieldNode):
yield child | [
"def",
"fields",
"(",
"self",
",",
"skip_not_present",
"=",
"True",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
"(",
"skip_not_present",
"=",
"skip_not_present",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"FieldNode",
")",
":",
"yield",
... | Returns an iterator that provides nodes for all immediate fields of
this component.
Parameters
----------
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
Yields
------
:class:`~FieldNode`
All fields in this component | [
"Returns",
"an",
"iterator",
"that",
"provides",
"nodes",
"for",
"all",
"immediate",
"fields",
"of",
"this",
"component",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L163-L180 |
24,799 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.registers | def registers(self, unroll=False, skip_not_present=True):
"""
Returns an iterator that provides nodes for all immediate registers of
this component.
Parameters
----------
unroll : bool
If True, any children that are arrays are unrolled.
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
Yields
------
:class:`~RegNode`
All registers in this component
"""
for child in self.children(unroll, skip_not_present):
if isinstance(child, RegNode):
yield child | python | def registers(self, unroll=False, skip_not_present=True):
for child in self.children(unroll, skip_not_present):
if isinstance(child, RegNode):
yield child | [
"def",
"registers",
"(",
"self",
",",
"unroll",
"=",
"False",
",",
"skip_not_present",
"=",
"True",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
"(",
"unroll",
",",
"skip_not_present",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"RegNode... | Returns an iterator that provides nodes for all immediate registers of
this component.
Parameters
----------
unroll : bool
If True, any children that are arrays are unrolled.
skip_not_present : bool
If True, skips children whose 'ispresent' property is set to False
Yields
------
:class:`~RegNode`
All registers in this component | [
"Returns",
"an",
"iterator",
"that",
"provides",
"nodes",
"for",
"all",
"immediate",
"registers",
"of",
"this",
"component",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L183-L203 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.