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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
241,400 | atztogo/phonopy | phonopy/harmonic/force_constants.py | get_fc2 | def get_fc2(supercell,
symmetry,
dataset,
atom_list=None,
decimals=None):
"""Force constants are computed.
Force constants, Phi, are calculated from sets for forces, F, and
atomic displacement, d:
Phi = -F / d
This is solved by matrix pseudo-inversion.
Crystal symmetry is included when creating F and d matrices.
Returns
-------
ndarray
Force constants[ i, j, a, b ]
i: Atom index of finitely displaced atom.
j: Atom index at which force on the atom is measured.
a, b: Cartesian direction indices = (0, 1, 2) for i and j, respectively
dtype=double
shape=(len(atom_list),n_satom,3,3),
"""
if atom_list is None:
fc_dim0 = supercell.get_number_of_atoms()
else:
fc_dim0 = len(atom_list)
force_constants = np.zeros((fc_dim0,
supercell.get_number_of_atoms(),
3, 3), dtype='double', order='C')
# Fill force_constants[ displaced_atoms, all_atoms_in_supercell ]
atom_list_done = _get_force_constants_disps(
force_constants,
supercell,
dataset,
symmetry,
atom_list=atom_list)
rotations = symmetry.get_symmetry_operations()['rotations']
lattice = np.array(supercell.get_cell().T, dtype='double', order='C')
permutations = symmetry.get_atomic_permutations()
distribute_force_constants(force_constants,
atom_list_done,
lattice,
rotations,
permutations,
atom_list=atom_list)
if decimals:
force_constants = force_constants.round(decimals=decimals)
return force_constants | python | def get_fc2(supercell,
symmetry,
dataset,
atom_list=None,
decimals=None):
if atom_list is None:
fc_dim0 = supercell.get_number_of_atoms()
else:
fc_dim0 = len(atom_list)
force_constants = np.zeros((fc_dim0,
supercell.get_number_of_atoms(),
3, 3), dtype='double', order='C')
# Fill force_constants[ displaced_atoms, all_atoms_in_supercell ]
atom_list_done = _get_force_constants_disps(
force_constants,
supercell,
dataset,
symmetry,
atom_list=atom_list)
rotations = symmetry.get_symmetry_operations()['rotations']
lattice = np.array(supercell.get_cell().T, dtype='double', order='C')
permutations = symmetry.get_atomic_permutations()
distribute_force_constants(force_constants,
atom_list_done,
lattice,
rotations,
permutations,
atom_list=atom_list)
if decimals:
force_constants = force_constants.round(decimals=decimals)
return force_constants | [
"def",
"get_fc2",
"(",
"supercell",
",",
"symmetry",
",",
"dataset",
",",
"atom_list",
"=",
"None",
",",
"decimals",
"=",
"None",
")",
":",
"if",
"atom_list",
"is",
"None",
":",
"fc_dim0",
"=",
"supercell",
".",
"get_number_of_atoms",
"(",
")",
"else",
"... | Force constants are computed.
Force constants, Phi, are calculated from sets for forces, F, and
atomic displacement, d:
Phi = -F / d
This is solved by matrix pseudo-inversion.
Crystal symmetry is included when creating F and d matrices.
Returns
-------
ndarray
Force constants[ i, j, a, b ]
i: Atom index of finitely displaced atom.
j: Atom index at which force on the atom is measured.
a, b: Cartesian direction indices = (0, 1, 2) for i and j, respectively
dtype=double
shape=(len(atom_list),n_satom,3,3), | [
"Force",
"constants",
"are",
"computed",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L58-L113 |
241,401 | atztogo/phonopy | phonopy/harmonic/force_constants.py | set_permutation_symmetry | def set_permutation_symmetry(force_constants):
"""Enforce permutation symmetry to force cosntants by
Phi_ij_ab = Phi_ji_ba
i, j: atom index
a, b: Cartesian axis index
This is not necessary for harmonic phonon calculation because this
condition is imposed when making dynamical matrix Hermite in
dynamical_matrix.py.
"""
fc_copy = force_constants.copy()
for i in range(force_constants.shape[0]):
for j in range(force_constants.shape[1]):
force_constants[i, j] = (force_constants[i, j] +
fc_copy[j, i].T) / 2 | python | def set_permutation_symmetry(force_constants):
fc_copy = force_constants.copy()
for i in range(force_constants.shape[0]):
for j in range(force_constants.shape[1]):
force_constants[i, j] = (force_constants[i, j] +
fc_copy[j, i].T) / 2 | [
"def",
"set_permutation_symmetry",
"(",
"force_constants",
")",
":",
"fc_copy",
"=",
"force_constants",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"force_constants",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"j",
"in",
"range",
"(",
"forc... | Enforce permutation symmetry to force cosntants by
Phi_ij_ab = Phi_ji_ba
i, j: atom index
a, b: Cartesian axis index
This is not necessary for harmonic phonon calculation because this
condition is imposed when making dynamical matrix Hermite in
dynamical_matrix.py. | [
"Enforce",
"permutation",
"symmetry",
"to",
"force",
"cosntants",
"by"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L462-L480 |
241,402 | atztogo/phonopy | phonopy/harmonic/force_constants.py | similarity_transformation | def similarity_transformation(rot, mat):
""" R x M x R^-1 """
return np.dot(rot, np.dot(mat, np.linalg.inv(rot))) | python | def similarity_transformation(rot, mat):
return np.dot(rot, np.dot(mat, np.linalg.inv(rot))) | [
"def",
"similarity_transformation",
"(",
"rot",
",",
"mat",
")",
":",
"return",
"np",
".",
"dot",
"(",
"rot",
",",
"np",
".",
"dot",
"(",
"mat",
",",
"np",
".",
"linalg",
".",
"inv",
"(",
"rot",
")",
")",
")"
] | R x M x R^-1 | [
"R",
"x",
"M",
"x",
"R^",
"-",
"1"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L529-L531 |
241,403 | atztogo/phonopy | phonopy/harmonic/force_constants.py | _get_sym_mappings_from_permutations | def _get_sym_mappings_from_permutations(permutations, atom_list_done):
"""This can be thought of as computing 'map_atom_disp' and 'map_sym'
for all atoms, except done using permutations instead of by
computing overlaps.
Input:
* permutations, shape [num_rot][num_pos]
* atom_list_done
Output:
* map_atoms, shape [num_pos].
Maps each atom in the full structure to its equivalent atom in
atom_list_done. (each entry will be an integer found in
atom_list_done)
* map_syms, shape [num_pos].
For each atom, provides the index of a rotation that maps it
into atom_list_done. (there might be more than one such
rotation, but only one will be returned) (each entry will be
an integer 0 <= i < num_rot)
"""
assert permutations.ndim == 2
num_pos = permutations.shape[1]
# filled with -1
map_atoms = np.zeros((num_pos,), dtype='intc') - 1
map_syms = np.zeros((num_pos,), dtype='intc') - 1
atom_list_done = set(atom_list_done)
for atom_todo in range(num_pos):
for (sym_index, permutation) in enumerate(permutations):
if permutation[atom_todo] in atom_list_done:
map_atoms[atom_todo] = permutation[atom_todo]
map_syms[atom_todo] = sym_index
break
else:
text = ("Input forces are not enough to calculate force constants,"
"or something wrong (e.g. crystal structure does not "
"match).")
print(textwrap.fill(text))
raise ValueError
assert set(map_atoms) & set(atom_list_done) == set(map_atoms)
assert -1 not in map_atoms
assert -1 not in map_syms
return map_atoms, map_syms | python | def _get_sym_mappings_from_permutations(permutations, atom_list_done):
assert permutations.ndim == 2
num_pos = permutations.shape[1]
# filled with -1
map_atoms = np.zeros((num_pos,), dtype='intc') - 1
map_syms = np.zeros((num_pos,), dtype='intc') - 1
atom_list_done = set(atom_list_done)
for atom_todo in range(num_pos):
for (sym_index, permutation) in enumerate(permutations):
if permutation[atom_todo] in atom_list_done:
map_atoms[atom_todo] = permutation[atom_todo]
map_syms[atom_todo] = sym_index
break
else:
text = ("Input forces are not enough to calculate force constants,"
"or something wrong (e.g. crystal structure does not "
"match).")
print(textwrap.fill(text))
raise ValueError
assert set(map_atoms) & set(atom_list_done) == set(map_atoms)
assert -1 not in map_atoms
assert -1 not in map_syms
return map_atoms, map_syms | [
"def",
"_get_sym_mappings_from_permutations",
"(",
"permutations",
",",
"atom_list_done",
")",
":",
"assert",
"permutations",
".",
"ndim",
"==",
"2",
"num_pos",
"=",
"permutations",
".",
"shape",
"[",
"1",
"]",
"# filled with -1",
"map_atoms",
"=",
"np",
".",
"z... | This can be thought of as computing 'map_atom_disp' and 'map_sym'
for all atoms, except done using permutations instead of by
computing overlaps.
Input:
* permutations, shape [num_rot][num_pos]
* atom_list_done
Output:
* map_atoms, shape [num_pos].
Maps each atom in the full structure to its equivalent atom in
atom_list_done. (each entry will be an integer found in
atom_list_done)
* map_syms, shape [num_pos].
For each atom, provides the index of a rotation that maps it
into atom_list_done. (there might be more than one such
rotation, but only one will be returned) (each entry will be
an integer 0 <= i < num_rot) | [
"This",
"can",
"be",
"thought",
"of",
"as",
"computing",
"map_atom_disp",
"and",
"map_sym",
"for",
"all",
"atoms",
"except",
"done",
"using",
"permutations",
"instead",
"of",
"by",
"computing",
"overlaps",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L778-L826 |
241,404 | atztogo/phonopy | phonopy/harmonic/displacement.py | get_least_displacements | def get_least_displacements(symmetry,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False,
log_level=0):
"""Return a set of displacements
Returns
-------
array_like
List of directions with respect to axes. This gives only the
symmetrically non equivalent directions. The format is like:
[[0, 1, 0, 0],
[7, 1, 0, 1], ...]
where each list is defined by:
First value: Atom index in supercell starting with 0
Second to fourth: If the direction is displaced or not (1, 0, or -1)
with respect to the axes.
"""
displacements = []
if is_diagonal:
directions = directions_diag
else:
directions = directions_axis
if log_level > 2:
print("Site point symmetry:")
for atom_num in symmetry.get_independent_atoms():
site_symmetry = symmetry.get_site_symmetry(atom_num)
if log_level > 2:
print("Atom %d" % (atom_num + 1))
for i, rot in enumerate(site_symmetry):
print("----%d----" % (i + 1))
for v in rot:
print("%2d %2d %2d" % tuple(v))
for disp in get_displacement(site_symmetry,
directions,
is_trigonal,
log_level):
displacements.append([atom_num,
disp[0], disp[1], disp[2]])
if is_plusminus == 'auto':
if is_minus_displacement(disp, site_symmetry):
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
elif is_plusminus is True:
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
return displacements | python | def get_least_displacements(symmetry,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False,
log_level=0):
displacements = []
if is_diagonal:
directions = directions_diag
else:
directions = directions_axis
if log_level > 2:
print("Site point symmetry:")
for atom_num in symmetry.get_independent_atoms():
site_symmetry = symmetry.get_site_symmetry(atom_num)
if log_level > 2:
print("Atom %d" % (atom_num + 1))
for i, rot in enumerate(site_symmetry):
print("----%d----" % (i + 1))
for v in rot:
print("%2d %2d %2d" % tuple(v))
for disp in get_displacement(site_symmetry,
directions,
is_trigonal,
log_level):
displacements.append([atom_num,
disp[0], disp[1], disp[2]])
if is_plusminus == 'auto':
if is_minus_displacement(disp, site_symmetry):
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
elif is_plusminus is True:
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
return displacements | [
"def",
"get_least_displacements",
"(",
"symmetry",
",",
"is_plusminus",
"=",
"'auto'",
",",
"is_diagonal",
"=",
"True",
",",
"is_trigonal",
"=",
"False",
",",
"log_level",
"=",
"0",
")",
":",
"displacements",
"=",
"[",
"]",
"if",
"is_diagonal",
":",
"directi... | Return a set of displacements
Returns
-------
array_like
List of directions with respect to axes. This gives only the
symmetrically non equivalent directions. The format is like:
[[0, 1, 0, 0],
[7, 1, 0, 1], ...]
where each list is defined by:
First value: Atom index in supercell starting with 0
Second to fourth: If the direction is displaced or not (1, 0, or -1)
with respect to the axes. | [
"Return",
"a",
"set",
"of",
"displacements"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/displacement.py#L74-L127 |
241,405 | atztogo/phonopy | phonopy/interface/FHIaims.py | read_aims | def read_aims(filename):
"""Method to read FHI-aims geometry files in phonopy context."""
lines = open(filename, 'r').readlines()
cell = []
is_frac = []
positions = []
symbols = []
magmoms = []
for line in lines:
fields = line.split()
if not len(fields):
continue
if fields[0] == "lattice_vector":
vec = lmap(float, fields[1:4])
cell.append(vec)
elif fields[0][0:4] == "atom":
if fields[0] == "atom":
frac = False
elif fields[0] == "atom_frac":
frac = True
pos = lmap(float, fields[1:4])
sym = fields[4]
is_frac.append(frac)
positions.append(pos)
symbols.append(sym)
magmoms.append(None)
# implicitly assuming that initial_moments line adhere to FHI-aims geometry.in specification,
# i.e. two subsequent initial_moments lines do not occur
# if they do, the value specified in the last line is taken here - without any warning
elif fields[0] == "initial_moment":
magmoms[-1] = float(fields[1])
for (n,frac) in enumerate(is_frac):
if frac:
pos = [ sum( [ positions[n][l] * cell[l][i] for l in range(3) ] ) for i in range(3) ]
positions[n] = pos
if None in magmoms:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions)
else:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions, magmoms=magmoms)
return atoms | python | def read_aims(filename):
lines = open(filename, 'r').readlines()
cell = []
is_frac = []
positions = []
symbols = []
magmoms = []
for line in lines:
fields = line.split()
if not len(fields):
continue
if fields[0] == "lattice_vector":
vec = lmap(float, fields[1:4])
cell.append(vec)
elif fields[0][0:4] == "atom":
if fields[0] == "atom":
frac = False
elif fields[0] == "atom_frac":
frac = True
pos = lmap(float, fields[1:4])
sym = fields[4]
is_frac.append(frac)
positions.append(pos)
symbols.append(sym)
magmoms.append(None)
# implicitly assuming that initial_moments line adhere to FHI-aims geometry.in specification,
# i.e. two subsequent initial_moments lines do not occur
# if they do, the value specified in the last line is taken here - without any warning
elif fields[0] == "initial_moment":
magmoms[-1] = float(fields[1])
for (n,frac) in enumerate(is_frac):
if frac:
pos = [ sum( [ positions[n][l] * cell[l][i] for l in range(3) ] ) for i in range(3) ]
positions[n] = pos
if None in magmoms:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions)
else:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions, magmoms=magmoms)
return atoms | [
"def",
"read_aims",
"(",
"filename",
")",
":",
"lines",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"cell",
"=",
"[",
"]",
"is_frac",
"=",
"[",
"]",
"positions",
"=",
"[",
"]",
"symbols",
"=",
"[",
"]",
"magmoms",
"... | Method to read FHI-aims geometry files in phonopy context. | [
"Method",
"to",
"read",
"FHI",
"-",
"aims",
"geometry",
"files",
"in",
"phonopy",
"context",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L49-L92 |
241,406 | atztogo/phonopy | phonopy/interface/FHIaims.py | write_aims | def write_aims(filename, atoms):
"""Method to write FHI-aims geometry files in phonopy context."""
lines = ""
lines += "# geometry.in for FHI-aims \n"
lines += "# | generated by phonopy.FHIaims.write_aims() \n"
lattice_vector_line = "lattice_vector " + "%16.16f "*3 + "\n"
for vec in atoms.get_cell():
lines += lattice_vector_line % tuple(vec)
N = atoms.get_number_of_atoms()
atom_line = "atom " + "%16.16f "*3 + "%s \n"
positions = atoms.get_positions()
symbols = atoms.get_chemical_symbols()
initial_moment_line = "initial_moment %16.6f\n"
magmoms = atoms.get_magnetic_moments()
for n in range(N):
lines += atom_line % (tuple(positions[n]) + (symbols[n],))
if magmoms is not None:
lines += initial_moment_line % magmoms[n]
with open(filename, 'w') as f:
f.write(lines) | python | def write_aims(filename, atoms):
lines = ""
lines += "# geometry.in for FHI-aims \n"
lines += "# | generated by phonopy.FHIaims.write_aims() \n"
lattice_vector_line = "lattice_vector " + "%16.16f "*3 + "\n"
for vec in atoms.get_cell():
lines += lattice_vector_line % tuple(vec)
N = atoms.get_number_of_atoms()
atom_line = "atom " + "%16.16f "*3 + "%s \n"
positions = atoms.get_positions()
symbols = atoms.get_chemical_symbols()
initial_moment_line = "initial_moment %16.6f\n"
magmoms = atoms.get_magnetic_moments()
for n in range(N):
lines += atom_line % (tuple(positions[n]) + (symbols[n],))
if magmoms is not None:
lines += initial_moment_line % magmoms[n]
with open(filename, 'w') as f:
f.write(lines) | [
"def",
"write_aims",
"(",
"filename",
",",
"atoms",
")",
":",
"lines",
"=",
"\"\"",
"lines",
"+=",
"\"# geometry.in for FHI-aims \\n\"",
"lines",
"+=",
"\"# | generated by phonopy.FHIaims.write_aims() \\n\"",
"lattice_vector_line",
"=",
"\"lattice_vector \"",
"+",
"\"%16.16... | Method to write FHI-aims geometry files in phonopy context. | [
"Method",
"to",
"write",
"FHI",
"-",
"aims",
"geometry",
"files",
"in",
"phonopy",
"context",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L95-L121 |
241,407 | atztogo/phonopy | phonopy/interface/FHIaims.py | read_aims_output | def read_aims_output(filename):
""" Read FHI-aims output and
return geometry, energy and forces from last self-consistency iteration"""
lines = open(filename, 'r').readlines()
l = 0
N = 0
while l < len(lines):
line = lines[l]
if "| Number of atoms" in line:
N = int(line.split()[5])
elif "| Unit cell:" in line:
cell = []
for i in range(3):
l += 1
vec = lmap(float, lines[l].split()[1:4])
cell.append(vec)
elif ("Atomic structure:" in line) or ("Updated atomic structure:" in line):
if "Atomic structure:" in line:
i_sym = 3
i_pos_min = 4 ; i_pos_max = 7
elif "Updated atomic structure:" in line:
i_sym = 4
i_pos_min = 1 ; i_pos_max = 4
l += 1
symbols = []
positions = []
for n in range(N):
l += 1
fields = lines[l].split()
sym = fields[i_sym]
pos = lmap(float, fields[i_pos_min:i_pos_max])
symbols.append(sym)
positions.append(pos)
elif "Total atomic forces" in line:
forces = []
for i in range(N):
l += 1
force = lmap(float, lines[l].split()[-3:])
forces.append(force)
l += 1
atoms = Atoms_with_forces(cell=cell, symbols=symbols, positions=positions)
atoms.forces = forces
return atoms | python | def read_aims_output(filename):
lines = open(filename, 'r').readlines()
l = 0
N = 0
while l < len(lines):
line = lines[l]
if "| Number of atoms" in line:
N = int(line.split()[5])
elif "| Unit cell:" in line:
cell = []
for i in range(3):
l += 1
vec = lmap(float, lines[l].split()[1:4])
cell.append(vec)
elif ("Atomic structure:" in line) or ("Updated atomic structure:" in line):
if "Atomic structure:" in line:
i_sym = 3
i_pos_min = 4 ; i_pos_max = 7
elif "Updated atomic structure:" in line:
i_sym = 4
i_pos_min = 1 ; i_pos_max = 4
l += 1
symbols = []
positions = []
for n in range(N):
l += 1
fields = lines[l].split()
sym = fields[i_sym]
pos = lmap(float, fields[i_pos_min:i_pos_max])
symbols.append(sym)
positions.append(pos)
elif "Total atomic forces" in line:
forces = []
for i in range(N):
l += 1
force = lmap(float, lines[l].split()[-3:])
forces.append(force)
l += 1
atoms = Atoms_with_forces(cell=cell, symbols=symbols, positions=positions)
atoms.forces = forces
return atoms | [
"def",
"read_aims_output",
"(",
"filename",
")",
":",
"lines",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"l",
"=",
"0",
"N",
"=",
"0",
"while",
"l",
"<",
"len",
"(",
"lines",
")",
":",
"line",
"=",
"lines",
"[",
... | Read FHI-aims output and
return geometry, energy and forces from last self-consistency iteration | [
"Read",
"FHI",
"-",
"aims",
"output",
"and",
"return",
"geometry",
"energy",
"and",
"forces",
"from",
"last",
"self",
"-",
"consistency",
"iteration"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L132-L178 |
241,408 | atztogo/phonopy | phonopy/structure/symmetry.py | find_primitive | def find_primitive(cell, symprec=1e-5):
"""
A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned.
"""
lattice, positions, numbers = spg.find_primitive(cell.totuple(), symprec)
if lattice is None:
return None
else:
return Atoms(numbers=numbers,
scaled_positions=positions,
cell=lattice,
pbc=True) | python | def find_primitive(cell, symprec=1e-5):
lattice, positions, numbers = spg.find_primitive(cell.totuple(), symprec)
if lattice is None:
return None
else:
return Atoms(numbers=numbers,
scaled_positions=positions,
cell=lattice,
pbc=True) | [
"def",
"find_primitive",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
")",
":",
"lattice",
",",
"positions",
",",
"numbers",
"=",
"spg",
".",
"find_primitive",
"(",
"cell",
".",
"totuple",
"(",
")",
",",
"symprec",
")",
"if",
"lattice",
"is",
"None",
":",... | A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned. | [
"A",
"primitive",
"cell",
"is",
"searched",
"in",
"the",
"input",
"cell",
".",
"When",
"a",
"primitive",
"cell",
"is",
"found",
"an",
"object",
"of",
"Atoms",
"class",
"of",
"the",
"primitive",
"cell",
"is",
"returned",
".",
"When",
"not",
"None",
"is",
... | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L300-L313 |
241,409 | atztogo/phonopy | phonopy/structure/symmetry.py | elaborate_borns_and_epsilon | def elaborate_borns_and_epsilon(ucell,
borns,
epsilon,
primitive_matrix=None,
supercell_matrix=None,
is_symmetry=True,
symmetrize_tensors=False,
symprec=1e-5):
"""Symmetrize Born effective charges and dielectric constants and
extract Born effective charges of symmetrically independent atoms
for primitive cell.
Args:
ucell (Atoms): Unit cell structure
borns (np.array): Born effective charges of ucell
epsilon (np.array): Dielectric constant tensor
Returns:
(np.array) Born effective charges of symmetrically independent atoms
in primitive cell
(np.array) Dielectric constant
(np.array) Atomic index mapping table from supercell to primitive cell
of independent atoms
Raises:
AssertionError: Inconsistency of number of atoms or Born effective
charges.
Warning:
Broken symmetry of Born effective charges
"""
assert len(borns) == ucell.get_number_of_atoms(), \
"num_atom %d != len(borns) %d" % (ucell.get_number_of_atoms(),
len(borns))
if symmetrize_tensors:
borns_, epsilon_ = symmetrize_borns_and_epsilon(
borns,
epsilon,
ucell,
symprec=symprec,
is_symmetry=is_symmetry)
else:
borns_ = borns
epsilon_ = epsilon
indeps_in_supercell, indeps_in_unitcell = _extract_independent_atoms(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
is_symmetry=is_symmetry,
symprec=symprec)
return borns_[indeps_in_unitcell].copy(), epsilon_, indeps_in_supercell | python | def elaborate_borns_and_epsilon(ucell,
borns,
epsilon,
primitive_matrix=None,
supercell_matrix=None,
is_symmetry=True,
symmetrize_tensors=False,
symprec=1e-5):
assert len(borns) == ucell.get_number_of_atoms(), \
"num_atom %d != len(borns) %d" % (ucell.get_number_of_atoms(),
len(borns))
if symmetrize_tensors:
borns_, epsilon_ = symmetrize_borns_and_epsilon(
borns,
epsilon,
ucell,
symprec=symprec,
is_symmetry=is_symmetry)
else:
borns_ = borns
epsilon_ = epsilon
indeps_in_supercell, indeps_in_unitcell = _extract_independent_atoms(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
is_symmetry=is_symmetry,
symprec=symprec)
return borns_[indeps_in_unitcell].copy(), epsilon_, indeps_in_supercell | [
"def",
"elaborate_borns_and_epsilon",
"(",
"ucell",
",",
"borns",
",",
"epsilon",
",",
"primitive_matrix",
"=",
"None",
",",
"supercell_matrix",
"=",
"None",
",",
"is_symmetry",
"=",
"True",
",",
"symmetrize_tensors",
"=",
"False",
",",
"symprec",
"=",
"1e-5",
... | Symmetrize Born effective charges and dielectric constants and
extract Born effective charges of symmetrically independent atoms
for primitive cell.
Args:
ucell (Atoms): Unit cell structure
borns (np.array): Born effective charges of ucell
epsilon (np.array): Dielectric constant tensor
Returns:
(np.array) Born effective charges of symmetrically independent atoms
in primitive cell
(np.array) Dielectric constant
(np.array) Atomic index mapping table from supercell to primitive cell
of independent atoms
Raises:
AssertionError: Inconsistency of number of atoms or Born effective
charges.
Warning:
Broken symmetry of Born effective charges | [
"Symmetrize",
"Born",
"effective",
"charges",
"and",
"dielectric",
"constants",
"and",
"extract",
"Born",
"effective",
"charges",
"of",
"symmetrically",
"independent",
"atoms",
"for",
"primitive",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L343-L399 |
241,410 | atztogo/phonopy | phonopy/structure/symmetry.py | symmetrize_borns_and_epsilon | def symmetrize_borns_and_epsilon(borns,
epsilon,
ucell,
primitive_matrix=None,
supercell_matrix=None,
symprec=1e-5,
is_symmetry=True):
"""Symmetrize Born effective charges and dielectric tensor
Parameters
----------
borns: array_like
Born effective charges.
shape=(unitcell_atoms, 3, 3)
dtype='double'
epsilon: array_like
Dielectric constant
shape=(3, 3)
dtype='double'
ucell: PhonopyAtoms
Unit cell
primitive_matrix: array_like, optional
Primitive matrix. This is used to select Born effective charges in
primitive cell. If None (default), Born effective charges in unit cell
are returned.
shape=(3, 3)
dtype='double'
supercell_matrix: array_like, optional
Supercell matrix. This is used to select Born effective charges in
**primitive cell**. Supercell matrix is needed because primitive
cell is created first creating supercell from unit cell, then
the primitive cell is created from the supercell. If None (defautl),
1x1x1 supercell is created.
shape=(3, 3)
dtype='int'
symprec: float, optional
Symmetry tolerance. Default is 1e-5
is_symmetry: bool, optinal
By setting False, symmetrization can be switched off. Default is True.
"""
lattice = ucell.get_cell()
positions = ucell.get_scaled_positions()
u_sym = Symmetry(ucell, is_symmetry=is_symmetry, symprec=symprec)
rotations = u_sym.get_symmetry_operations()['rotations']
translations = u_sym.get_symmetry_operations()['translations']
ptg_ops = u_sym.get_pointgroup_operations()
epsilon_ = _symmetrize_2nd_rank_tensor(epsilon, ptg_ops, lattice)
for i, Z in enumerate(borns):
site_sym = u_sym.get_site_symmetry(i)
Z = _symmetrize_2nd_rank_tensor(Z, site_sym, lattice)
borns_ = np.zeros_like(borns)
for i in range(len(borns)):
count = 0
for r, t in zip(rotations, translations):
count += 1
diff = np.dot(positions, r.T) + t - positions[i]
diff -= np.rint(diff)
dist = np.sqrt(np.sum(np.dot(diff, lattice) ** 2, axis=1))
j = np.nonzero(dist < symprec)[0][0]
r_cart = similarity_transformation(lattice.T, r)
borns_[i] += similarity_transformation(r_cart, borns[j])
borns_[i] /= count
sum_born = borns_.sum(axis=0) / len(borns_)
borns_ -= sum_born
if (abs(borns - borns_) > 0.1).any():
lines = ["Born effective charge symmetry is largely broken. "
"Largest different among elements: "
"%s" % np.amax(abs(borns - borns_))]
import warnings
warnings.warn("\n".join(lines))
if primitive_matrix is None:
return borns_, epsilon_
else:
scell, pcell = _get_supercell_and_primitive(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
symprec=symprec)
idx = [scell.u2u_map[i] for i in scell.s2u_map[pcell.p2s_map]]
return borns_[idx], epsilon_ | python | def symmetrize_borns_and_epsilon(borns,
epsilon,
ucell,
primitive_matrix=None,
supercell_matrix=None,
symprec=1e-5,
is_symmetry=True):
lattice = ucell.get_cell()
positions = ucell.get_scaled_positions()
u_sym = Symmetry(ucell, is_symmetry=is_symmetry, symprec=symprec)
rotations = u_sym.get_symmetry_operations()['rotations']
translations = u_sym.get_symmetry_operations()['translations']
ptg_ops = u_sym.get_pointgroup_operations()
epsilon_ = _symmetrize_2nd_rank_tensor(epsilon, ptg_ops, lattice)
for i, Z in enumerate(borns):
site_sym = u_sym.get_site_symmetry(i)
Z = _symmetrize_2nd_rank_tensor(Z, site_sym, lattice)
borns_ = np.zeros_like(borns)
for i in range(len(borns)):
count = 0
for r, t in zip(rotations, translations):
count += 1
diff = np.dot(positions, r.T) + t - positions[i]
diff -= np.rint(diff)
dist = np.sqrt(np.sum(np.dot(diff, lattice) ** 2, axis=1))
j = np.nonzero(dist < symprec)[0][0]
r_cart = similarity_transformation(lattice.T, r)
borns_[i] += similarity_transformation(r_cart, borns[j])
borns_[i] /= count
sum_born = borns_.sum(axis=0) / len(borns_)
borns_ -= sum_born
if (abs(borns - borns_) > 0.1).any():
lines = ["Born effective charge symmetry is largely broken. "
"Largest different among elements: "
"%s" % np.amax(abs(borns - borns_))]
import warnings
warnings.warn("\n".join(lines))
if primitive_matrix is None:
return borns_, epsilon_
else:
scell, pcell = _get_supercell_and_primitive(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
symprec=symprec)
idx = [scell.u2u_map[i] for i in scell.s2u_map[pcell.p2s_map]]
return borns_[idx], epsilon_ | [
"def",
"symmetrize_borns_and_epsilon",
"(",
"borns",
",",
"epsilon",
",",
"ucell",
",",
"primitive_matrix",
"=",
"None",
",",
"supercell_matrix",
"=",
"None",
",",
"symprec",
"=",
"1e-5",
",",
"is_symmetry",
"=",
"True",
")",
":",
"lattice",
"=",
"ucell",
".... | Symmetrize Born effective charges and dielectric tensor
Parameters
----------
borns: array_like
Born effective charges.
shape=(unitcell_atoms, 3, 3)
dtype='double'
epsilon: array_like
Dielectric constant
shape=(3, 3)
dtype='double'
ucell: PhonopyAtoms
Unit cell
primitive_matrix: array_like, optional
Primitive matrix. This is used to select Born effective charges in
primitive cell. If None (default), Born effective charges in unit cell
are returned.
shape=(3, 3)
dtype='double'
supercell_matrix: array_like, optional
Supercell matrix. This is used to select Born effective charges in
**primitive cell**. Supercell matrix is needed because primitive
cell is created first creating supercell from unit cell, then
the primitive cell is created from the supercell. If None (defautl),
1x1x1 supercell is created.
shape=(3, 3)
dtype='int'
symprec: float, optional
Symmetry tolerance. Default is 1e-5
is_symmetry: bool, optinal
By setting False, symmetrization can be switched off. Default is True. | [
"Symmetrize",
"Born",
"effective",
"charges",
"and",
"dielectric",
"tensor"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L402-L488 |
241,411 | atztogo/phonopy | phonopy/interface/dftbp.py | read_dftbp | def read_dftbp(filename):
""" Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename
"""
infile = open(filename, 'r')
lines = infile.readlines()
# remove any comments
for ss in lines:
if ss.strip().startswith('#'):
lines.remove(ss)
natoms = int(lines[0].split()[0])
symbols = lines[1].split()
if (lines[0].split()[1].lower() == 'f'):
is_scaled = True
scale_pos = 1
scale_latvecs = dftbpToBohr
else:
is_scaled = False
scale_pos = dftbpToBohr
scale_latvecs = dftbpToBohr
# assign positions and expanded symbols
positions = []
expaned_symbols = []
for ii in range(2, natoms+2):
lsplit = lines[ii].split()
expaned_symbols.append(symbols[int(lsplit[1]) - 1])
positions.append([float(ss)*scale_pos for ss in lsplit[2:5]])
# origin is ignored, may be used in future
origin = [float(ss) for ss in lines[natoms+2].split()]
# assign coords of unitcell
cell = []
for ii in range(natoms+3, natoms+6):
lsplit = lines[ii].split()
cell.append([float(ss)*scale_latvecs for ss in lsplit[:3]])
cell = np.array(cell)
if is_scaled:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
scaled_positions=positions)
else:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
positions=positions)
return atoms | python | def read_dftbp(filename):
infile = open(filename, 'r')
lines = infile.readlines()
# remove any comments
for ss in lines:
if ss.strip().startswith('#'):
lines.remove(ss)
natoms = int(lines[0].split()[0])
symbols = lines[1].split()
if (lines[0].split()[1].lower() == 'f'):
is_scaled = True
scale_pos = 1
scale_latvecs = dftbpToBohr
else:
is_scaled = False
scale_pos = dftbpToBohr
scale_latvecs = dftbpToBohr
# assign positions and expanded symbols
positions = []
expaned_symbols = []
for ii in range(2, natoms+2):
lsplit = lines[ii].split()
expaned_symbols.append(symbols[int(lsplit[1]) - 1])
positions.append([float(ss)*scale_pos for ss in lsplit[2:5]])
# origin is ignored, may be used in future
origin = [float(ss) for ss in lines[natoms+2].split()]
# assign coords of unitcell
cell = []
for ii in range(natoms+3, natoms+6):
lsplit = lines[ii].split()
cell.append([float(ss)*scale_latvecs for ss in lsplit[:3]])
cell = np.array(cell)
if is_scaled:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
scaled_positions=positions)
else:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
positions=positions)
return atoms | [
"def",
"read_dftbp",
"(",
"filename",
")",
":",
"infile",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"lines",
"=",
"infile",
".",
"readlines",
"(",
")",
"# remove any comments",
"for",
"ss",
"in",
"lines",
":",
"if",
"ss",
".",
"strip",
"(",
")",
... | Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename | [
"Reads",
"DFTB",
"+",
"structure",
"files",
"in",
"gen",
"format",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L72-L135 |
241,412 | atztogo/phonopy | phonopy/interface/dftbp.py | get_reduced_symbols | def get_reduced_symbols(symbols):
"""Reduces expanded list of symbols.
Args:
symbols: list containing any chemical symbols as often as
the atom appears in the structure
Returns:
reduced_symbols: any symbols appears only once
"""
reduced_symbols = []
for ss in symbols:
if not (ss in reduced_symbols):
reduced_symbols.append(ss)
return reduced_symbols | python | def get_reduced_symbols(symbols):
reduced_symbols = []
for ss in symbols:
if not (ss in reduced_symbols):
reduced_symbols.append(ss)
return reduced_symbols | [
"def",
"get_reduced_symbols",
"(",
"symbols",
")",
":",
"reduced_symbols",
"=",
"[",
"]",
"for",
"ss",
"in",
"symbols",
":",
"if",
"not",
"(",
"ss",
"in",
"reduced_symbols",
")",
":",
"reduced_symbols",
".",
"append",
"(",
"ss",
")",
"return",
"reduced_sym... | Reduces expanded list of symbols.
Args:
symbols: list containing any chemical symbols as often as
the atom appears in the structure
Returns:
reduced_symbols: any symbols appears only once | [
"Reduces",
"expanded",
"list",
"of",
"symbols",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L140-L157 |
241,413 | atztogo/phonopy | phonopy/interface/dftbp.py | write_dftbp | def write_dftbp(filename, atoms):
"""Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure
"""
scale_pos = dftbpToBohr
lines = ""
# 1. line, use absolute positions
natoms = atoms.get_number_of_atoms()
lines += str(natoms)
lines += ' S \n'
# 2. line
expaned_symbols = atoms.get_chemical_symbols()
symbols = get_reduced_symbols(expaned_symbols)
lines += ' '.join(symbols) + '\n'
atom_numbers = []
for ss in expaned_symbols:
atom_numbers.append(symbols.index(ss) + 1)
positions = atoms.get_positions()/scale_pos
for ii in range(natoms):
pos = positions[ii]
pos_str = "{:3d} {:3d} {:20.15f} {:20.15f} {:20.15f}\n".format(
ii + 1, atom_numbers[ii], pos[0], pos[1], pos[2])
lines += pos_str
# origin arbitrary
lines +='0.0 0.0 0.0\n'
cell = atoms.get_cell()/scale_pos
for ii in range(3):
cell_str = "{:20.15f} {:20.15f} {:20.15f}\n".format(
cell[ii][0], cell[ii][1], cell[ii][2])
lines += cell_str
outfile = open(filename, 'w')
outfile.write(lines) | python | def write_dftbp(filename, atoms):
scale_pos = dftbpToBohr
lines = ""
# 1. line, use absolute positions
natoms = atoms.get_number_of_atoms()
lines += str(natoms)
lines += ' S \n'
# 2. line
expaned_symbols = atoms.get_chemical_symbols()
symbols = get_reduced_symbols(expaned_symbols)
lines += ' '.join(symbols) + '\n'
atom_numbers = []
for ss in expaned_symbols:
atom_numbers.append(symbols.index(ss) + 1)
positions = atoms.get_positions()/scale_pos
for ii in range(natoms):
pos = positions[ii]
pos_str = "{:3d} {:3d} {:20.15f} {:20.15f} {:20.15f}\n".format(
ii + 1, atom_numbers[ii], pos[0], pos[1], pos[2])
lines += pos_str
# origin arbitrary
lines +='0.0 0.0 0.0\n'
cell = atoms.get_cell()/scale_pos
for ii in range(3):
cell_str = "{:20.15f} {:20.15f} {:20.15f}\n".format(
cell[ii][0], cell[ii][1], cell[ii][2])
lines += cell_str
outfile = open(filename, 'w')
outfile.write(lines) | [
"def",
"write_dftbp",
"(",
"filename",
",",
"atoms",
")",
":",
"scale_pos",
"=",
"dftbpToBohr",
"lines",
"=",
"\"\"",
"# 1. line, use absolute positions",
"natoms",
"=",
"atoms",
".",
"get_number_of_atoms",
"(",
")",
"lines",
"+=",
"str",
"(",
"natoms",
")",
"... | Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure | [
"Writes",
"DFTB",
"+",
"readable",
"gen",
"-",
"formatted",
"structure",
"files"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L159-L203 |
241,414 | atztogo/phonopy | phonopy/interface/dftbp.py | write_supercells_with_displacements | def write_supercells_with_displacements(supercell, cells_with_disps, filename="geo.gen"):
"""Writes perfect supercell and supercells with displacements
Args:
supercell: perfect supercell
cells_with_disps: supercells with displaced atoms
filename: root-filename
"""
# original cell
write_dftbp(filename + "S", supercell)
# displaced cells
for ii in range(len(cells_with_disps)):
write_dftbp(filename + "S-{:03d}".format(ii+1), cells_with_disps[ii]) | python | def write_supercells_with_displacements(supercell, cells_with_disps, filename="geo.gen"):
# original cell
write_dftbp(filename + "S", supercell)
# displaced cells
for ii in range(len(cells_with_disps)):
write_dftbp(filename + "S-{:03d}".format(ii+1), cells_with_disps[ii]) | [
"def",
"write_supercells_with_displacements",
"(",
"supercell",
",",
"cells_with_disps",
",",
"filename",
"=",
"\"geo.gen\"",
")",
":",
"# original cell",
"write_dftbp",
"(",
"filename",
"+",
"\"S\"",
",",
"supercell",
")",
"# displaced cells",
"for",
"ii",
"in",
"r... | Writes perfect supercell and supercells with displacements
Args:
supercell: perfect supercell
cells_with_disps: supercells with displaced atoms
filename: root-filename | [
"Writes",
"perfect",
"supercell",
"and",
"supercells",
"with",
"displacements"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L205-L219 |
241,415 | atztogo/phonopy | phonopy/interface/__init__.py | get_interface_mode | def get_interface_mode(args):
"""Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}.
"""
calculator_list = ['wien2k', 'abinit', 'qe', 'elk', 'siesta', 'cp2k',
'crystal', 'vasp', 'dftbp', 'turbomole']
for calculator in calculator_list:
mode = "%s_mode" % calculator
if mode in args and args.__dict__[mode]:
return calculator
return None | python | def get_interface_mode(args):
calculator_list = ['wien2k', 'abinit', 'qe', 'elk', 'siesta', 'cp2k',
'crystal', 'vasp', 'dftbp', 'turbomole']
for calculator in calculator_list:
mode = "%s_mode" % calculator
if mode in args and args.__dict__[mode]:
return calculator
return None | [
"def",
"get_interface_mode",
"(",
"args",
")",
":",
"calculator_list",
"=",
"[",
"'wien2k'",
",",
"'abinit'",
",",
"'qe'",
",",
"'elk'",
",",
"'siesta'",
",",
"'cp2k'",
",",
"'crystal'",
",",
"'vasp'",
",",
"'dftbp'",
",",
"'turbomole'",
"]",
"for",
"calcu... | Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}. | [
"Return",
"calculator",
"name"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/__init__.py#L40-L55 |
241,416 | atztogo/phonopy | phonopy/interface/__init__.py | get_default_physical_units | def get_default_physical_units(interface_mode=None):
"""Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree, au, AMU, hartree/au
qe : Ry, au, AMU, Ry/au
siesta : eV, au, AMU, eV/Angstroem
CRYSTAL : eV, Angstrom, AMU, eV/Angstroem
DFTB+ : hartree, au, AMU hartree/au
TURBOMOLE : hartree, au, AMU, hartree/au
"""
from phonopy.units import (Wien2kToTHz, AbinitToTHz, PwscfToTHz, ElkToTHz,
SiestaToTHz, VaspToTHz, CP2KToTHz, CrystalToTHz,
DftbpToTHz, TurbomoleToTHz, Hartree, Bohr)
units = {'factor': None,
'nac_factor': None,
'distance_to_A': None,
'force_constants_unit': None,
'length_unit': None}
if interface_mode is None or interface_mode == 'vasp':
units['factor'] = VaspToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'abinit':
units['factor'] = AbinitToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'qe':
units['factor'] = PwscfToTHz
units['nac_factor'] = 2.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'Ry/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'wien2k':
units['factor'] = Wien2kToTHz
units['nac_factor'] = 2000.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'mRy/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'elk':
units['factor'] = ElkToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'siesta':
units['factor'] = SiestaToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'cp2k':
units['factor'] = CP2KToTHz
units['nac_factor'] = Hartree / Bohr # in a.u.
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'crystal':
units['factor'] = CrystalToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'dftbp':
units['factor'] = DftbpToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'turbomole':
units['factor'] = TurbomoleToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
return units | python | def get_default_physical_units(interface_mode=None):
from phonopy.units import (Wien2kToTHz, AbinitToTHz, PwscfToTHz, ElkToTHz,
SiestaToTHz, VaspToTHz, CP2KToTHz, CrystalToTHz,
DftbpToTHz, TurbomoleToTHz, Hartree, Bohr)
units = {'factor': None,
'nac_factor': None,
'distance_to_A': None,
'force_constants_unit': None,
'length_unit': None}
if interface_mode is None or interface_mode == 'vasp':
units['factor'] = VaspToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'abinit':
units['factor'] = AbinitToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'qe':
units['factor'] = PwscfToTHz
units['nac_factor'] = 2.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'Ry/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'wien2k':
units['factor'] = Wien2kToTHz
units['nac_factor'] = 2000.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'mRy/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'elk':
units['factor'] = ElkToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'siesta':
units['factor'] = SiestaToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'cp2k':
units['factor'] = CP2KToTHz
units['nac_factor'] = Hartree / Bohr # in a.u.
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'crystal':
units['factor'] = CrystalToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'dftbp':
units['factor'] = DftbpToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'turbomole':
units['factor'] = TurbomoleToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
return units | [
"def",
"get_default_physical_units",
"(",
"interface_mode",
"=",
"None",
")",
":",
"from",
"phonopy",
".",
"units",
"import",
"(",
"Wien2kToTHz",
",",
"AbinitToTHz",
",",
"PwscfToTHz",
",",
"ElkToTHz",
",",
"SiestaToTHz",
",",
"VaspToTHz",
",",
"CP2KToTHz",
",",... | Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree, au, AMU, hartree/au
qe : Ry, au, AMU, Ry/au
siesta : eV, au, AMU, eV/Angstroem
CRYSTAL : eV, Angstrom, AMU, eV/Angstroem
DFTB+ : hartree, au, AMU hartree/au
TURBOMOLE : hartree, au, AMU, hartree/au | [
"Return",
"physical",
"units",
"used",
"for",
"calculators"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/__init__.py#L231-L318 |
241,417 | atztogo/phonopy | phonopy/structure/tetrahedron_method.py | get_tetrahedra_integration_weight | def get_tetrahedra_integration_weight(omegas,
tetrahedra_omegas,
function='I'):
"""Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function : str, 'I' or 'J'
'J' is for intetration and 'I' is for its derivative.
"""
if isinstance(omegas, float):
return phonoc.tetrahedra_integration_weight(
omegas,
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
else:
integration_weights = np.zeros(len(omegas), dtype='double')
phonoc.tetrahedra_integration_weight_at_omegas(
integration_weights,
np.array(omegas, dtype='double'),
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
return integration_weights | python | def get_tetrahedra_integration_weight(omegas,
tetrahedra_omegas,
function='I'):
if isinstance(omegas, float):
return phonoc.tetrahedra_integration_weight(
omegas,
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
else:
integration_weights = np.zeros(len(omegas), dtype='double')
phonoc.tetrahedra_integration_weight_at_omegas(
integration_weights,
np.array(omegas, dtype='double'),
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
return integration_weights | [
"def",
"get_tetrahedra_integration_weight",
"(",
"omegas",
",",
"tetrahedra_omegas",
",",
"function",
"=",
"'I'",
")",
":",
"if",
"isinstance",
"(",
"omegas",
",",
"float",
")",
":",
"return",
"phonoc",
".",
"tetrahedra_integration_weight",
"(",
"omegas",
",",
"... | Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function : str, 'I' or 'J'
'J' is for intetration and 'I' is for its derivative. | [
"Returns",
"integration",
"weights"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L95-L125 |
241,418 | atztogo/phonopy | phonopy/structure/tetrahedron_method.py | TetrahedronMethod._g_1 | def _g_1(self):
"""omega1 < omega < omega2"""
# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])
return (3 * self._f(1, 0) * self._f(2, 0) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | python | def _g_1(self):
# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])
return (3 * self._f(1, 0) * self._f(2, 0) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | [
"def",
"_g_1",
"(",
"self",
")",
":",
"# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])",
"return",
"(",
"3",
"*",
"self",
".",
"_f",
"(",
"1",
",",
"0",
")",
"*",
"self",
".",
"_f",
"(",
"2",
",",
"0",
")",
"/",
"(",
"self",
".",
"_... | omega1 < omega < omega2 | [
"omega1",
"<",
"omega",
"<",
"omega2"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L438-L442 |
241,419 | atztogo/phonopy | phonopy/structure/tetrahedron_method.py | TetrahedronMethod._g_3 | def _g_3(self):
"""omega3 < omega < omega4"""
# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)
return (3 * self._f(1, 3) * self._f(2, 3) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | python | def _g_3(self):
# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)
return (3 * self._f(1, 3) * self._f(2, 3) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | [
"def",
"_g_3",
"(",
"self",
")",
":",
"# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)",
"return",
"(",
"3",
"*",
"self",
".",
"_f",
"(",
"1",
",",
"3",
")",
"*",
"self",
".",
"_f",
"(",
"2",
",",
"3",
")",
"/",
"(",
"self",
"... | omega3 < omega < omega4 | [
"omega3",
"<",
"omega",
"<",
"omega4"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L450-L454 |
241,420 | mattupstate/flask-security | flask_security/datastore.py | UserDatastore.deactivate_user | def deactivate_user(self, user):
"""Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate
"""
if user.active:
user.active = False
return True
return False | python | def deactivate_user(self, user):
if user.active:
user.active = False
return True
return False | [
"def",
"deactivate_user",
"(",
"self",
",",
"user",
")",
":",
"if",
"user",
".",
"active",
":",
"user",
".",
"active",
"=",
"False",
"return",
"True",
"return",
"False"
] | Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate | [
"Deactivates",
"a",
"specified",
"user",
".",
"Returns",
"True",
"if",
"a",
"change",
"was",
"made",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L180-L188 |
241,421 | mattupstate/flask-security | flask_security/datastore.py | UserDatastore.activate_user | def activate_user(self, user):
"""Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate
"""
if not user.active:
user.active = True
return True
return False | python | def activate_user(self, user):
if not user.active:
user.active = True
return True
return False | [
"def",
"activate_user",
"(",
"self",
",",
"user",
")",
":",
"if",
"not",
"user",
".",
"active",
":",
"user",
".",
"active",
"=",
"True",
"return",
"True",
"return",
"False"
] | Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate | [
"Activates",
"a",
"specified",
"user",
".",
"Returns",
"True",
"if",
"a",
"change",
"was",
"made",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L190-L198 |
241,422 | mattupstate/flask-security | flask_security/datastore.py | UserDatastore.create_role | def create_role(self, **kwargs):
"""Creates and returns a new role from the given parameters."""
role = self.role_model(**kwargs)
return self.put(role) | python | def create_role(self, **kwargs):
role = self.role_model(**kwargs)
return self.put(role) | [
"def",
"create_role",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"role",
"=",
"self",
".",
"role_model",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"put",
"(",
"role",
")"
] | Creates and returns a new role from the given parameters. | [
"Creates",
"and",
"returns",
"a",
"new",
"role",
"from",
"the",
"given",
"parameters",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L200-L204 |
241,423 | mattupstate/flask-security | flask_security/datastore.py | UserDatastore.find_or_create_role | def find_or_create_role(self, name, **kwargs):
"""Returns a role matching the given name or creates it with any
additionally provided parameters.
"""
kwargs["name"] = name
return self.find_role(name) or self.create_role(**kwargs) | python | def find_or_create_role(self, name, **kwargs):
kwargs["name"] = name
return self.find_role(name) or self.create_role(**kwargs) | [
"def",
"find_or_create_role",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"name\"",
"]",
"=",
"name",
"return",
"self",
".",
"find_role",
"(",
"name",
")",
"or",
"self",
".",
"create_role",
"(",
"*",
"*",
"kwargs",
"... | Returns a role matching the given name or creates it with any
additionally provided parameters. | [
"Returns",
"a",
"role",
"matching",
"the",
"given",
"name",
"or",
"creates",
"it",
"with",
"any",
"additionally",
"provided",
"parameters",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L206-L211 |
241,424 | mattupstate/flask-security | flask_security/decorators.py | http_auth_required | def http_auth_required(realm):
"""Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name"""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if _check_http_auth():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
r = _security.default_http_auth_realm \
if callable(realm) else realm
h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
return _get_unauthorized_response(headers=h)
return wrapper
if callable(realm):
return decorator(realm)
return decorator | python | def http_auth_required(realm):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if _check_http_auth():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
r = _security.default_http_auth_realm \
if callable(realm) else realm
h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
return _get_unauthorized_response(headers=h)
return wrapper
if callable(realm):
return decorator(realm)
return decorator | [
"def",
"http_auth_required",
"(",
"realm",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_check_http_auth",
"(",
")",
":",
"return",
"f... | Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name | [
"Decorator",
"that",
"protects",
"endpoints",
"using",
"Basic",
"HTTP",
"authentication",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/decorators.py#L93-L114 |
241,425 | mattupstate/flask-security | flask_security/decorators.py | auth_token_required | def auth_token_required(fn):
"""Decorator that protects endpoints using token authentication. The token
should be added to the request by the client by using a query string
variable with a name equal to the configuration value of
`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER`
"""
@wraps(fn)
def decorated(*args, **kwargs):
if _check_token():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
return _get_unauthorized_response()
return decorated | python | def auth_token_required(fn):
@wraps(fn)
def decorated(*args, **kwargs):
if _check_token():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
return _get_unauthorized_response()
return decorated | [
"def",
"auth_token_required",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_check_token",
"(",
")",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwarg... | Decorator that protects endpoints using token authentication. The token
should be added to the request by the client by using a query string
variable with a name equal to the configuration value of
`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER` | [
"Decorator",
"that",
"protects",
"endpoints",
"using",
"token",
"authentication",
".",
"The",
"token",
"should",
"be",
"added",
"to",
"the",
"request",
"by",
"the",
"client",
"by",
"using",
"a",
"query",
"string",
"variable",
"with",
"a",
"name",
"equal",
"t... | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/decorators.py#L117-L133 |
241,426 | mattupstate/flask-security | flask_security/confirmable.py | confirm_user | def confirm_user(user):
"""Confirms the specified user
:param user: The user to confirm
"""
if user.confirmed_at is not None:
return False
user.confirmed_at = _security.datetime_factory()
_datastore.put(user)
user_confirmed.send(app._get_current_object(), user=user)
return True | python | def confirm_user(user):
if user.confirmed_at is not None:
return False
user.confirmed_at = _security.datetime_factory()
_datastore.put(user)
user_confirmed.send(app._get_current_object(), user=user)
return True | [
"def",
"confirm_user",
"(",
"user",
")",
":",
"if",
"user",
".",
"confirmed_at",
"is",
"not",
"None",
":",
"return",
"False",
"user",
".",
"confirmed_at",
"=",
"_security",
".",
"datetime_factory",
"(",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"u... | Confirms the specified user
:param user: The user to confirm | [
"Confirms",
"the",
"specified",
"user"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/confirmable.py#L82-L92 |
241,427 | mattupstate/flask-security | flask_security/recoverable.py | send_password_reset_notice | def send_password_reset_notice(user):
"""Sends the password reset notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_RESET_NOTICE_EMAIL'):
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORD_NOTICE'),
user.email, 'reset_notice', user=user) | python | def send_password_reset_notice(user):
if config_value('SEND_PASSWORD_RESET_NOTICE_EMAIL'):
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORD_NOTICE'),
user.email, 'reset_notice', user=user) | [
"def",
"send_password_reset_notice",
"(",
"user",
")",
":",
"if",
"config_value",
"(",
"'SEND_PASSWORD_RESET_NOTICE_EMAIL'",
")",
":",
"_security",
".",
"send_mail",
"(",
"config_value",
"(",
"'EMAIL_SUBJECT_PASSWORD_NOTICE'",
")",
",",
"user",
".",
"email",
",",
"'... | Sends the password reset notice email for the specified user.
:param user: The user to send the notice to | [
"Sends",
"the",
"password",
"reset",
"notice",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/recoverable.py#L45-L52 |
241,428 | mattupstate/flask-security | flask_security/recoverable.py | update_password | def update_password(user, password):
"""Update the specified user's password
:param user: The user to update_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_reset_notice(user)
password_reset.send(app._get_current_object(), user=user) | python | def update_password(user, password):
user.password = hash_password(password)
_datastore.put(user)
send_password_reset_notice(user)
password_reset.send(app._get_current_object(), user=user) | [
"def",
"update_password",
"(",
"user",
",",
"password",
")",
":",
"user",
".",
"password",
"=",
"hash_password",
"(",
"password",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"send_password_reset_notice",
"(",
"user",
")",
"password_reset",
".",
"send",
... | Update the specified user's password
:param user: The user to update_password
:param password: The unhashed new password | [
"Update",
"the",
"specified",
"user",
"s",
"password"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/recoverable.py#L84-L93 |
241,429 | mattupstate/flask-security | flask_security/core.py | Security.init_app | def init_app(self, app, datastore=None, register_blueprint=None, **kwargs):
"""Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blueprint: to register the Security blueprint or not.
"""
self.app = app
if datastore is None:
datastore = self._datastore
if register_blueprint is None:
register_blueprint = self._register_blueprint
for key, value in self._kwargs.items():
kwargs.setdefault(key, value)
for key, value in _default_config.items():
app.config.setdefault('SECURITY_' + key, value)
for key, value in _default_messages.items():
app.config.setdefault('SECURITY_MSG_' + key, value)
identity_loaded.connect_via(app)(_on_identity_loaded)
self._state = state = _get_state(app, datastore, **kwargs)
if register_blueprint:
app.register_blueprint(create_blueprint(state, __name__))
app.context_processor(_context_processor)
@app.before_first_request
def _register_i18n():
if '_' not in app.jinja_env.globals:
app.jinja_env.globals['_'] = state.i18n_domain.gettext
state.render_template = self.render_template
state.send_mail = self.send_mail
app.extensions['security'] = state
if hasattr(app, 'cli'):
from .cli import users, roles
if state.cli_users_name:
app.cli.add_command(users, state.cli_users_name)
if state.cli_roles_name:
app.cli.add_command(roles, state.cli_roles_name)
return state | python | def init_app(self, app, datastore=None, register_blueprint=None, **kwargs):
self.app = app
if datastore is None:
datastore = self._datastore
if register_blueprint is None:
register_blueprint = self._register_blueprint
for key, value in self._kwargs.items():
kwargs.setdefault(key, value)
for key, value in _default_config.items():
app.config.setdefault('SECURITY_' + key, value)
for key, value in _default_messages.items():
app.config.setdefault('SECURITY_MSG_' + key, value)
identity_loaded.connect_via(app)(_on_identity_loaded)
self._state = state = _get_state(app, datastore, **kwargs)
if register_blueprint:
app.register_blueprint(create_blueprint(state, __name__))
app.context_processor(_context_processor)
@app.before_first_request
def _register_i18n():
if '_' not in app.jinja_env.globals:
app.jinja_env.globals['_'] = state.i18n_domain.gettext
state.render_template = self.render_template
state.send_mail = self.send_mail
app.extensions['security'] = state
if hasattr(app, 'cli'):
from .cli import users, roles
if state.cli_users_name:
app.cli.add_command(users, state.cli_users_name)
if state.cli_roles_name:
app.cli.add_command(roles, state.cli_roles_name)
return state | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"datastore",
"=",
"None",
",",
"register_blueprint",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"app",
"=",
"app",
"if",
"datastore",
"is",
"None",
":",
"datastore",
"=",
"self",
".",... | Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blueprint: to register the Security blueprint or not. | [
"Initializes",
"the",
"Flask",
"-",
"Security",
"extension",
"for",
"the",
"specified",
"application",
"and",
"datastore",
"implementation",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/core.py#L511-L560 |
241,430 | mattupstate/flask-security | flask_security/views.py | login | def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
after_this_request(_commit)
if not request.is_json:
return redirect(get_post_login_redirect(form.next.data))
if request.is_json:
return _render_json(form, include_auth_token=True)
return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
login_user_form=form,
**_ctx('login')) | python | def login():
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
after_this_request(_commit)
if not request.is_json:
return redirect(get_post_login_redirect(form.next.data))
if request.is_json:
return _render_json(form, include_auth_token=True)
return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
login_user_form=form,
**_ctx('login')) | [
"def",
"login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_cl... | View function for login view | [
"View",
"function",
"for",
"login",
"view"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L67-L89 |
241,431 | mattupstate/flask-security | flask_security/views.py | register | def register():
"""View function which handles a registration request."""
if _security.confirmable or request.is_json:
form_class = _security.confirm_register_form
else:
form_class = _security.register_form
if request.is_json:
form_data = MultiDict(request.get_json())
else:
form_data = request.form
form = form_class(form_data)
if form.validate_on_submit():
user = register_user(**form.to_dict())
form.user = user
if not _security.confirmable or _security.login_without_confirmation:
after_this_request(_commit)
login_user(user)
if not request.is_json:
if 'next' in form:
redirect_url = get_post_register_redirect(form.next.data)
else:
redirect_url = get_post_register_redirect()
return redirect(redirect_url)
return _render_json(form, include_auth_token=True)
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
register_user_form=form,
**_ctx('register')) | python | def register():
if _security.confirmable or request.is_json:
form_class = _security.confirm_register_form
else:
form_class = _security.register_form
if request.is_json:
form_data = MultiDict(request.get_json())
else:
form_data = request.form
form = form_class(form_data)
if form.validate_on_submit():
user = register_user(**form.to_dict())
form.user = user
if not _security.confirmable or _security.login_without_confirmation:
after_this_request(_commit)
login_user(user)
if not request.is_json:
if 'next' in form:
redirect_url = get_post_register_redirect(form.next.data)
else:
redirect_url = get_post_register_redirect()
return redirect(redirect_url)
return _render_json(form, include_auth_token=True)
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
register_user_form=form,
**_ctx('register')) | [
"def",
"register",
"(",
")",
":",
"if",
"_security",
".",
"confirmable",
"or",
"request",
".",
"is_json",
":",
"form_class",
"=",
"_security",
".",
"confirm_register_form",
"else",
":",
"form_class",
"=",
"_security",
".",
"register_form",
"if",
"request",
"."... | View function which handles a registration request. | [
"View",
"function",
"which",
"handles",
"a",
"registration",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L102-L139 |
241,432 | mattupstate/flask-security | flask_security/views.py | send_login | def send_login():
"""View function that sends login instructions for passwordless login"""
form_class = _security.passwordless_login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_login_instructions(form.user)
if not request.is_json:
do_flash(*get_message('LOGIN_EMAIL_SENT', email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('SEND_LOGIN_TEMPLATE'),
send_login_form=form,
**_ctx('send_login')) | python | def send_login():
form_class = _security.passwordless_login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_login_instructions(form.user)
if not request.is_json:
do_flash(*get_message('LOGIN_EMAIL_SENT', email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('SEND_LOGIN_TEMPLATE'),
send_login_form=form,
**_ctx('send_login')) | [
"def",
"send_login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"passwordless_login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",... | View function that sends login instructions for passwordless login | [
"View",
"function",
"that",
"sends",
"login",
"instructions",
"for",
"passwordless",
"login"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L142-L162 |
241,433 | mattupstate/flask-security | flask_security/views.py | token_login | def token_login(token):
"""View function that handles passwordless login via a token"""
expired, invalid, user = login_token_status(token)
if invalid:
do_flash(*get_message('INVALID_LOGIN_TOKEN'))
if expired:
send_login_instructions(user)
do_flash(*get_message('LOGIN_EXPIRED', email=user.email,
within=_security.login_within))
if invalid or expired:
return redirect(url_for('login'))
login_user(user)
after_this_request(_commit)
do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))
return redirect(get_post_login_redirect()) | python | def token_login(token):
expired, invalid, user = login_token_status(token)
if invalid:
do_flash(*get_message('INVALID_LOGIN_TOKEN'))
if expired:
send_login_instructions(user)
do_flash(*get_message('LOGIN_EXPIRED', email=user.email,
within=_security.login_within))
if invalid or expired:
return redirect(url_for('login'))
login_user(user)
after_this_request(_commit)
do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))
return redirect(get_post_login_redirect()) | [
"def",
"token_login",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"login_token_status",
"(",
"token",
")",
"if",
"invalid",
":",
"do_flash",
"(",
"*",
"get_message",
"(",
"'INVALID_LOGIN_TOKEN'",
")",
")",
"if",
"expired",
":",
"se... | View function that handles passwordless login via a token | [
"View",
"function",
"that",
"handles",
"passwordless",
"login",
"via",
"a",
"token"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L166-L184 |
241,434 | mattupstate/flask-security | flask_security/views.py | send_confirmation | def send_confirmation():
"""View function which sends confirmation instructions."""
form_class = _security.send_confirmation_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_confirmation_instructions(form.user)
if not request.is_json:
do_flash(*get_message('CONFIRMATION_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(
config_value('SEND_CONFIRMATION_TEMPLATE'),
send_confirmation_form=form,
**_ctx('send_confirmation')
) | python | def send_confirmation():
form_class = _security.send_confirmation_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_confirmation_instructions(form.user)
if not request.is_json:
do_flash(*get_message('CONFIRMATION_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(
config_value('SEND_CONFIRMATION_TEMPLATE'),
send_confirmation_form=form,
**_ctx('send_confirmation')
) | [
"def",
"send_confirmation",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"send_confirmation_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"... | View function which sends confirmation instructions. | [
"View",
"function",
"which",
"sends",
"confirmation",
"instructions",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L187-L210 |
241,435 | mattupstate/flask-security | flask_security/views.py | confirm_email | def confirm_email(token):
"""View function which handles a email confirmation request."""
expired, invalid, user = confirm_email_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))
already_confirmed = user is not None and user.confirmed_at is not None
if expired and not already_confirmed:
send_confirmation_instructions(user)
do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email,
within=_security.confirm_email_within))
if invalid or (expired and not already_confirmed):
return redirect(get_url(_security.confirm_error_view) or
url_for('send_confirmation'))
if user != current_user:
logout_user()
if confirm_user(user):
after_this_request(_commit)
msg = 'EMAIL_CONFIRMED'
else:
msg = 'ALREADY_CONFIRMED'
do_flash(*get_message(msg))
return redirect(get_url(_security.post_confirm_view) or
get_url(_security.login_url)) | python | def confirm_email(token):
expired, invalid, user = confirm_email_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))
already_confirmed = user is not None and user.confirmed_at is not None
if expired and not already_confirmed:
send_confirmation_instructions(user)
do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email,
within=_security.confirm_email_within))
if invalid or (expired and not already_confirmed):
return redirect(get_url(_security.confirm_error_view) or
url_for('send_confirmation'))
if user != current_user:
logout_user()
if confirm_user(user):
after_this_request(_commit)
msg = 'EMAIL_CONFIRMED'
else:
msg = 'ALREADY_CONFIRMED'
do_flash(*get_message(msg))
return redirect(get_url(_security.post_confirm_view) or
get_url(_security.login_url)) | [
"def",
"confirm_email",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"confirm_email_token_status",
"(",
"token",
")",
"if",
"not",
"user",
"or",
"invalid",
":",
"invalid",
"=",
"True",
"do_flash",
"(",
"*",
"get_message",
"(",
"'INV... | View function which handles a email confirmation request. | [
"View",
"function",
"which",
"handles",
"a",
"email",
"confirmation",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L213-L244 |
241,436 | mattupstate/flask-security | flask_security/views.py | forgot_password | def forgot_password():
"""View function that handles a forgotten password request."""
form_class = _security.forgot_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_reset_password_instructions(form.user)
if not request.is_json:
do_flash(*get_message('PASSWORD_RESET_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form, include_user=False)
return _security.render_template(config_value('FORGOT_PASSWORD_TEMPLATE'),
forgot_password_form=form,
**_ctx('forgot_password')) | python | def forgot_password():
form_class = _security.forgot_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_reset_password_instructions(form.user)
if not request.is_json:
do_flash(*get_message('PASSWORD_RESET_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form, include_user=False)
return _security.render_template(config_value('FORGOT_PASSWORD_TEMPLATE'),
forgot_password_form=form,
**_ctx('forgot_password')) | [
"def",
"forgot_password",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"forgot_password_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form... | View function that handles a forgotten password request. | [
"View",
"function",
"that",
"handles",
"a",
"forgotten",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L248-L269 |
241,437 | mattupstate/flask-security | flask_security/views.py | reset_password | def reset_password(token):
"""View function that handles a reset password request."""
expired, invalid, user = reset_password_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
if expired:
send_reset_password_instructions(user)
do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
within=_security.reset_password_within))
if invalid or expired:
return redirect(url_for('forgot_password'))
form = _security.reset_password_form()
if form.validate_on_submit():
after_this_request(_commit)
update_password(user, form.password.data)
do_flash(*get_message('PASSWORD_RESET'))
return redirect(get_url(_security.post_reset_view) or
get_url(_security.login_url))
return _security.render_template(
config_value('RESET_PASSWORD_TEMPLATE'),
reset_password_form=form,
reset_password_token=token,
**_ctx('reset_password')
) | python | def reset_password(token):
expired, invalid, user = reset_password_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
if expired:
send_reset_password_instructions(user)
do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
within=_security.reset_password_within))
if invalid or expired:
return redirect(url_for('forgot_password'))
form = _security.reset_password_form()
if form.validate_on_submit():
after_this_request(_commit)
update_password(user, form.password.data)
do_flash(*get_message('PASSWORD_RESET'))
return redirect(get_url(_security.post_reset_view) or
get_url(_security.login_url))
return _security.render_template(
config_value('RESET_PASSWORD_TEMPLATE'),
reset_password_form=form,
reset_password_token=token,
**_ctx('reset_password')
) | [
"def",
"reset_password",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"reset_password_token_status",
"(",
"token",
")",
"if",
"not",
"user",
"or",
"invalid",
":",
"invalid",
"=",
"True",
"do_flash",
"(",
"*",
"get_message",
"(",
"'I... | View function that handles a reset password request. | [
"View",
"function",
"that",
"handles",
"a",
"reset",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L273-L303 |
241,438 | mattupstate/flask-security | flask_security/views.py | change_password | def change_password():
"""View function which handles a change password request."""
form_class = _security.change_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(),
form.new_password.data)
if not request.is_json:
do_flash(*get_message('PASSWORD_CHANGE'))
return redirect(get_url(_security.post_change_view) or
get_url(_security.post_login_view))
if request.is_json:
form.user = current_user
return _render_json(form)
return _security.render_template(
config_value('CHANGE_PASSWORD_TEMPLATE'),
change_password_form=form,
**_ctx('change_password')
) | python | def change_password():
form_class = _security.change_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(),
form.new_password.data)
if not request.is_json:
do_flash(*get_message('PASSWORD_CHANGE'))
return redirect(get_url(_security.post_change_view) or
get_url(_security.post_login_view))
if request.is_json:
form.user = current_user
return _render_json(form)
return _security.render_template(
config_value('CHANGE_PASSWORD_TEMPLATE'),
change_password_form=form,
**_ctx('change_password')
) | [
"def",
"change_password",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"change_password_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form... | View function which handles a change password request. | [
"View",
"function",
"which",
"handles",
"a",
"change",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L307-L334 |
241,439 | mattupstate/flask-security | flask_security/views.py | create_blueprint | def create_blueprint(state, import_name):
"""Creates the security extension blueprint"""
bp = Blueprint(state.blueprint_name, import_name,
url_prefix=state.url_prefix,
subdomain=state.subdomain,
template_folder='templates')
bp.route(state.logout_url, endpoint='logout')(logout)
if state.passwordless:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(send_login)
bp.route(state.login_url + slash_url_suffix(state.login_url,
'<token>'),
endpoint='token_login')(token_login)
else:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(login)
if state.registerable:
bp.route(state.register_url,
methods=['GET', 'POST'],
endpoint='register')(register)
if state.recoverable:
bp.route(state.reset_url,
methods=['GET', 'POST'],
endpoint='forgot_password')(forgot_password)
bp.route(state.reset_url + slash_url_suffix(state.reset_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='reset_password')(reset_password)
if state.changeable:
bp.route(state.change_url,
methods=['GET', 'POST'],
endpoint='change_password')(change_password)
if state.confirmable:
bp.route(state.confirm_url,
methods=['GET', 'POST'],
endpoint='send_confirmation')(send_confirmation)
bp.route(state.confirm_url + slash_url_suffix(state.confirm_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='confirm_email')(confirm_email)
return bp | python | def create_blueprint(state, import_name):
bp = Blueprint(state.blueprint_name, import_name,
url_prefix=state.url_prefix,
subdomain=state.subdomain,
template_folder='templates')
bp.route(state.logout_url, endpoint='logout')(logout)
if state.passwordless:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(send_login)
bp.route(state.login_url + slash_url_suffix(state.login_url,
'<token>'),
endpoint='token_login')(token_login)
else:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(login)
if state.registerable:
bp.route(state.register_url,
methods=['GET', 'POST'],
endpoint='register')(register)
if state.recoverable:
bp.route(state.reset_url,
methods=['GET', 'POST'],
endpoint='forgot_password')(forgot_password)
bp.route(state.reset_url + slash_url_suffix(state.reset_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='reset_password')(reset_password)
if state.changeable:
bp.route(state.change_url,
methods=['GET', 'POST'],
endpoint='change_password')(change_password)
if state.confirmable:
bp.route(state.confirm_url,
methods=['GET', 'POST'],
endpoint='send_confirmation')(send_confirmation)
bp.route(state.confirm_url + slash_url_suffix(state.confirm_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='confirm_email')(confirm_email)
return bp | [
"def",
"create_blueprint",
"(",
"state",
",",
"import_name",
")",
":",
"bp",
"=",
"Blueprint",
"(",
"state",
".",
"blueprint_name",
",",
"import_name",
",",
"url_prefix",
"=",
"state",
".",
"url_prefix",
",",
"subdomain",
"=",
"state",
".",
"subdomain",
",",... | Creates the security extension blueprint | [
"Creates",
"the",
"security",
"extension",
"blueprint"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L337-L387 |
241,440 | mattupstate/flask-security | flask_security/utils.py | login_user | def login_user(user, remember=None):
"""Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this
request (i.e. ``app.security.datastore.commit()``).
:param user: The user to login
:param remember: Flag specifying if the remember cookie should be set.
Defaults to ``False``
"""
if remember is None:
remember = config_value('DEFAULT_REMEMBER_ME')
if not _login_user(user, remember): # pragma: no cover
return False
if _security.trackable:
remote_addr = request.remote_addr or None # make sure it is None
old_current_login, new_current_login = (
user.current_login_at, _security.datetime_factory()
)
old_current_ip, new_current_ip = user.current_login_ip, remote_addr
user.last_login_at = old_current_login or new_current_login
user.current_login_at = new_current_login
user.last_login_ip = old_current_ip
user.current_login_ip = new_current_ip
user.login_count = user.login_count + 1 if user.login_count else 1
_datastore.put(user)
identity_changed.send(current_app._get_current_object(),
identity=Identity(user.id))
return True | python | def login_user(user, remember=None):
if remember is None:
remember = config_value('DEFAULT_REMEMBER_ME')
if not _login_user(user, remember): # pragma: no cover
return False
if _security.trackable:
remote_addr = request.remote_addr or None # make sure it is None
old_current_login, new_current_login = (
user.current_login_at, _security.datetime_factory()
)
old_current_ip, new_current_ip = user.current_login_ip, remote_addr
user.last_login_at = old_current_login or new_current_login
user.current_login_at = new_current_login
user.last_login_ip = old_current_ip
user.current_login_ip = new_current_ip
user.login_count = user.login_count + 1 if user.login_count else 1
_datastore.put(user)
identity_changed.send(current_app._get_current_object(),
identity=Identity(user.id))
return True | [
"def",
"login_user",
"(",
"user",
",",
"remember",
"=",
"None",
")",
":",
"if",
"remember",
"is",
"None",
":",
"remember",
"=",
"config_value",
"(",
"'DEFAULT_REMEMBER_ME'",
")",
"if",
"not",
"_login_user",
"(",
"user",
",",
"remember",
")",
":",
"# pragma... | Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this
request (i.e. ``app.security.datastore.commit()``).
:param user: The user to login
:param remember: Flag specifying if the remember cookie should be set.
Defaults to ``False`` | [
"Perform",
"the",
"login",
"routine",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L63-L98 |
241,441 | mattupstate/flask-security | flask_security/utils.py | logout_user | def logout_user():
"""Logs out the current.
This will also clean up the remember me cookie if it exists.
"""
for key in ('identity.name', 'identity.auth_type'):
session.pop(key, None)
identity_changed.send(current_app._get_current_object(),
identity=AnonymousIdentity())
_logout_user() | python | def logout_user():
for key in ('identity.name', 'identity.auth_type'):
session.pop(key, None)
identity_changed.send(current_app._get_current_object(),
identity=AnonymousIdentity())
_logout_user() | [
"def",
"logout_user",
"(",
")",
":",
"for",
"key",
"in",
"(",
"'identity.name'",
",",
"'identity.auth_type'",
")",
":",
"session",
".",
"pop",
"(",
"key",
",",
"None",
")",
"identity_changed",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",... | Logs out the current.
This will also clean up the remember me cookie if it exists. | [
"Logs",
"out",
"the",
"current",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L101-L111 |
241,442 | mattupstate/flask-security | flask_security/utils.py | verify_password | def verify_password(password, password_hash):
"""Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database)
"""
if use_double_hash(password_hash):
password = get_hmac(password)
return _pwd_context.verify(password, password_hash) | python | def verify_password(password, password_hash):
if use_double_hash(password_hash):
password = get_hmac(password)
return _pwd_context.verify(password, password_hash) | [
"def",
"verify_password",
"(",
"password",
",",
"password_hash",
")",
":",
"if",
"use_double_hash",
"(",
"password_hash",
")",
":",
"password",
"=",
"get_hmac",
"(",
"password",
")",
"return",
"_pwd_context",
".",
"verify",
"(",
"password",
",",
"password_hash",... | Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database) | [
"Returns",
"True",
"if",
"the",
"password",
"matches",
"the",
"supplied",
"hash",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L132-L142 |
241,443 | mattupstate/flask-security | flask_security/utils.py | find_redirect | def find_redirect(key):
"""Returns the URL to redirect to after a user logs in successfully.
:param key: The session or application configuration key to search for
"""
rv = (get_url(session.pop(key.lower(), None)) or
get_url(current_app.config[key.upper()] or None) or '/')
return rv | python | def find_redirect(key):
rv = (get_url(session.pop(key.lower(), None)) or
get_url(current_app.config[key.upper()] or None) or '/')
return rv | [
"def",
"find_redirect",
"(",
"key",
")",
":",
"rv",
"=",
"(",
"get_url",
"(",
"session",
".",
"pop",
"(",
"key",
".",
"lower",
"(",
")",
",",
"None",
")",
")",
"or",
"get_url",
"(",
"current_app",
".",
"config",
"[",
"key",
".",
"upper",
"(",
")"... | Returns the URL to redirect to after a user logs in successfully.
:param key: The session or application configuration key to search for | [
"Returns",
"the",
"URL",
"to",
"redirect",
"to",
"after",
"a",
"user",
"logs",
"in",
"successfully",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L306-L313 |
241,444 | mattupstate/flask-security | flask_security/utils.py | send_mail | def send_mail(subject, recipient, template, **context):
"""Send an email via the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with
"""
context.setdefault('security', _security)
context.update(_security._run_ctx_processor('mail'))
sender = _security.email_sender
if isinstance(sender, LocalProxy):
sender = sender._get_current_object()
msg = Message(subject,
sender=sender,
recipients=[recipient])
ctx = ('security/email', template)
if config_value('EMAIL_PLAINTEXT'):
msg.body = _security.render_template('%s/%s.txt' % ctx, **context)
if config_value('EMAIL_HTML'):
msg.html = _security.render_template('%s/%s.html' % ctx, **context)
if _security._send_mail_task:
_security._send_mail_task(msg)
return
mail = current_app.extensions.get('mail')
mail.send(msg) | python | def send_mail(subject, recipient, template, **context):
context.setdefault('security', _security)
context.update(_security._run_ctx_processor('mail'))
sender = _security.email_sender
if isinstance(sender, LocalProxy):
sender = sender._get_current_object()
msg = Message(subject,
sender=sender,
recipients=[recipient])
ctx = ('security/email', template)
if config_value('EMAIL_PLAINTEXT'):
msg.body = _security.render_template('%s/%s.txt' % ctx, **context)
if config_value('EMAIL_HTML'):
msg.html = _security.render_template('%s/%s.html' % ctx, **context)
if _security._send_mail_task:
_security._send_mail_task(msg)
return
mail = current_app.extensions.get('mail')
mail.send(msg) | [
"def",
"send_mail",
"(",
"subject",
",",
"recipient",
",",
"template",
",",
"*",
"*",
"context",
")",
":",
"context",
".",
"setdefault",
"(",
"'security'",
",",
"_security",
")",
"context",
".",
"update",
"(",
"_security",
".",
"_run_ctx_processor",
"(",
"... | Send an email via the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with | [
"Send",
"an",
"email",
"via",
"the",
"Flask",
"-",
"Mail",
"extension",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L373-L404 |
241,445 | mattupstate/flask-security | flask_security/utils.py | capture_registrations | def capture_registrations():
"""Testing utility for capturing registrations.
:param confirmation_sent_at: An optional datetime object to set the
user's `confirmation_sent_at` to
"""
registrations = []
def _on(app, **data):
registrations.append(data)
user_registered.connect(_on)
try:
yield registrations
finally:
user_registered.disconnect(_on) | python | def capture_registrations():
registrations = []
def _on(app, **data):
registrations.append(data)
user_registered.connect(_on)
try:
yield registrations
finally:
user_registered.disconnect(_on) | [
"def",
"capture_registrations",
"(",
")",
":",
"registrations",
"=",
"[",
"]",
"def",
"_on",
"(",
"app",
",",
"*",
"*",
"data",
")",
":",
"registrations",
".",
"append",
"(",
"data",
")",
"user_registered",
".",
"connect",
"(",
"_on",
")",
"try",
":",
... | Testing utility for capturing registrations.
:param confirmation_sent_at: An optional datetime object to set the
user's `confirmation_sent_at` to | [
"Testing",
"utility",
"for",
"capturing",
"registrations",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L481-L497 |
241,446 | mattupstate/flask-security | flask_security/utils.py | capture_reset_password_requests | def capture_reset_password_requests(reset_password_sent_at=None):
"""Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to
"""
reset_requests = []
def _on(app, **data):
reset_requests.append(data)
reset_password_instructions_sent.connect(_on)
try:
yield reset_requests
finally:
reset_password_instructions_sent.disconnect(_on) | python | def capture_reset_password_requests(reset_password_sent_at=None):
reset_requests = []
def _on(app, **data):
reset_requests.append(data)
reset_password_instructions_sent.connect(_on)
try:
yield reset_requests
finally:
reset_password_instructions_sent.disconnect(_on) | [
"def",
"capture_reset_password_requests",
"(",
"reset_password_sent_at",
"=",
"None",
")",
":",
"reset_requests",
"=",
"[",
"]",
"def",
"_on",
"(",
"app",
",",
"*",
"*",
"data",
")",
":",
"reset_requests",
".",
"append",
"(",
"data",
")",
"reset_password_instr... | Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to | [
"Testing",
"utility",
"for",
"capturing",
"password",
"reset",
"requests",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L501-L517 |
241,447 | mattupstate/flask-security | flask_security/passwordless.py | send_login_instructions | def send_login_instructions(user):
"""Sends the login instructions email for the specified user.
:param user: The user to send the instructions to
:param token: The login token
"""
token = generate_login_token(user)
login_link = url_for_security('token_login', token=token, _external=True)
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORDLESS'), user.email,
'login_instructions', user=user, login_link=login_link)
login_instructions_sent.send(app._get_current_object(), user=user,
login_token=token) | python | def send_login_instructions(user):
token = generate_login_token(user)
login_link = url_for_security('token_login', token=token, _external=True)
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORDLESS'), user.email,
'login_instructions', user=user, login_link=login_link)
login_instructions_sent.send(app._get_current_object(), user=user,
login_token=token) | [
"def",
"send_login_instructions",
"(",
"user",
")",
":",
"token",
"=",
"generate_login_token",
"(",
"user",
")",
"login_link",
"=",
"url_for_security",
"(",
"'token_login'",
",",
"token",
"=",
"token",
",",
"_external",
"=",
"True",
")",
"_security",
".",
"sen... | Sends the login instructions email for the specified user.
:param user: The user to send the instructions to
:param token: The login token | [
"Sends",
"the",
"login",
"instructions",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/passwordless.py#L24-L37 |
241,448 | mattupstate/flask-security | flask_security/cli.py | roles_add | def roles_add(user, role):
"""Add user to role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.add_role_to_user(user, role):
click.secho('Role "{0}" added to user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot add role to user.') | python | def roles_add(user, role):
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.add_role_to_user(user, role):
click.secho('Role "{0}" added to user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot add role to user.') | [
"def",
"roles_add",
"(",
"user",
",",
"role",
")",
":",
"user",
",",
"role",
"=",
"_datastore",
".",
"_prepare_role_modify_args",
"(",
"user",
",",
"role",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot find user.'... | Add user to role. | [
"Add",
"user",
"to",
"role",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/cli.py#L93-L104 |
241,449 | mattupstate/flask-security | flask_security/cli.py | roles_remove | def roles_remove(user, role):
"""Remove user from role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.remove_role_from_user(user, role):
click.secho('Role "{0}" removed from user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot remove role from user.') | python | def roles_remove(user, role):
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.remove_role_from_user(user, role):
click.secho('Role "{0}" removed from user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot remove role from user.') | [
"def",
"roles_remove",
"(",
"user",
",",
"role",
")",
":",
"user",
",",
"role",
"=",
"_datastore",
".",
"_prepare_role_modify_args",
"(",
"user",
",",
"role",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot find use... | Remove user from role. | [
"Remove",
"user",
"from",
"role",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/cli.py#L112-L123 |
241,450 | mattupstate/flask-security | flask_security/changeable.py | send_password_changed_notice | def send_password_changed_notice(user):
"""Sends the password changed notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_CHANGE_EMAIL'):
subject = config_value('EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE')
_security.send_mail(subject, user.email, 'change_notice', user=user) | python | def send_password_changed_notice(user):
if config_value('SEND_PASSWORD_CHANGE_EMAIL'):
subject = config_value('EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE')
_security.send_mail(subject, user.email, 'change_notice', user=user) | [
"def",
"send_password_changed_notice",
"(",
"user",
")",
":",
"if",
"config_value",
"(",
"'SEND_PASSWORD_CHANGE_EMAIL'",
")",
":",
"subject",
"=",
"config_value",
"(",
"'EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE'",
")",
"_security",
".",
"send_mail",
"(",
"subject",
",",
"... | Sends the password changed notice email for the specified user.
:param user: The user to send the notice to | [
"Sends",
"the",
"password",
"changed",
"notice",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/changeable.py#L25-L32 |
241,451 | mattupstate/flask-security | flask_security/changeable.py | change_user_password | def change_user_password(user, password):
"""Change the specified user's password
:param user: The user to change_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_changed_notice(user)
password_changed.send(current_app._get_current_object(),
user=user) | python | def change_user_password(user, password):
user.password = hash_password(password)
_datastore.put(user)
send_password_changed_notice(user)
password_changed.send(current_app._get_current_object(),
user=user) | [
"def",
"change_user_password",
"(",
"user",
",",
"password",
")",
":",
"user",
".",
"password",
"=",
"hash_password",
"(",
"password",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"send_password_changed_notice",
"(",
"user",
")",
"password_changed",
".",
"... | Change the specified user's password
:param user: The user to change_password
:param password: The unhashed new password | [
"Change",
"the",
"specified",
"user",
"s",
"password"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/changeable.py#L35-L45 |
241,452 | jd/tenacity | tenacity/after.py | after_log | def after_log(logger, log_level, sec_format="%0.3f"):
"""After call strategy that logs to some logger the finished attempt."""
log_tpl = ("Finished call to '%s' after " + str(sec_format) + "(s), "
"this was the %s time calling it.")
def log_it(retry_state):
logger.log(log_level, log_tpl,
_utils.get_callback_name(retry_state.fn),
retry_state.seconds_since_start,
_utils.to_ordinal(retry_state.attempt_number))
return log_it | python | def after_log(logger, log_level, sec_format="%0.3f"):
log_tpl = ("Finished call to '%s' after " + str(sec_format) + "(s), "
"this was the %s time calling it.")
def log_it(retry_state):
logger.log(log_level, log_tpl,
_utils.get_callback_name(retry_state.fn),
retry_state.seconds_since_start,
_utils.to_ordinal(retry_state.attempt_number))
return log_it | [
"def",
"after_log",
"(",
"logger",
",",
"log_level",
",",
"sec_format",
"=",
"\"%0.3f\"",
")",
":",
"log_tpl",
"=",
"(",
"\"Finished call to '%s' after \"",
"+",
"str",
"(",
"sec_format",
")",
"+",
"\"(s), \"",
"\"this was the %s time calling it.\"",
")",
"def",
"... | After call strategy that logs to some logger the finished attempt. | [
"After",
"call",
"strategy",
"that",
"logs",
"to",
"some",
"logger",
"the",
"finished",
"attempt",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/after.py#L24-L35 |
241,453 | jd/tenacity | tenacity/__init__.py | retry | def retry(*dargs, **dkw):
"""Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
return retry()(dargs[0])
else:
def wrap(f):
if asyncio and asyncio.iscoroutinefunction(f):
r = AsyncRetrying(*dargs, **dkw)
elif tornado and hasattr(tornado.gen, 'is_coroutine_function') \
and tornado.gen.is_coroutine_function(f):
r = TornadoRetrying(*dargs, **dkw)
else:
r = Retrying(*dargs, **dkw)
return r.wraps(f)
return wrap | python | def retry(*dargs, **dkw):
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
return retry()(dargs[0])
else:
def wrap(f):
if asyncio and asyncio.iscoroutinefunction(f):
r = AsyncRetrying(*dargs, **dkw)
elif tornado and hasattr(tornado.gen, 'is_coroutine_function') \
and tornado.gen.is_coroutine_function(f):
r = TornadoRetrying(*dargs, **dkw)
else:
r = Retrying(*dargs, **dkw)
return r.wraps(f)
return wrap | [
"def",
"retry",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
":",
"# support both @retry and @retry() as valid syntax",
"if",
"len",
"(",
"dargs",
")",
"==",
"1",
"and",
"callable",
"(",
"dargs",
"[",
"0",
"]",
")",
":",
"return",
"retry",
"(",
")",
"... | Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object | [
"Wrap",
"a",
"function",
"with",
"a",
"new",
"Retrying",
"object",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L88-L109 |
241,454 | jd/tenacity | tenacity/__init__.py | BaseRetrying.copy | def copy(self, sleep=_unset, stop=_unset, wait=_unset,
retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
reraise=_unset):
"""Copy this object with some parameters changed if needed."""
if before_sleep is _unset:
before_sleep = self.before_sleep
return self.__class__(
sleep=self.sleep if sleep is _unset else sleep,
stop=self.stop if stop is _unset else stop,
wait=self.wait if wait is _unset else wait,
retry=self.retry if retry is _unset else retry,
before=self.before if before is _unset else before,
after=self.after if after is _unset else after,
before_sleep=before_sleep,
reraise=self.reraise if after is _unset else reraise,
) | python | def copy(self, sleep=_unset, stop=_unset, wait=_unset,
retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
reraise=_unset):
if before_sleep is _unset:
before_sleep = self.before_sleep
return self.__class__(
sleep=self.sleep if sleep is _unset else sleep,
stop=self.stop if stop is _unset else stop,
wait=self.wait if wait is _unset else wait,
retry=self.retry if retry is _unset else retry,
before=self.before if before is _unset else before,
after=self.after if after is _unset else after,
before_sleep=before_sleep,
reraise=self.reraise if after is _unset else reraise,
) | [
"def",
"copy",
"(",
"self",
",",
"sleep",
"=",
"_unset",
",",
"stop",
"=",
"_unset",
",",
"wait",
"=",
"_unset",
",",
"retry",
"=",
"_unset",
",",
"before",
"=",
"_unset",
",",
"after",
"=",
"_unset",
",",
"before_sleep",
"=",
"_unset",
",",
"reraise... | Copy this object with some parameters changed if needed. | [
"Copy",
"this",
"object",
"with",
"some",
"parameters",
"changed",
"if",
"needed",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L231-L246 |
241,455 | jd/tenacity | tenacity/__init__.py | BaseRetrying.statistics | def statistics(self):
"""Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. warning:: The keys in this dictionary **should** be some what
stable (not changing), but there existence **may**
change between major releases as new statistics are
gathered or removed so before accessing keys ensure that
they actually exist and handle when they do not.
.. note:: The values in this dictionary are local to the thread
running call (so if multiple threads share the same retrying
object - either directly or indirectly) they will each have
there own view of statistics they have collected (in the
future we may provide a way to aggregate the various
statistics from each thread).
"""
try:
return self._local.statistics
except AttributeError:
self._local.statistics = {}
return self._local.statistics | python | def statistics(self):
try:
return self._local.statistics
except AttributeError:
self._local.statistics = {}
return self._local.statistics | [
"def",
"statistics",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_local",
".",
"statistics",
"except",
"AttributeError",
":",
"self",
".",
"_local",
".",
"statistics",
"=",
"{",
"}",
"return",
"self",
".",
"_local",
".",
"statistics"
] | Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. warning:: The keys in this dictionary **should** be some what
stable (not changing), but there existence **may**
change between major releases as new statistics are
gathered or removed so before accessing keys ensure that
they actually exist and handle when they do not.
.. note:: The values in this dictionary are local to the thread
running call (so if multiple threads share the same retrying
object - either directly or indirectly) they will each have
there own view of statistics they have collected (in the
future we may provide a way to aggregate the various
statistics from each thread). | [
"Return",
"a",
"dictionary",
"of",
"runtime",
"statistics",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L258-L283 |
241,456 | jd/tenacity | tenacity/__init__.py | BaseRetrying.wraps | def wraps(self, f):
"""Wrap a function for retrying.
:param f: A function to wraps for retrying.
"""
@_utils.wraps(f)
def wrapped_f(*args, **kw):
return self.call(f, *args, **kw)
def retry_with(*args, **kwargs):
return self.copy(*args, **kwargs).wraps(f)
wrapped_f.retry = self
wrapped_f.retry_with = retry_with
return wrapped_f | python | def wraps(self, f):
@_utils.wraps(f)
def wrapped_f(*args, **kw):
return self.call(f, *args, **kw)
def retry_with(*args, **kwargs):
return self.copy(*args, **kwargs).wraps(f)
wrapped_f.retry = self
wrapped_f.retry_with = retry_with
return wrapped_f | [
"def",
"wraps",
"(",
"self",
",",
"f",
")",
":",
"@",
"_utils",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"call",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kw"... | Wrap a function for retrying.
:param f: A function to wraps for retrying. | [
"Wrap",
"a",
"function",
"for",
"retrying",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L285-L300 |
241,457 | jd/tenacity | tenacity/__init__.py | Future.construct | def construct(cls, attempt_number, value, has_exception):
"""Construct a new Future object."""
fut = cls(attempt_number)
if has_exception:
fut.set_exception(value)
else:
fut.set_result(value)
return fut | python | def construct(cls, attempt_number, value, has_exception):
fut = cls(attempt_number)
if has_exception:
fut.set_exception(value)
else:
fut.set_result(value)
return fut | [
"def",
"construct",
"(",
"cls",
",",
"attempt_number",
",",
"value",
",",
"has_exception",
")",
":",
"fut",
"=",
"cls",
"(",
"attempt_number",
")",
"if",
"has_exception",
":",
"fut",
".",
"set_exception",
"(",
"value",
")",
"else",
":",
"fut",
".",
"set_... | Construct a new Future object. | [
"Construct",
"a",
"new",
"Future",
"object",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L388-L395 |
241,458 | jd/tenacity | tenacity/_utils.py | get_callback_name | def get_callback_name(cb):
"""Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned.
"""
segments = []
try:
segments.append(cb.__qualname__)
except AttributeError:
try:
segments.append(cb.__name__)
if inspect.ismethod(cb):
try:
# This attribute doesn't exist on py3.x or newer, so
# we optionally ignore it... (on those versions of
# python `__qualname__` should have been found anyway).
segments.insert(0, cb.im_class.__name__)
except AttributeError:
pass
except AttributeError:
pass
if not segments:
return repr(cb)
else:
try:
# When running under sphinx it appears this can be none?
if cb.__module__:
segments.insert(0, cb.__module__)
except AttributeError:
pass
return ".".join(segments) | python | def get_callback_name(cb):
segments = []
try:
segments.append(cb.__qualname__)
except AttributeError:
try:
segments.append(cb.__name__)
if inspect.ismethod(cb):
try:
# This attribute doesn't exist on py3.x or newer, so
# we optionally ignore it... (on those versions of
# python `__qualname__` should have been found anyway).
segments.insert(0, cb.im_class.__name__)
except AttributeError:
pass
except AttributeError:
pass
if not segments:
return repr(cb)
else:
try:
# When running under sphinx it appears this can be none?
if cb.__module__:
segments.insert(0, cb.__module__)
except AttributeError:
pass
return ".".join(segments) | [
"def",
"get_callback_name",
"(",
"cb",
")",
":",
"segments",
"=",
"[",
"]",
"try",
":",
"segments",
".",
"append",
"(",
"cb",
".",
"__qualname__",
")",
"except",
"AttributeError",
":",
"try",
":",
"segments",
".",
"append",
"(",
"cb",
".",
"__name__",
... | Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned. | [
"Get",
"a",
"callback",
"fully",
"-",
"qualified",
"name",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/_utils.py#L98-L128 |
241,459 | jd/tenacity | tenacity/compat.py | make_retry_state | def make_retry_state(previous_attempt_number, delay_since_first_attempt,
last_result=None):
"""Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics.
"""
required_parameter_unset = (previous_attempt_number is _unset or
delay_since_first_attempt is _unset)
if required_parameter_unset:
raise _make_unset_exception(
'wait/stop',
previous_attempt_number=previous_attempt_number,
delay_since_first_attempt=delay_since_first_attempt)
from tenacity import RetryCallState
retry_state = RetryCallState(None, None, (), {})
retry_state.attempt_number = previous_attempt_number
if last_result is not None:
retry_state.outcome = last_result
else:
retry_state.set_result(None)
_set_delay_since_start(retry_state, delay_since_first_attempt)
return retry_state | python | def make_retry_state(previous_attempt_number, delay_since_first_attempt,
last_result=None):
required_parameter_unset = (previous_attempt_number is _unset or
delay_since_first_attempt is _unset)
if required_parameter_unset:
raise _make_unset_exception(
'wait/stop',
previous_attempt_number=previous_attempt_number,
delay_since_first_attempt=delay_since_first_attempt)
from tenacity import RetryCallState
retry_state = RetryCallState(None, None, (), {})
retry_state.attempt_number = previous_attempt_number
if last_result is not None:
retry_state.outcome = last_result
else:
retry_state.set_result(None)
_set_delay_since_start(retry_state, delay_since_first_attempt)
return retry_state | [
"def",
"make_retry_state",
"(",
"previous_attempt_number",
",",
"delay_since_first_attempt",
",",
"last_result",
"=",
"None",
")",
":",
"required_parameter_unset",
"=",
"(",
"previous_attempt_number",
"is",
"_unset",
"or",
"delay_since_first_attempt",
"is",
"_unset",
")",... | Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics. | [
"Construct",
"RetryCallState",
"for",
"given",
"attempt",
"number",
"&",
"delay",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L57-L79 |
241,460 | jd/tenacity | tenacity/compat.py | func_takes_last_result | def func_takes_last_result(waiter):
"""Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning.
"""
if not six.callable(waiter):
return False
if not inspect.isfunction(waiter) and not inspect.ismethod(waiter):
# waiter is a class, check dunder-call rather than dunder-init.
waiter = waiter.__call__
waiter_spec = _utils.getargspec(waiter)
return 'last_result' in waiter_spec.args | python | def func_takes_last_result(waiter):
if not six.callable(waiter):
return False
if not inspect.isfunction(waiter) and not inspect.ismethod(waiter):
# waiter is a class, check dunder-call rather than dunder-init.
waiter = waiter.__call__
waiter_spec = _utils.getargspec(waiter)
return 'last_result' in waiter_spec.args | [
"def",
"func_takes_last_result",
"(",
"waiter",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"waiter",
")",
":",
"return",
"False",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"waiter",
")",
"and",
"not",
"inspect",
".",
"ismethod",
"(",
"wait... | Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning. | [
"Check",
"if",
"function",
"has",
"a",
"last_result",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L82-L94 |
241,461 | jd/tenacity | tenacity/compat.py | stop_func_accept_retry_state | def stop_func_accept_retry_state(stop_func):
"""Wrap "stop" function to accept "retry_state" parameter."""
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
warn_about_non_retry_state_deprecation(
'stop', stop_func, stacklevel=4)
return stop_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_stop_func | python | def stop_func_accept_retry_state(stop_func):
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
warn_about_non_retry_state_deprecation(
'stop', stop_func, stacklevel=4)
return stop_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_stop_func | [
"def",
"stop_func_accept_retry_state",
"(",
"stop_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"stop_func",
")",
":",
"return",
"stop_func",
"if",
"func_takes_retry_state",
"(",
"stop_func",
")",
":",
"return",
"stop_func",
"@",
"_utils",
".",
"w... | Wrap "stop" function to accept "retry_state" parameter. | [
"Wrap",
"stop",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L120-L136 |
241,462 | jd/tenacity | tenacity/compat.py | wait_func_accept_retry_state | def wait_func_accept_retry_state(wait_func):
"""Wrap wait function to accept "retry_state" parameter."""
if not six.callable(wait_func):
return wait_func
if func_takes_retry_state(wait_func):
return wait_func
if func_takes_last_result(wait_func):
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
last_result=retry_state.outcome,
)
else:
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_wait_func | python | def wait_func_accept_retry_state(wait_func):
if not six.callable(wait_func):
return wait_func
if func_takes_retry_state(wait_func):
return wait_func
if func_takes_last_result(wait_func):
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
last_result=retry_state.outcome,
)
else:
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_wait_func | [
"def",
"wait_func_accept_retry_state",
"(",
"wait_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"wait_func",
")",
":",
"return",
"wait_func",
"if",
"func_takes_retry_state",
"(",
"wait_func",
")",
":",
"return",
"wait_func",
"if",
"func_takes_last_res... | Wrap wait function to accept "retry_state" parameter. | [
"Wrap",
"wait",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L164-L191 |
241,463 | jd/tenacity | tenacity/compat.py | retry_func_accept_retry_state | def retry_func_accept_retry_state(retry_func):
"""Wrap "retry" function to accept "retry_state" parameter."""
if not six.callable(retry_func):
return retry_func
if func_takes_retry_state(retry_func):
return retry_func
@_utils.wraps(retry_func)
def wrapped_retry_func(retry_state):
warn_about_non_retry_state_deprecation(
'retry', retry_func, stacklevel=4)
return retry_func(retry_state.outcome)
return wrapped_retry_func | python | def retry_func_accept_retry_state(retry_func):
if not six.callable(retry_func):
return retry_func
if func_takes_retry_state(retry_func):
return retry_func
@_utils.wraps(retry_func)
def wrapped_retry_func(retry_state):
warn_about_non_retry_state_deprecation(
'retry', retry_func, stacklevel=4)
return retry_func(retry_state.outcome)
return wrapped_retry_func | [
"def",
"retry_func_accept_retry_state",
"(",
"retry_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"retry_func",
")",
":",
"return",
"retry_func",
"if",
"func_takes_retry_state",
"(",
"retry_func",
")",
":",
"return",
"retry_func",
"@",
"_utils",
"."... | Wrap "retry" function to accept "retry_state" parameter. | [
"Wrap",
"retry",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L215-L228 |
241,464 | jd/tenacity | tenacity/compat.py | before_func_accept_retry_state | def before_func_accept_retry_state(fn):
"""Wrap "before" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('before', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
)
return wrapped_before_func | python | def before_func_accept_retry_state(fn):
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('before', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
)
return wrapped_before_func | [
"def",
"before_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")",
"d... | Wrap "before" function to accept "retry_state". | [
"Wrap",
"before",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L231-L247 |
241,465 | jd/tenacity | tenacity/compat.py | after_func_accept_retry_state | def after_func_accept_retry_state(fn):
"""Wrap "after" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_after_sleep_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('after', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
retry_state.seconds_since_start)
return wrapped_after_sleep_func | python | def after_func_accept_retry_state(fn):
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_after_sleep_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('after', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
retry_state.seconds_since_start)
return wrapped_after_sleep_func | [
"def",
"after_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")",
"de... | Wrap "after" function to accept "retry_state". | [
"Wrap",
"after",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L250-L266 |
241,466 | jd/tenacity | tenacity/compat.py | before_sleep_func_accept_retry_state | def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, sleep, last_result
warn_about_non_retry_state_deprecation(
'before_sleep', fn, stacklevel=4)
return fn(
retry_state.retry_object,
sleep=getattr(retry_state.next_action, 'sleep'),
last_result=retry_state.outcome)
return wrapped_before_sleep_func | python | def before_sleep_func_accept_retry_state(fn):
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, sleep, last_result
warn_about_non_retry_state_deprecation(
'before_sleep', fn, stacklevel=4)
return fn(
retry_state.retry_object,
sleep=getattr(retry_state.next_action, 'sleep'),
last_result=retry_state.outcome)
return wrapped_before_sleep_func | [
"def",
"before_sleep_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")"... | Wrap "before_sleep" function to accept "retry_state". | [
"Wrap",
"before_sleep",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L269-L286 |
241,467 | divio/django-filer | filer/admin/patched/admin_utils.py | NestedObjects.nested | def nested(self, format_callback=None):
"""
Return the graph as a nested list.
"""
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots | python | def nested(self, format_callback=None):
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots | [
"def",
"nested",
"(",
"self",
",",
"format_callback",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"roots",
"=",
"[",
"]",
"for",
"root",
"in",
"self",
".",
"edges",
".",
"get",
"(",
"None",
",",
"(",
")",
")",
":",
"roots",
".",
"exten... | Return the graph as a nested list. | [
"Return",
"the",
"graph",
"as",
"a",
"nested",
"list",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/patched/admin_utils.py#L132-L140 |
241,468 | divio/django-filer | filer/utils/files.py | get_valid_filename | def get_valid_filename(s):
"""
like the regular get_valid_filename, but also slugifies away
umlauts and stuff.
"""
s = get_valid_filename_django(s)
filename, ext = os.path.splitext(s)
filename = slugify(filename)
ext = slugify(ext)
if ext:
return "%s.%s" % (filename, ext)
else:
return "%s" % (filename,) | python | def get_valid_filename(s):
s = get_valid_filename_django(s)
filename, ext = os.path.splitext(s)
filename = slugify(filename)
ext = slugify(ext)
if ext:
return "%s.%s" % (filename, ext)
else:
return "%s" % (filename,) | [
"def",
"get_valid_filename",
"(",
"s",
")",
":",
"s",
"=",
"get_valid_filename_django",
"(",
"s",
")",
"filename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"s",
")",
"filename",
"=",
"slugify",
"(",
"filename",
")",
"ext",
"=",
"slugif... | like the regular get_valid_filename, but also slugifies away
umlauts and stuff. | [
"like",
"the",
"regular",
"get_valid_filename",
"but",
"also",
"slugifies",
"away",
"umlauts",
"and",
"stuff",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/files.py#L122-L134 |
241,469 | divio/django-filer | filer/management/commands/import_files.py | FileImporter.walker | def walker(self, path=None, base_folder=None):
"""
This method walk a directory structure and create the
Folders and Files as they appear.
"""
path = path or self.path or ''
base_folder = base_folder or self.base_folder
# prevent trailing slashes and other inconsistencies on path.
path = os.path.normpath(upath(path))
if base_folder:
base_folder = os.path.normpath(upath(base_folder))
print("The directory structure will be imported in %s" % (base_folder,))
if self.verbosity >= 1:
print("Import the folders and files in %s" % (path,))
root_folder_name = os.path.basename(path)
for root, dirs, files in os.walk(path):
rel_folders = root.partition(path)[2].strip(os.path.sep).split(os.path.sep)
while '' in rel_folders:
rel_folders.remove('')
if base_folder:
folder_names = base_folder.split('/') + [root_folder_name] + rel_folders
else:
folder_names = [root_folder_name] + rel_folders
folder = self.get_or_create_folder(folder_names)
for file_obj in files:
dj_file = DjangoFile(open(os.path.join(root, file_obj), mode='rb'),
name=file_obj)
self.import_file(file_obj=dj_file, folder=folder)
if self.verbosity >= 1:
print(('folder_created #%s / file_created #%s / ' + 'image_created #%s') % (self.folder_created, self.file_created, self.image_created)) | python | def walker(self, path=None, base_folder=None):
path = path or self.path or ''
base_folder = base_folder or self.base_folder
# prevent trailing slashes and other inconsistencies on path.
path = os.path.normpath(upath(path))
if base_folder:
base_folder = os.path.normpath(upath(base_folder))
print("The directory structure will be imported in %s" % (base_folder,))
if self.verbosity >= 1:
print("Import the folders and files in %s" % (path,))
root_folder_name = os.path.basename(path)
for root, dirs, files in os.walk(path):
rel_folders = root.partition(path)[2].strip(os.path.sep).split(os.path.sep)
while '' in rel_folders:
rel_folders.remove('')
if base_folder:
folder_names = base_folder.split('/') + [root_folder_name] + rel_folders
else:
folder_names = [root_folder_name] + rel_folders
folder = self.get_or_create_folder(folder_names)
for file_obj in files:
dj_file = DjangoFile(open(os.path.join(root, file_obj), mode='rb'),
name=file_obj)
self.import_file(file_obj=dj_file, folder=folder)
if self.verbosity >= 1:
print(('folder_created #%s / file_created #%s / ' + 'image_created #%s') % (self.folder_created, self.file_created, self.image_created)) | [
"def",
"walker",
"(",
"self",
",",
"path",
"=",
"None",
",",
"base_folder",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"self",
".",
"path",
"or",
"''",
"base_folder",
"=",
"base_folder",
"or",
"self",
".",
"base_folder",
"# prevent trailing slashes ... | This method walk a directory structure and create the
Folders and Files as they appear. | [
"This",
"method",
"walk",
"a",
"directory",
"structure",
"and",
"create",
"the",
"Folders",
"and",
"Files",
"as",
"they",
"appear",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/management/commands/import_files.py#L79-L108 |
241,470 | divio/django-filer | filer/utils/zip.py | unzip | def unzip(file_obj):
"""
Take a path to a zipfile and checks if it is a valid zip file
and returns...
"""
files = []
# TODO: implement try-except here
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
infolist = zip.infolist()
for zipinfo in infolist:
if zipinfo.filename.startswith('__'): # do not process meta files
continue
file_obj = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo))
files.append((file_obj, zipinfo.filename))
zip.close()
return files | python | def unzip(file_obj):
files = []
# TODO: implement try-except here
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
infolist = zip.infolist()
for zipinfo in infolist:
if zipinfo.filename.startswith('__'): # do not process meta files
continue
file_obj = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo))
files.append((file_obj, zipinfo.filename))
zip.close()
return files | [
"def",
"unzip",
"(",
"file_obj",
")",
":",
"files",
"=",
"[",
"]",
"# TODO: implement try-except here",
"zip",
"=",
"ZipFile",
"(",
"file_obj",
")",
"bad_file",
"=",
"zip",
".",
"testzip",
"(",
")",
"if",
"bad_file",
":",
"raise",
"Exception",
"(",
"'\"%s\... | Take a path to a zipfile and checks if it is a valid zip file
and returns... | [
"Take",
"a",
"path",
"to",
"a",
"zipfile",
"and",
"checks",
"if",
"it",
"is",
"a",
"valid",
"zip",
"file",
"and",
"returns",
"..."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/zip.py#L9-L27 |
241,471 | divio/django-filer | filer/utils/filer_easy_thumbnails.py | ThumbnailerNameMixin.get_thumbnail_name | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename.
"""
path, source_filename = os.path.split(self.name)
source_extension = os.path.splitext(source_filename)[1][1:]
if self.thumbnail_preserve_extensions is True or \
(self.thumbnail_preserve_extensions and source_extension.lower()
in self.thumbnail_preserve_extensions):
extension = source_extension
elif transparent:
extension = self.thumbnail_transparency_extension
else:
extension = self.thumbnail_extension
extension = extension or 'jpg'
thumbnail_options = thumbnail_options.copy()
size = tuple(thumbnail_options.pop('size'))
quality = thumbnail_options.pop('quality', self.thumbnail_quality)
initial_opts = ['%sx%s' % size, 'q%s' % quality]
opts = list(thumbnail_options.items())
opts.sort() # Sort the options so the file name is consistent.
opts = ['%s' % (v is not True and '%s-%s' % (k, v) or k)
for k, v in opts if v]
all_opts = '_'.join(initial_opts + opts)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
# make sure our magic delimiter is not used in all_opts
all_opts = all_opts.replace('__', '_')
if high_resolution:
try:
all_opts += self.thumbnail_highres_infix
except AttributeError:
all_opts += '@2x'
filename = '%s__%s.%s' % (source_filename, all_opts, extension)
return os.path.join(basedir, path, subdir, filename) | python | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
path, source_filename = os.path.split(self.name)
source_extension = os.path.splitext(source_filename)[1][1:]
if self.thumbnail_preserve_extensions is True or \
(self.thumbnail_preserve_extensions and source_extension.lower()
in self.thumbnail_preserve_extensions):
extension = source_extension
elif transparent:
extension = self.thumbnail_transparency_extension
else:
extension = self.thumbnail_extension
extension = extension or 'jpg'
thumbnail_options = thumbnail_options.copy()
size = tuple(thumbnail_options.pop('size'))
quality = thumbnail_options.pop('quality', self.thumbnail_quality)
initial_opts = ['%sx%s' % size, 'q%s' % quality]
opts = list(thumbnail_options.items())
opts.sort() # Sort the options so the file name is consistent.
opts = ['%s' % (v is not True and '%s-%s' % (k, v) or k)
for k, v in opts if v]
all_opts = '_'.join(initial_opts + opts)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
# make sure our magic delimiter is not used in all_opts
all_opts = all_opts.replace('__', '_')
if high_resolution:
try:
all_opts += self.thumbnail_highres_infix
except AttributeError:
all_opts += '@2x'
filename = '%s__%s.%s' % (source_filename, all_opts, extension)
return os.path.join(basedir, path, subdir, filename) | [
"def",
"get_thumbnail_name",
"(",
"self",
",",
"thumbnail_options",
",",
"transparent",
"=",
"False",
",",
"high_resolution",
"=",
"False",
")",
":",
"path",
",",
"source_filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"sour... | A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename. | [
"A",
"version",
"of",
"Thumbnailer",
".",
"get_thumbnail_name",
"that",
"produces",
"a",
"reproducible",
"thumbnail",
"name",
"that",
"can",
"be",
"converted",
"back",
"to",
"the",
"original",
"filename",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/filer_easy_thumbnails.py#L29-L72 |
241,472 | divio/django-filer | filer/utils/filer_easy_thumbnails.py | ActionThumbnailerMixin.get_thumbnail_name | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that returns the original
filename to resize.
"""
path, filename = os.path.split(self.name)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
return os.path.join(basedir, path, subdir, filename) | python | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
path, filename = os.path.split(self.name)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
return os.path.join(basedir, path, subdir, filename) | [
"def",
"get_thumbnail_name",
"(",
"self",
",",
"thumbnail_options",
",",
"transparent",
"=",
"False",
",",
"high_resolution",
"=",
"False",
")",
":",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"basedir",
... | A version of ``Thumbnailer.get_thumbnail_name`` that returns the original
filename to resize. | [
"A",
"version",
"of",
"Thumbnailer",
".",
"get_thumbnail_name",
"that",
"returns",
"the",
"original",
"filename",
"to",
"resize",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/filer_easy_thumbnails.py#L80-L91 |
241,473 | divio/django-filer | filer/admin/folderadmin.py | FolderAdmin.owner_search_fields | def owner_search_fields(self):
"""
Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email.
"""
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return [
field.name for field in User._meta.fields
if isinstance(field, models.CharField) and field.name != 'password'
] | python | def owner_search_fields(self):
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return [
field.name for field in User._meta.fields
if isinstance(field, models.CharField) and field.name != 'password'
] | [
"def",
"owner_search_fields",
"(",
"self",
")",
":",
"try",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
"import",
"get_user_model",
"except",
"ImportError",
":",
"# Django < 1.5",
"from",
"django",
".",
"contrib",
".",
"auth",
".",
"models",
"import",
... | Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email. | [
"Returns",
"all",
"the",
"fields",
"that",
"are",
"CharFields",
"except",
"for",
"password",
"from",
"the",
"User",
"model",
".",
"For",
"the",
"built",
"-",
"in",
"User",
"model",
"that",
"means",
"username",
"first_name",
"last_name",
"and",
"email",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/folderadmin.py#L481-L496 |
241,474 | divio/django-filer | filer/admin/folderadmin.py | FolderAdmin.move_to_clipboard | def move_to_clipboard(self, request, files_queryset, folders_queryset):
"""
Action which moves the selected files and files in selected folders
to clipboard.
"""
if not self.has_change_permission(request):
raise PermissionDenied
if request.method != 'POST':
return None
clipboard = tools.get_user_clipboard(request.user)
check_files_edit_permissions(request, files_queryset)
check_folder_edit_permissions(request, folders_queryset)
# TODO: Display a confirmation page if moving more than X files to
# clipboard?
# We define it like that so that we can modify it inside the
# move_files function
files_count = [0]
def move_files(files):
files_count[0] += tools.move_file_to_clipboard(files, clipboard)
def move_folders(folders):
for f in folders:
move_files(f.files)
move_folders(f.children.all())
move_files(files_queryset)
move_folders(folders_queryset)
self.message_user(request, _("Successfully moved %(count)d files to "
"clipboard.") % {"count": files_count[0]})
return None | python | def move_to_clipboard(self, request, files_queryset, folders_queryset):
if not self.has_change_permission(request):
raise PermissionDenied
if request.method != 'POST':
return None
clipboard = tools.get_user_clipboard(request.user)
check_files_edit_permissions(request, files_queryset)
check_folder_edit_permissions(request, folders_queryset)
# TODO: Display a confirmation page if moving more than X files to
# clipboard?
# We define it like that so that we can modify it inside the
# move_files function
files_count = [0]
def move_files(files):
files_count[0] += tools.move_file_to_clipboard(files, clipboard)
def move_folders(folders):
for f in folders:
move_files(f.files)
move_folders(f.children.all())
move_files(files_queryset)
move_folders(folders_queryset)
self.message_user(request, _("Successfully moved %(count)d files to "
"clipboard.") % {"count": files_count[0]})
return None | [
"def",
"move_to_clipboard",
"(",
"self",
",",
"request",
",",
"files_queryset",
",",
"folders_queryset",
")",
":",
"if",
"not",
"self",
".",
"has_change_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"if",
"request",
".",
"method",
"!=",
"... | Action which moves the selected files and files in selected folders
to clipboard. | [
"Action",
"which",
"moves",
"the",
"selected",
"files",
"and",
"files",
"in",
"selected",
"folders",
"to",
"clipboard",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/folderadmin.py#L596-L634 |
241,475 | divio/django-filer | filer/admin/tools.py | admin_url_params | def admin_url_params(request, params=None):
"""
given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode.
"""
params = params or {}
if popup_status(request):
params[IS_POPUP_VAR] = '1'
pick_type = popup_pick_type(request)
if pick_type:
params['_pick'] = pick_type
return params | python | def admin_url_params(request, params=None):
params = params or {}
if popup_status(request):
params[IS_POPUP_VAR] = '1'
pick_type = popup_pick_type(request)
if pick_type:
params['_pick'] = pick_type
return params | [
"def",
"admin_url_params",
"(",
"request",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"params",
"or",
"{",
"}",
"if",
"popup_status",
"(",
"request",
")",
":",
"params",
"[",
"IS_POPUP_VAR",
"]",
"=",
"'1'",
"pick_type",
"=",
"popup_pick_type",
... | given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode. | [
"given",
"a",
"request",
"looks",
"at",
"GET",
"and",
"POST",
"values",
"to",
"determine",
"which",
"params",
"should",
"be",
"added",
".",
"Is",
"used",
"to",
"keep",
"the",
"context",
"of",
"popup",
"and",
"picker",
"mode",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/tools.py#L70-L81 |
241,476 | divio/django-filer | filer/admin/imageadmin.py | ImageAdminForm.clean_subject_location | def clean_subject_location(self):
"""
Validate subject_location preserving last saved value.
Last valid value of the subject_location field is shown to the user
for subject location widget to receive valid coordinates on field
validation errors.
"""
cleaned_data = super(ImageAdminForm, self).clean()
subject_location = cleaned_data['subject_location']
if not subject_location:
# if supplied subject location is empty, do not check it
return subject_location
# use thumbnail's helper function to check the format
coordinates = normalize_subject_location(subject_location)
if not coordinates:
err_msg = ugettext_lazy('Invalid subject location format. ')
err_code = 'invalid_subject_format'
elif (
coordinates[0] > self.instance.width
or coordinates[1] > self.instance.height
):
err_msg = ugettext_lazy(
'Subject location is outside of the image. ')
err_code = 'subject_out_of_bounds'
else:
return subject_location
self._set_previous_subject_location(cleaned_data)
raise forms.ValidationError(
string_concat(
err_msg,
ugettext_lazy('Your input: "{subject_location}". '.format(
subject_location=subject_location)),
'Previous value is restored.'),
code=err_code) | python | def clean_subject_location(self):
cleaned_data = super(ImageAdminForm, self).clean()
subject_location = cleaned_data['subject_location']
if not subject_location:
# if supplied subject location is empty, do not check it
return subject_location
# use thumbnail's helper function to check the format
coordinates = normalize_subject_location(subject_location)
if not coordinates:
err_msg = ugettext_lazy('Invalid subject location format. ')
err_code = 'invalid_subject_format'
elif (
coordinates[0] > self.instance.width
or coordinates[1] > self.instance.height
):
err_msg = ugettext_lazy(
'Subject location is outside of the image. ')
err_code = 'subject_out_of_bounds'
else:
return subject_location
self._set_previous_subject_location(cleaned_data)
raise forms.ValidationError(
string_concat(
err_msg,
ugettext_lazy('Your input: "{subject_location}". '.format(
subject_location=subject_location)),
'Previous value is restored.'),
code=err_code) | [
"def",
"clean_subject_location",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"ImageAdminForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"subject_location",
"=",
"cleaned_data",
"[",
"'subject_location'",
"]",
"if",
"not",
"subject_location",
":",
... | Validate subject_location preserving last saved value.
Last valid value of the subject_location field is shown to the user
for subject location widget to receive valid coordinates on field
validation errors. | [
"Validate",
"subject_location",
"preserving",
"last",
"saved",
"value",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/imageadmin.py#L42-L80 |
241,477 | divio/django-filer | filer/utils/loader.py | load_object | def load_object(import_path):
"""
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised.
"""
if not isinstance(import_path, six.string_types):
return import_path
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'django_load.core.load_object' must "
"contain at least one dot.")
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name) | python | def load_object(import_path):
if not isinstance(import_path, six.string_types):
return import_path
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'django_load.core.load_object' must "
"contain at least one dot.")
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name) | [
"def",
"load_object",
"(",
"import_path",
")",
":",
"if",
"not",
"isinstance",
"(",
"import_path",
",",
"six",
".",
"string_types",
")",
":",
"return",
"import_path",
"if",
"'.'",
"not",
"in",
"import_path",
":",
"raise",
"TypeError",
"(",
"\"'import_path' arg... | Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised. | [
"Loads",
"an",
"object",
"from",
"an",
"import_path",
"like",
"in",
"MIDDLEWARE_CLASSES",
"and",
"the",
"likes",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/loader.py#L18-L41 |
241,478 | divio/django-filer | filer/management/commands/generate_thumbnails.py | Command.handle | def handle(self, *args, **options):
"""
Generates image thumbnails
NOTE: To keep memory consumption stable avoid iteration over the Image queryset
"""
pks = Image.objects.all().values_list('id', flat=True)
total = len(pks)
for idx, pk in enumerate(pks):
image = None
try:
image = Image.objects.get(pk=pk)
self.stdout.write(u'Processing image {0} / {1} {2}'.format(idx + 1, total, image))
self.stdout.flush()
image.thumbnails
image.icons
except IOError as e:
self.stderr.write('Failed to generate thumbnails: {0}'.format(str(e)))
self.stderr.flush()
finally:
del image | python | def handle(self, *args, **options):
pks = Image.objects.all().values_list('id', flat=True)
total = len(pks)
for idx, pk in enumerate(pks):
image = None
try:
image = Image.objects.get(pk=pk)
self.stdout.write(u'Processing image {0} / {1} {2}'.format(idx + 1, total, image))
self.stdout.flush()
image.thumbnails
image.icons
except IOError as e:
self.stderr.write('Failed to generate thumbnails: {0}'.format(str(e)))
self.stderr.flush()
finally:
del image | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"pks",
"=",
"Image",
".",
"objects",
".",
"all",
"(",
")",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"total",
"=",
"len",
"(",
"pks",
")",... | Generates image thumbnails
NOTE: To keep memory consumption stable avoid iteration over the Image queryset | [
"Generates",
"image",
"thumbnails"
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/management/commands/generate_thumbnails.py#L9-L29 |
241,479 | divio/django-filer | filer/utils/compatibility.py | upath | def upath(path):
"""
Always return a unicode path.
"""
if six.PY2 and not isinstance(path, six.text_type):
return path.decode(fs_encoding)
return path | python | def upath(path):
if six.PY2 and not isinstance(path, six.text_type):
return path.decode(fs_encoding)
return path | [
"def",
"upath",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY2",
"and",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
":",
"return",
"path",
".",
"decode",
"(",
"fs_encoding",
")",
"return",
"path"
] | Always return a unicode path. | [
"Always",
"return",
"a",
"unicode",
"path",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/compatibility.py#L60-L66 |
241,480 | divio/django-filer | filer/utils/model_label.py | get_model_label | def get_model_label(model):
"""
Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel"
"""
if isinstance(model, six.string_types):
return model
else:
return "%s.%s" % (
model._meta.app_label,
model.__name__
) | python | def get_model_label(model):
if isinstance(model, six.string_types):
return model
else:
return "%s.%s" % (
model._meta.app_label,
model.__name__
) | [
"def",
"get_model_label",
"(",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"six",
".",
"string_types",
")",
":",
"return",
"model",
"else",
":",
"return",
"\"%s.%s\"",
"%",
"(",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
... | Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel" | [
"Take",
"a",
"model",
"class",
"or",
"model",
"label",
"and",
"return",
"its",
"model",
"label",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/model_label.py#L8-L24 |
241,481 | divio/django-filer | filer/admin/clipboardadmin.py | ajax_upload | def ajax_upload(request, folder_id=None):
"""
Receives an upload from the uploader. Receives only one file at a time.
"""
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return JsonResponse({'error': NO_FOLDER_ERROR})
# check permissions
if folder and not folder.has_add_children_permission(request):
return JsonResponse({'error': NO_PERMISSIONS_FOR_FOLDER})
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# TODO: Deprecated/refactor
# Get clipboad
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in filer_settings.FILER_FILE_MODELS:
FileSubClass = load_model(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = filer_settings.FILER_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
# Try to generate thumbnails.
if not file_obj.icons:
# There is no point to continue, as we can't generate
# thumbnails for this file. Usual reasons: bad format or
# filename.
file_obj.delete()
# This would be logged in BaseImage._generate_thumbnails()
# if FILER_ENABLE_LOGGING is on.
return JsonResponse(
{'error': 'failed to generate icons for file'},
status=500,
)
thumbnail = None
# Backwards compatibility: try to get specific icon size (32px)
# first. Then try medium icon size (they are already sorted),
# fallback to the first (smallest) configured icon.
for size in (['32']
+ filer_settings.FILER_ADMIN_ICON_SIZES[1::-1]):
try:
thumbnail = file_obj.icons[size]
break
except KeyError:
continue
data = {
'thumbnail': thumbnail,
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
# prepare preview thumbnail
if type(file_obj) == Image:
thumbnail_180_options = {
'size': (180, 180),
'crop': True,
'upscale': True,
}
thumbnail_180 = file_obj.file.get_thumbnail(
thumbnail_180_options)
data['thumbnail_180'] = thumbnail_180.url
data['original_image'] = file_obj.url
return JsonResponse(data)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(
uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (
form_errors,))
except UploadException as e:
return JsonResponse({'error': str(e)}, status=500) | python | def ajax_upload(request, folder_id=None):
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return JsonResponse({'error': NO_FOLDER_ERROR})
# check permissions
if folder and not folder.has_add_children_permission(request):
return JsonResponse({'error': NO_PERMISSIONS_FOR_FOLDER})
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# TODO: Deprecated/refactor
# Get clipboad
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in filer_settings.FILER_FILE_MODELS:
FileSubClass = load_model(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = filer_settings.FILER_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
# Try to generate thumbnails.
if not file_obj.icons:
# There is no point to continue, as we can't generate
# thumbnails for this file. Usual reasons: bad format or
# filename.
file_obj.delete()
# This would be logged in BaseImage._generate_thumbnails()
# if FILER_ENABLE_LOGGING is on.
return JsonResponse(
{'error': 'failed to generate icons for file'},
status=500,
)
thumbnail = None
# Backwards compatibility: try to get specific icon size (32px)
# first. Then try medium icon size (they are already sorted),
# fallback to the first (smallest) configured icon.
for size in (['32']
+ filer_settings.FILER_ADMIN_ICON_SIZES[1::-1]):
try:
thumbnail = file_obj.icons[size]
break
except KeyError:
continue
data = {
'thumbnail': thumbnail,
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
# prepare preview thumbnail
if type(file_obj) == Image:
thumbnail_180_options = {
'size': (180, 180),
'crop': True,
'upscale': True,
}
thumbnail_180 = file_obj.file.get_thumbnail(
thumbnail_180_options)
data['thumbnail_180'] = thumbnail_180.url
data['original_image'] = file_obj.url
return JsonResponse(data)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(
uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (
form_errors,))
except UploadException as e:
return JsonResponse({'error': str(e)}, status=500) | [
"def",
"ajax_upload",
"(",
"request",
",",
"folder_id",
"=",
"None",
")",
":",
"folder",
"=",
"None",
"if",
"folder_id",
":",
"try",
":",
"# Get folder",
"folder",
"=",
"Folder",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"folder_id",
")",
"except",
"... | Receives an upload from the uploader. Receives only one file at a time. | [
"Receives",
"an",
"upload",
"from",
"the",
"uploader",
".",
"Receives",
"only",
"one",
"file",
"at",
"a",
"time",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/clipboardadmin.py#L72-L174 |
241,482 | pyeve/cerberus | cerberus/validator.py | BareValidator.__store_config | def __store_config(self, args, kwargs):
""" Assign args to kwargs and store configuration. """
signature = (
'schema',
'ignore_none_values',
'allow_unknown',
'require_all',
'purge_unknown',
'purge_readonly',
)
for i, p in enumerate(signature[: len(args)]):
if p in kwargs:
raise TypeError("__init__ got multiple values for argument " "'%s'" % p)
else:
kwargs[p] = args[i]
self._config = kwargs
""" This dictionary holds the configuration arguments that were used to
initialize the :class:`Validator` instance except the
``error_handler``. """ | python | def __store_config(self, args, kwargs):
signature = (
'schema',
'ignore_none_values',
'allow_unknown',
'require_all',
'purge_unknown',
'purge_readonly',
)
for i, p in enumerate(signature[: len(args)]):
if p in kwargs:
raise TypeError("__init__ got multiple values for argument " "'%s'" % p)
else:
kwargs[p] = args[i]
self._config = kwargs
""" This dictionary holds the configuration arguments that were used to
initialize the :class:`Validator` instance except the
``error_handler``. """ | [
"def",
"__store_config",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"signature",
"=",
"(",
"'schema'",
",",
"'ignore_none_values'",
",",
"'allow_unknown'",
",",
"'require_all'",
",",
"'purge_unknown'",
",",
"'purge_readonly'",
",",
")",
"for",
"i",
","... | Assign args to kwargs and store configuration. | [
"Assign",
"args",
"to",
"kwargs",
"and",
"store",
"configuration",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L207-L225 |
241,483 | pyeve/cerberus | cerberus/validator.py | BareValidator._error | def _error(self, *args):
""" Creates and adds one or multiple errors.
:param args: Accepts different argument's signatures.
*1. Bulk addition of errors:*
- :term:`iterable` of
:class:`~cerberus.errors.ValidationError`-instances
The errors will be added to
:attr:`~cerberus.Validator._errors`.
*2. Custom error:*
- the invalid field's name
- the error message
A custom error containing the message will be created and
added to :attr:`~cerberus.Validator._errors`.
There will however be fewer information contained in the
error (no reference to the violated rule and its
constraint).
*3. Defined error:*
- the invalid field's name
- the error-reference, see :mod:`cerberus.errors`
- arbitrary, supplemental information about the error
A :class:`~cerberus.errors.ValidationError` instance will
be created and added to
:attr:`~cerberus.Validator._errors`.
"""
if len(args) == 1:
self._errors.extend(args[0])
self._errors.sort()
for error in args[0]:
self.document_error_tree.add(error)
self.schema_error_tree.add(error)
self.error_handler.emit(error)
elif len(args) == 2 and isinstance(args[1], _str_type):
self._error(args[0], errors.CUSTOM, args[1])
elif len(args) >= 2:
field = args[0]
code = args[1].code
rule = args[1].rule
info = args[2:]
document_path = self.document_path + (field,)
schema_path = self.schema_path
if code != errors.UNKNOWN_FIELD.code and rule is not None:
schema_path += (field, rule)
if not rule:
constraint = None
else:
field_definitions = self._resolve_rules_set(self.schema[field])
if rule == 'nullable':
constraint = field_definitions.get(rule, False)
elif rule == 'required':
constraint = field_definitions.get(rule, self.require_all)
if rule not in field_definitions:
schema_path = "__require_all__"
else:
constraint = field_definitions[rule]
value = self.document.get(field)
self.recent_error = errors.ValidationError(
document_path, schema_path, code, rule, constraint, value, info
)
self._error([self.recent_error]) | python | def _error(self, *args):
if len(args) == 1:
self._errors.extend(args[0])
self._errors.sort()
for error in args[0]:
self.document_error_tree.add(error)
self.schema_error_tree.add(error)
self.error_handler.emit(error)
elif len(args) == 2 and isinstance(args[1], _str_type):
self._error(args[0], errors.CUSTOM, args[1])
elif len(args) >= 2:
field = args[0]
code = args[1].code
rule = args[1].rule
info = args[2:]
document_path = self.document_path + (field,)
schema_path = self.schema_path
if code != errors.UNKNOWN_FIELD.code and rule is not None:
schema_path += (field, rule)
if not rule:
constraint = None
else:
field_definitions = self._resolve_rules_set(self.schema[field])
if rule == 'nullable':
constraint = field_definitions.get(rule, False)
elif rule == 'required':
constraint = field_definitions.get(rule, self.require_all)
if rule not in field_definitions:
schema_path = "__require_all__"
else:
constraint = field_definitions[rule]
value = self.document.get(field)
self.recent_error = errors.ValidationError(
document_path, schema_path, code, rule, constraint, value, info
)
self._error([self.recent_error]) | [
"def",
"_error",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"self",
".",
"_errors",
".",
"extend",
"(",
"args",
"[",
"0",
"]",
")",
"self",
".",
"_errors",
".",
"sort",
"(",
")",
"for",
"error",
"i... | Creates and adds one or multiple errors.
:param args: Accepts different argument's signatures.
*1. Bulk addition of errors:*
- :term:`iterable` of
:class:`~cerberus.errors.ValidationError`-instances
The errors will be added to
:attr:`~cerberus.Validator._errors`.
*2. Custom error:*
- the invalid field's name
- the error message
A custom error containing the message will be created and
added to :attr:`~cerberus.Validator._errors`.
There will however be fewer information contained in the
error (no reference to the violated rule and its
constraint).
*3. Defined error:*
- the invalid field's name
- the error-reference, see :mod:`cerberus.errors`
- arbitrary, supplemental information about the error
A :class:`~cerberus.errors.ValidationError` instance will
be created and added to
:attr:`~cerberus.Validator._errors`. | [
"Creates",
"and",
"adds",
"one",
"or",
"multiple",
"errors",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L232-L308 |
241,484 | pyeve/cerberus | cerberus/validator.py | BareValidator.__validate_definitions | def __validate_definitions(self, definitions, field):
""" Validate a field's value against its defined rules. """
def validate_rule(rule):
validator = self.__get_rule_handler('validate', rule)
return validator(definitions.get(rule, None), field, value)
definitions = self._resolve_rules_set(definitions)
value = self.document[field]
rules_queue = [
x
for x in self.priority_validations
if x in definitions or x in self.mandatory_validations
]
rules_queue.extend(
x for x in self.mandatory_validations if x not in rules_queue
)
rules_queue.extend(
x
for x in definitions
if x not in rules_queue
and x not in self.normalization_rules
and x not in ('allow_unknown', 'require_all', 'meta', 'required')
)
self._remaining_rules = rules_queue
while self._remaining_rules:
rule = self._remaining_rules.pop(0)
try:
result = validate_rule(rule)
# TODO remove on next breaking release
if result:
break
except _SchemaRuleTypeError:
break
self._drop_remaining_rules() | python | def __validate_definitions(self, definitions, field):
def validate_rule(rule):
validator = self.__get_rule_handler('validate', rule)
return validator(definitions.get(rule, None), field, value)
definitions = self._resolve_rules_set(definitions)
value = self.document[field]
rules_queue = [
x
for x in self.priority_validations
if x in definitions or x in self.mandatory_validations
]
rules_queue.extend(
x for x in self.mandatory_validations if x not in rules_queue
)
rules_queue.extend(
x
for x in definitions
if x not in rules_queue
and x not in self.normalization_rules
and x not in ('allow_unknown', 'require_all', 'meta', 'required')
)
self._remaining_rules = rules_queue
while self._remaining_rules:
rule = self._remaining_rules.pop(0)
try:
result = validate_rule(rule)
# TODO remove on next breaking release
if result:
break
except _SchemaRuleTypeError:
break
self._drop_remaining_rules() | [
"def",
"__validate_definitions",
"(",
"self",
",",
"definitions",
",",
"field",
")",
":",
"def",
"validate_rule",
"(",
"rule",
")",
":",
"validator",
"=",
"self",
".",
"__get_rule_handler",
"(",
"'validate'",
",",
"rule",
")",
"return",
"validator",
"(",
"de... | Validate a field's value against its defined rules. | [
"Validate",
"a",
"field",
"s",
"value",
"against",
"its",
"defined",
"rules",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L1036-L1073 |
241,485 | mobolic/facebook-sdk | facebook/__init__.py | get_user_from_cookie | def get_user_from_cookie(cookies, app_id, app_secret):
"""Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Read more about Facebook authentication at
https://developers.facebook.com/docs/facebook-login.
"""
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
return None
parsed_request = parse_signed_request(cookie, app_secret)
if not parsed_request:
return None
try:
result = GraphAPI().get_access_token_from_code(
parsed_request["code"], "", app_id, app_secret
)
except GraphAPIError:
return None
result["uid"] = parsed_request["user_id"]
return result | python | def get_user_from_cookie(cookies, app_id, app_secret):
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
return None
parsed_request = parse_signed_request(cookie, app_secret)
if not parsed_request:
return None
try:
result = GraphAPI().get_access_token_from_code(
parsed_request["code"], "", app_id, app_secret
)
except GraphAPIError:
return None
result["uid"] = parsed_request["user_id"]
return result | [
"def",
"get_user_from_cookie",
"(",
"cookies",
",",
"app_id",
",",
"app_secret",
")",
":",
"cookie",
"=",
"cookies",
".",
"get",
"(",
"\"fbsr_\"",
"+",
"app_id",
",",
"\"\"",
")",
"if",
"not",
"cookie",
":",
"return",
"None",
"parsed_request",
"=",
"parse_... | Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Read more about Facebook authentication at
https://developers.facebook.com/docs/facebook-login. | [
"Parses",
"the",
"cookie",
"set",
"by",
"the",
"official",
"Facebook",
"JavaScript",
"SDK",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L443-L472 |
241,486 | mobolic/facebook-sdk | facebook/__init__.py | parse_signed_request | def parse_signed_request(signed_request, app_secret):
""" Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned.
"""
try:
encoded_sig, payload = map(str, signed_request.split(".", 1))
sig = base64.urlsafe_b64decode(
encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)
)
data = base64.urlsafe_b64decode(
payload + "=" * ((4 - len(payload) % 4) % 4)
)
except IndexError:
# Signed request was malformed.
return False
except TypeError:
# Signed request had a corrupted payload.
return False
except binascii.Error:
# Signed request had a corrupted payload.
return False
data = json.loads(data.decode("ascii"))
if data.get("algorithm", "").upper() != "HMAC-SHA256":
return False
# HMAC can only handle ascii (byte) strings
# https://bugs.python.org/issue5285
app_secret = app_secret.encode("ascii")
payload = payload.encode("ascii")
expected_sig = hmac.new(
app_secret, msg=payload, digestmod=hashlib.sha256
).digest()
if sig != expected_sig:
return False
return data | python | def parse_signed_request(signed_request, app_secret):
try:
encoded_sig, payload = map(str, signed_request.split(".", 1))
sig = base64.urlsafe_b64decode(
encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)
)
data = base64.urlsafe_b64decode(
payload + "=" * ((4 - len(payload) % 4) % 4)
)
except IndexError:
# Signed request was malformed.
return False
except TypeError:
# Signed request had a corrupted payload.
return False
except binascii.Error:
# Signed request had a corrupted payload.
return False
data = json.loads(data.decode("ascii"))
if data.get("algorithm", "").upper() != "HMAC-SHA256":
return False
# HMAC can only handle ascii (byte) strings
# https://bugs.python.org/issue5285
app_secret = app_secret.encode("ascii")
payload = payload.encode("ascii")
expected_sig = hmac.new(
app_secret, msg=payload, digestmod=hashlib.sha256
).digest()
if sig != expected_sig:
return False
return data | [
"def",
"parse_signed_request",
"(",
"signed_request",
",",
"app_secret",
")",
":",
"try",
":",
"encoded_sig",
",",
"payload",
"=",
"map",
"(",
"str",
",",
"signed_request",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
")",
"sig",
"=",
"base64",
".",
"urlsa... | Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned. | [
"Return",
"dictionary",
"with",
"signed",
"request",
"data",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L475-L519 |
241,487 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_permissions | def get_permissions(self, user_id):
"""Fetches the permissions object from the graph."""
response = self.request(
"{0}/{1}/permissions".format(self.version, user_id), {}
)["data"]
return {x["permission"] for x in response if x["status"] == "granted"} | python | def get_permissions(self, user_id):
response = self.request(
"{0}/{1}/permissions".format(self.version, user_id), {}
)["data"]
return {x["permission"] for x in response if x["status"] == "granted"} | [
"def",
"get_permissions",
"(",
"self",
",",
"user_id",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"\"{0}/{1}/permissions\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"user_id",
")",
",",
"{",
"}",
")",
"[",
"\"data\"",
"]",
"return",... | Fetches the permissions object from the graph. | [
"Fetches",
"the",
"permissions",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L126-L131 |
241,488 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_object | def get_object(self, id, **args):
"""Fetches the given object from the graph."""
return self.request("{0}/{1}".format(self.version, id), args) | python | def get_object(self, id, **args):
return self.request("{0}/{1}".format(self.version, id), args) | [
"def",
"get_object",
"(",
"self",
",",
"id",
",",
"*",
"*",
"args",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"id",
")",
",",
"args",
")"
] | Fetches the given object from the graph. | [
"Fetches",
"the",
"given",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L133-L135 |
241,489 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_objects | def get_objects(self, ids, **args):
"""Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception.
"""
args["ids"] = ",".join(ids)
return self.request(self.version + "/", args) | python | def get_objects(self, ids, **args):
args["ids"] = ",".join(ids)
return self.request(self.version + "/", args) | [
"def",
"get_objects",
"(",
"self",
",",
"ids",
",",
"*",
"*",
"args",
")",
":",
"args",
"[",
"\"ids\"",
"]",
"=",
"\",\"",
".",
"join",
"(",
"ids",
")",
"return",
"self",
".",
"request",
"(",
"self",
".",
"version",
"+",
"\"/\"",
",",
"args",
")"... | Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception. | [
"Fetches",
"all",
"of",
"the",
"given",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L137-L144 |
241,490 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_connections | def get_connections(self, id, connection_name, **args):
"""Fetches the connections for given object."""
return self.request(
"{0}/{1}/{2}".format(self.version, id, connection_name), args
) | python | def get_connections(self, id, connection_name, **args):
return self.request(
"{0}/{1}/{2}".format(self.version, id, connection_name), args
) | [
"def",
"get_connections",
"(",
"self",
",",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}/{2}\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"id",
",",
"connection_name",
")",
",",
... | Fetches the connections for given object. | [
"Fetches",
"the",
"connections",
"for",
"given",
"object",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L156-L160 |
241,491 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_all_connections | def get_all_connections(self, id, connection_name, **args):
"""Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items.
"""
while True:
page = self.get_connections(id, connection_name, **args)
for post in page["data"]:
yield post
next = page.get("paging", {}).get("next")
if not next:
return
args = parse_qs(urlparse(next).query)
del args["access_token"] | python | def get_all_connections(self, id, connection_name, **args):
while True:
page = self.get_connections(id, connection_name, **args)
for post in page["data"]:
yield post
next = page.get("paging", {}).get("next")
if not next:
return
args = parse_qs(urlparse(next).query)
del args["access_token"] | [
"def",
"get_all_connections",
"(",
"self",
",",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
":",
"while",
"True",
":",
"page",
"=",
"self",
".",
"get_connections",
"(",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
"for",
"pos... | Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items. | [
"Get",
"all",
"pages",
"from",
"a",
"get_connections",
"call"
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L162-L176 |
241,492 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.put_object | def put_object(self, parent_object, connection_name, **data):
"""Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
Certain operations require extended permissions. See
https://developers.facebook.com/docs/facebook-login/permissions
for details about permissions.
"""
assert self.access_token, "Write operations require an access token"
return self.request(
"{0}/{1}/{2}".format(self.version, parent_object, connection_name),
post_args=data,
method="POST",
) | python | def put_object(self, parent_object, connection_name, **data):
assert self.access_token, "Write operations require an access token"
return self.request(
"{0}/{1}/{2}".format(self.version, parent_object, connection_name),
post_args=data,
method="POST",
) | [
"def",
"put_object",
"(",
"self",
",",
"parent_object",
",",
"connection_name",
",",
"*",
"*",
"data",
")",
":",
"assert",
"self",
".",
"access_token",
",",
"\"Write operations require an access token\"",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}/{2}\"",
"... | Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
Certain operations require extended permissions. See
https://developers.facebook.com/docs/facebook-login/permissions
for details about permissions. | [
"Writes",
"the",
"given",
"object",
"to",
"the",
"graph",
"connected",
"to",
"the",
"given",
"parent",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L178-L202 |
241,493 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.delete_request | def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
return self.request(
"{0}_{1}".format(request_id, user_id), method="DELETE"
) | python | def delete_request(self, user_id, request_id):
return self.request(
"{0}_{1}".format(request_id, user_id), method="DELETE"
) | [
"def",
"delete_request",
"(",
"self",
",",
"user_id",
",",
"request_id",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}_{1}\"",
".",
"format",
"(",
"request_id",
",",
"user_id",
")",
",",
"method",
"=",
"\"DELETE\"",
")"
] | Deletes the Request with the given ID for the given user. | [
"Deletes",
"the",
"Request",
"with",
"the",
"given",
"ID",
"for",
"the",
"given",
"user",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L218-L222 |
241,494 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_version | def get_version(self):
"""Fetches the current version number of the Graph API being used."""
args = {"access_token": self.access_token}
try:
response = self.session.request(
"GET",
FACEBOOK_GRAPH_URL + self.version + "/me",
params=args,
timeout=self.timeout,
proxies=self.proxies,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
try:
headers = response.headers
version = headers["facebook-api-version"].replace("v", "")
return str(version)
except Exception:
raise GraphAPIError("API version number not available") | python | def get_version(self):
args = {"access_token": self.access_token}
try:
response = self.session.request(
"GET",
FACEBOOK_GRAPH_URL + self.version + "/me",
params=args,
timeout=self.timeout,
proxies=self.proxies,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
try:
headers = response.headers
version = headers["facebook-api-version"].replace("v", "")
return str(version)
except Exception:
raise GraphAPIError("API version number not available") | [
"def",
"get_version",
"(",
"self",
")",
":",
"args",
"=",
"{",
"\"access_token\"",
":",
"self",
".",
"access_token",
"}",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"\"GET\"",
",",
"FACEBOOK_GRAPH_URL",
"+",
"self",
".",
"v... | Fetches the current version number of the Graph API being used. | [
"Fetches",
"the",
"current",
"version",
"number",
"of",
"the",
"Graph",
"API",
"being",
"used",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L239-L259 |
241,495 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.request | def request(
self, path, args=None, post_args=None, files=None, method=None
):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
if args is None:
args = dict()
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
try:
response = self.session.request(
method or "GET",
FACEBOOK_GRAPH_URL + path,
timeout=self.timeout,
params=args,
data=post_args,
proxies=self.proxies,
files=files,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
headers = response.headers
if "json" in headers["content-type"]:
result = response.json()
elif "image/" in headers["content-type"]:
mimetype = headers["content-type"]
result = {
"data": response.content,
"mime-type": mimetype,
"url": response.url,
}
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise GraphAPIError(response.json())
else:
raise GraphAPIError("Maintype was not text, image, or querystring")
if result and isinstance(result, dict) and result.get("error"):
raise GraphAPIError(result)
return result | python | def request(
self, path, args=None, post_args=None, files=None, method=None
):
if args is None:
args = dict()
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
try:
response = self.session.request(
method or "GET",
FACEBOOK_GRAPH_URL + path,
timeout=self.timeout,
params=args,
data=post_args,
proxies=self.proxies,
files=files,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
headers = response.headers
if "json" in headers["content-type"]:
result = response.json()
elif "image/" in headers["content-type"]:
mimetype = headers["content-type"]
result = {
"data": response.content,
"mime-type": mimetype,
"url": response.url,
}
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise GraphAPIError(response.json())
else:
raise GraphAPIError("Maintype was not text, image, or querystring")
if result and isinstance(result, dict) and result.get("error"):
raise GraphAPIError(result)
return result | [
"def",
"request",
"(",
"self",
",",
"path",
",",
"args",
"=",
"None",
",",
"post_args",
"=",
"None",
",",
"files",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"dict",
"(",
")",
"if",
"post_args... | Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments. | [
"Fetches",
"the",
"given",
"path",
"in",
"the",
"Graph",
"API",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L261-L323 |
241,496 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_access_token_from_code | def get_access_token_from_code(
self, code, redirect_uri, app_id, app_secret
):
"""Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable).
"""
args = {
"code": code,
"redirect_uri": redirect_uri,
"client_id": app_id,
"client_secret": app_secret,
}
return self.request(
"{0}/oauth/access_token".format(self.version), args
) | python | def get_access_token_from_code(
self, code, redirect_uri, app_id, app_secret
):
args = {
"code": code,
"redirect_uri": redirect_uri,
"client_id": app_id,
"client_secret": app_secret,
}
return self.request(
"{0}/oauth/access_token".format(self.version), args
) | [
"def",
"get_access_token_from_code",
"(",
"self",
",",
"code",
",",
"redirect_uri",
",",
"app_id",
",",
"app_secret",
")",
":",
"args",
"=",
"{",
"\"code\"",
":",
"code",
",",
"\"redirect_uri\"",
":",
"redirect_uri",
",",
"\"client_id\"",
":",
"app_id",
",",
... | Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable). | [
"Get",
"an",
"access",
"token",
"from",
"the",
"code",
"returned",
"from",
"an",
"OAuth",
"dialog",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L346-L364 |
241,497 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_auth_url | def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs):
"""Build a URL to create an OAuth dialog."""
url = "{0}{1}/{2}".format(
FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH
)
args = {"client_id": app_id, "redirect_uri": canvas_url}
if perms:
args["scope"] = ",".join(perms)
args.update(kwargs)
return url + urlencode(args) | python | def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs):
url = "{0}{1}/{2}".format(
FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH
)
args = {"client_id": app_id, "redirect_uri": canvas_url}
if perms:
args["scope"] = ",".join(perms)
args.update(kwargs)
return url + urlencode(args) | [
"def",
"get_auth_url",
"(",
"self",
",",
"app_id",
",",
"canvas_url",
",",
"perms",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"{0}{1}/{2}\"",
".",
"format",
"(",
"FACEBOOK_WWW_URL",
",",
"self",
".",
"version",
",",
"FACEBOOK_OAUTH_DIAL... | Build a URL to create an OAuth dialog. | [
"Build",
"a",
"URL",
"to",
"create",
"an",
"OAuth",
"dialog",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L401-L411 |
241,498 | mobolic/facebook-sdk | examples/flask/app/views.py | get_current_user | def get_current_user():
"""Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user.
"""
# Set the user in the session dictionary as a global g.user and bail out
# of this function early.
if session.get("user"):
g.user = session.get("user")
return
# Attempt to get the short term access token for the current user.
result = get_user_from_cookie(
cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET
)
# If there is no result, we assume the user is not logged in.
if result:
# Check to see if this user is already in our database.
user = User.query.filter(User.id == result["uid"]).first()
if not user:
# Not an existing user so get info
graph = GraphAPI(result["access_token"])
profile = graph.get_object("me")
if "link" not in profile:
profile["link"] = ""
# Create the user and insert it into the database
user = User(
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=result["access_token"],
)
db.session.add(user)
elif user.access_token != result["access_token"]:
# If an existing user, update the access token
user.access_token = result["access_token"]
# Add the user to the current session
session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
)
# Commit changes to the database and set the user as a global g.user
db.session.commit()
g.user = session.get("user", None) | python | def get_current_user():
# Set the user in the session dictionary as a global g.user and bail out
# of this function early.
if session.get("user"):
g.user = session.get("user")
return
# Attempt to get the short term access token for the current user.
result = get_user_from_cookie(
cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET
)
# If there is no result, we assume the user is not logged in.
if result:
# Check to see if this user is already in our database.
user = User.query.filter(User.id == result["uid"]).first()
if not user:
# Not an existing user so get info
graph = GraphAPI(result["access_token"])
profile = graph.get_object("me")
if "link" not in profile:
profile["link"] = ""
# Create the user and insert it into the database
user = User(
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=result["access_token"],
)
db.session.add(user)
elif user.access_token != result["access_token"]:
# If an existing user, update the access token
user.access_token = result["access_token"]
# Add the user to the current session
session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
)
# Commit changes to the database and set the user as a global g.user
db.session.commit()
g.user = session.get("user", None) | [
"def",
"get_current_user",
"(",
")",
":",
"# Set the user in the session dictionary as a global g.user and bail out",
"# of this function early.",
"if",
"session",
".",
"get",
"(",
"\"user\"",
")",
":",
"g",
".",
"user",
"=",
"session",
".",
"get",
"(",
"\"user\"",
")... | Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user. | [
"Set",
"g",
".",
"user",
"to",
"the",
"currently",
"logged",
"in",
"user",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/examples/flask/app/views.py#L38-L95 |
241,499 | NetEaseGame/ATX | atx/record/scene_detector.py | SceneDetector.build_tree | def build_tree(self, directory):
'''build scene tree from images'''
confile = os.path.join(directory, 'config.yml')
conf = {}
if os.path.exists(confile):
conf = yaml.load(open(confile).read())
class node(defaultdict):
name = ''
parent = None
tmpl = None
rect = None
mask = None
def __str__(self):
obj = self
names = []
while obj.parent is not None:
names.append(obj.name)
obj = obj.parent
return '-'.join(names[::-1])
def tree():
return node(tree)
root = tree()
for s in os.listdir(directory):
if not s.endswith('.png') or s.endswith('_mask.png'):
continue
obj = root
for i in s[:-4].split('-'):
obj[i].name = i
obj[i].parent = obj
obj = obj[i]
obj.tmpl = cv2.imread(os.path.join(directory, s))
obj.rect = conf.get(s[:-4], {}).get('rect')
maskimg = conf.get(s[:-4], {}).get('mask')
if maskimg is not None:
maskimg = os.path.join(directory, maskimg)
if os.path.exists(maskimg):
obj.mask = cv2.imread(maskimg)
self.tree = root
self.current_scene = []
self.confile = confile
self.conf = conf | python | def build_tree(self, directory):
'''build scene tree from images'''
confile = os.path.join(directory, 'config.yml')
conf = {}
if os.path.exists(confile):
conf = yaml.load(open(confile).read())
class node(defaultdict):
name = ''
parent = None
tmpl = None
rect = None
mask = None
def __str__(self):
obj = self
names = []
while obj.parent is not None:
names.append(obj.name)
obj = obj.parent
return '-'.join(names[::-1])
def tree():
return node(tree)
root = tree()
for s in os.listdir(directory):
if not s.endswith('.png') or s.endswith('_mask.png'):
continue
obj = root
for i in s[:-4].split('-'):
obj[i].name = i
obj[i].parent = obj
obj = obj[i]
obj.tmpl = cv2.imread(os.path.join(directory, s))
obj.rect = conf.get(s[:-4], {}).get('rect')
maskimg = conf.get(s[:-4], {}).get('mask')
if maskimg is not None:
maskimg = os.path.join(directory, maskimg)
if os.path.exists(maskimg):
obj.mask = cv2.imread(maskimg)
self.tree = root
self.current_scene = []
self.confile = confile
self.conf = conf | [
"def",
"build_tree",
"(",
"self",
",",
"directory",
")",
":",
"confile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'config.yml'",
")",
"conf",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"confile",
")",
":",
"conf... | build scene tree from images | [
"build",
"scene",
"tree",
"from",
"images"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/scene_detector.py#L81-L126 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.