repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
globality-corp/microcosm-postgres
microcosm_postgres/temporary/methods.py
upsert_into
def upsert_into(self, table): """ Upsert from a temporarty table into another table. """ return SessionContext.session.execute( insert(table).from_select( self.c, self, ).on_conflict_do_nothing(), ).rowcount
python
def upsert_into(self, table): """ Upsert from a temporarty table into another table. """ return SessionContext.session.execute( insert(table).from_select( self.c, self, ).on_conflict_do_nothing(), ).rowcount
[ "def", "upsert_into", "(", "self", ",", "table", ")", ":", "return", "SessionContext", ".", "session", ".", "execute", "(", "insert", "(", "table", ")", ".", "from_select", "(", "self", ".", "c", ",", "self", ",", ")", ".", "on_conflict_do_nothing", "(",...
Upsert from a temporarty table into another table.
[ "Upsert", "from", "a", "temporarty", "table", "into", "another", "table", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/temporary/methods.py#L36-L46
train
26,500
globality-corp/microcosm-postgres
microcosm_postgres/encryption/providers.py
configure_key_provider
def configure_key_provider(graph, key_ids): """ Configure a key provider. During unit tests, use a static key provider (e.g. without AWS calls). """ if graph.metadata.testing: # use static provider provider = StaticMasterKeyProvider() provider.add_master_keys_from_list(key_ids) return provider # use AWS provider return KMSMasterKeyProvider(key_ids=key_ids)
python
def configure_key_provider(graph, key_ids): """ Configure a key provider. During unit tests, use a static key provider (e.g. without AWS calls). """ if graph.metadata.testing: # use static provider provider = StaticMasterKeyProvider() provider.add_master_keys_from_list(key_ids) return provider # use AWS provider return KMSMasterKeyProvider(key_ids=key_ids)
[ "def", "configure_key_provider", "(", "graph", ",", "key_ids", ")", ":", "if", "graph", ".", "metadata", ".", "testing", ":", "# use static provider", "provider", "=", "StaticMasterKeyProvider", "(", ")", "provider", ".", "add_master_keys_from_list", "(", "key_ids",...
Configure a key provider. During unit tests, use a static key provider (e.g. without AWS calls).
[ "Configure", "a", "key", "provider", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/providers.py#L40-L54
train
26,501
globality-corp/microcosm-postgres
microcosm_postgres/encryption/providers.py
configure_materials_manager
def configure_materials_manager(graph, key_provider): """ Configure a crypto materials manager """ if graph.config.materials_manager.enable_cache: return CachingCryptoMaterialsManager( cache=LocalCryptoMaterialsCache(graph.config.materials_manager.cache_capacity), master_key_provider=key_provider, max_age=graph.config.materials_manager.cache_max_age, max_messages_encrypted=graph.config.materials_manager.cache_max_messages_encrypted, ) return DefaultCryptoMaterialsManager(master_key_provider=key_provider)
python
def configure_materials_manager(graph, key_provider): """ Configure a crypto materials manager """ if graph.config.materials_manager.enable_cache: return CachingCryptoMaterialsManager( cache=LocalCryptoMaterialsCache(graph.config.materials_manager.cache_capacity), master_key_provider=key_provider, max_age=graph.config.materials_manager.cache_max_age, max_messages_encrypted=graph.config.materials_manager.cache_max_messages_encrypted, ) return DefaultCryptoMaterialsManager(master_key_provider=key_provider)
[ "def", "configure_materials_manager", "(", "graph", ",", "key_provider", ")", ":", "if", "graph", ".", "config", ".", "materials_manager", ".", "enable_cache", ":", "return", "CachingCryptoMaterialsManager", "(", "cache", "=", "LocalCryptoMaterialsCache", "(", "graph"...
Configure a crypto materials manager
[ "Configure", "a", "crypto", "materials", "manager" ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/encryption/providers.py#L63-L75
train
26,502
globality-corp/microcosm-postgres
microcosm_postgres/createall.py
main
def main(graph): """ Create and drop databases. """ args = parse_args(graph) if args.drop: drop_all(graph) create_all(graph)
python
def main(graph): """ Create and drop databases. """ args = parse_args(graph) if args.drop: drop_all(graph) create_all(graph)
[ "def", "main", "(", "graph", ")", ":", "args", "=", "parse_args", "(", "graph", ")", "if", "args", ".", "drop", ":", "drop_all", "(", "graph", ")", "create_all", "(", "graph", ")" ]
Create and drop databases.
[ "Create", "and", "drop", "databases", "." ]
43dd793b1fc9b84e4056700f350e79e0df5ff501
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/createall.py#L16-L25
train
26,503
jochym/Elastic
elastic/elastic.py
get_lattice_type
def get_lattice_type(cryst): '''Find the symmetry of the crystal using spglib symmetry finder. Derive name of the space group and its number extracted from the result. Based on the group number identify also the lattice type and the Bravais lattice of the crystal. The lattice type numbers are (the numbering starts from 1): Triclinic (1), Monoclinic (2), Orthorombic (3), Tetragonal (4), Trigonal (5), Hexagonal (6), Cubic (7) :param cryst: ASE Atoms object :returns: tuple (lattice type number (1-7), lattice name, space group name, space group number) ''' # Table of lattice types and correcponding group numbers dividing # the ranges. See get_lattice_type method for precise definition. lattice_types = [ [3, "Triclinic"], [16, "Monoclinic"], [75, "Orthorombic"], [143, "Tetragonal"], [168, "Trigonal"], [195, "Hexagonal"], [231, "Cubic"] ] sg = spg.get_spacegroup(cryst) m = re.match(r'([A-Z].*\b)\s*\(([0-9]*)\)', sg) sg_name = m.group(1) sg_nr = int(m.group(2)) for n, l in enumerate(lattice_types): if sg_nr < l[0]: bravais = l[1] lattype = n+1 break return lattype, bravais, sg_name, sg_nr
python
def get_lattice_type(cryst): '''Find the symmetry of the crystal using spglib symmetry finder. Derive name of the space group and its number extracted from the result. Based on the group number identify also the lattice type and the Bravais lattice of the crystal. The lattice type numbers are (the numbering starts from 1): Triclinic (1), Monoclinic (2), Orthorombic (3), Tetragonal (4), Trigonal (5), Hexagonal (6), Cubic (7) :param cryst: ASE Atoms object :returns: tuple (lattice type number (1-7), lattice name, space group name, space group number) ''' # Table of lattice types and correcponding group numbers dividing # the ranges. See get_lattice_type method for precise definition. lattice_types = [ [3, "Triclinic"], [16, "Monoclinic"], [75, "Orthorombic"], [143, "Tetragonal"], [168, "Trigonal"], [195, "Hexagonal"], [231, "Cubic"] ] sg = spg.get_spacegroup(cryst) m = re.match(r'([A-Z].*\b)\s*\(([0-9]*)\)', sg) sg_name = m.group(1) sg_nr = int(m.group(2)) for n, l in enumerate(lattice_types): if sg_nr < l[0]: bravais = l[1] lattype = n+1 break return lattype, bravais, sg_name, sg_nr
[ "def", "get_lattice_type", "(", "cryst", ")", ":", "# Table of lattice types and correcponding group numbers dividing", "# the ranges. See get_lattice_type method for precise definition.", "lattice_types", "=", "[", "[", "3", ",", "\"Triclinic\"", "]", ",", "[", "16", ",", "\...
Find the symmetry of the crystal using spglib symmetry finder. Derive name of the space group and its number extracted from the result. Based on the group number identify also the lattice type and the Bravais lattice of the crystal. The lattice type numbers are (the numbering starts from 1): Triclinic (1), Monoclinic (2), Orthorombic (3), Tetragonal (4), Trigonal (5), Hexagonal (6), Cubic (7) :param cryst: ASE Atoms object :returns: tuple (lattice type number (1-7), lattice name, space group name, space group number)
[ "Find", "the", "symmetry", "of", "the", "crystal", "using", "spglib", "symmetry", "finder", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L305-L345
train
26,504
jochym/Elastic
elastic/elastic.py
get_bulk_modulus
def get_bulk_modulus(cryst): '''Calculate bulk modulus using the Birch-Murnaghan equation of state. The EOS must be previously calculated by get_BM_EOS routine. The returned bulk modulus is a :math:`B_0` coefficient of the B-M EOS. The units of the result are defined by ASE. To get the result in any particular units (e.g. GPa) you need to divide it by ase.units.<unit name>:: get_bulk_modulus(cryst)/ase.units.GPa :param cryst: ASE Atoms object :returns: float, bulk modulus :math:`B_0` in ASE units. ''' if getattr(cryst, 'bm_eos', None) is None: raise RuntimeError('Missing B-M EOS data.') cryst.bulk_modulus = cryst.bm_eos[1] return cryst.bulk_modulus
python
def get_bulk_modulus(cryst): '''Calculate bulk modulus using the Birch-Murnaghan equation of state. The EOS must be previously calculated by get_BM_EOS routine. The returned bulk modulus is a :math:`B_0` coefficient of the B-M EOS. The units of the result are defined by ASE. To get the result in any particular units (e.g. GPa) you need to divide it by ase.units.<unit name>:: get_bulk_modulus(cryst)/ase.units.GPa :param cryst: ASE Atoms object :returns: float, bulk modulus :math:`B_0` in ASE units. ''' if getattr(cryst, 'bm_eos', None) is None: raise RuntimeError('Missing B-M EOS data.') cryst.bulk_modulus = cryst.bm_eos[1] return cryst.bulk_modulus
[ "def", "get_bulk_modulus", "(", "cryst", ")", ":", "if", "getattr", "(", "cryst", ",", "'bm_eos'", ",", "None", ")", "is", "None", ":", "raise", "RuntimeError", "(", "'Missing B-M EOS data.'", ")", "cryst", ".", "bulk_modulus", "=", "cryst", ".", "bm_eos", ...
Calculate bulk modulus using the Birch-Murnaghan equation of state. The EOS must be previously calculated by get_BM_EOS routine. The returned bulk modulus is a :math:`B_0` coefficient of the B-M EOS. The units of the result are defined by ASE. To get the result in any particular units (e.g. GPa) you need to divide it by ase.units.<unit name>:: get_bulk_modulus(cryst)/ase.units.GPa :param cryst: ASE Atoms object :returns: float, bulk modulus :math:`B_0` in ASE units.
[ "Calculate", "bulk", "modulus", "using", "the", "Birch", "-", "Murnaghan", "equation", "of", "state", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L348-L367
train
26,505
jochym/Elastic
elastic/elastic.py
get_BM_EOS
def get_BM_EOS(cryst, systems): """Calculate Birch-Murnaghan Equation of State for the crystal. The B-M equation of state is defined by: .. math:: P(V)= \\frac{B_0}{B'_0}\\left[ \\left({\\frac{V}{V_0}}\\right)^{-B'_0} - 1 \\right] It's coefficients are estimated using n single-point structures ganerated from the crystal (cryst) by the scan_volumes function between two relative volumes. The BM EOS is fitted to the computed points by least squares method. The returned value is a list of fitted parameters: :math:`V_0, B_0, B_0'` if the fit succeded. If the fitting fails the ``RuntimeError('Calculation failed')`` is raised. The data from the calculation and fit is stored in the bm_eos and pv members of cryst for future reference. You have to provide properly optimized structures in cryst and systems list. :param cryst: Atoms object, basic structure :param systems: A list of calculated structures :returns: tuple of EOS parameters :math:`V_0, B_0, B_0'`. """ pvdat = array([[r.get_volume(), get_pressure(r.get_stress()), norm(r.get_cell()[:, 0]), norm(r.get_cell()[:, 1]), norm(r.get_cell()[:, 2])] for r in systems]).T # Estimate the initial guess assuming b0p=1 # Limiting volumes v1 = min(pvdat[0]) v2 = max(pvdat[0]) # The pressure is falling with the growing volume p2 = min(pvdat[1]) p1 = max(pvdat[1]) b0 = (p1*v1-p2*v2)/(v2-v1) v0 = v1*(p1+b0)/b0 # Initial guess p0 = [v0, b0, 1] # Fitting try : p1, succ = optimize.curve_fit(BMEOS, pvdat[0], pvdat[1], p0) except (ValueError, RuntimeError, optimize.OptimizeWarning) as ex: raise RuntimeError('Calculation failed') cryst.bm_eos = p1 cryst.pv = pvdat return cryst.bm_eos
python
def get_BM_EOS(cryst, systems): """Calculate Birch-Murnaghan Equation of State for the crystal. The B-M equation of state is defined by: .. math:: P(V)= \\frac{B_0}{B'_0}\\left[ \\left({\\frac{V}{V_0}}\\right)^{-B'_0} - 1 \\right] It's coefficients are estimated using n single-point structures ganerated from the crystal (cryst) by the scan_volumes function between two relative volumes. The BM EOS is fitted to the computed points by least squares method. The returned value is a list of fitted parameters: :math:`V_0, B_0, B_0'` if the fit succeded. If the fitting fails the ``RuntimeError('Calculation failed')`` is raised. The data from the calculation and fit is stored in the bm_eos and pv members of cryst for future reference. You have to provide properly optimized structures in cryst and systems list. :param cryst: Atoms object, basic structure :param systems: A list of calculated structures :returns: tuple of EOS parameters :math:`V_0, B_0, B_0'`. """ pvdat = array([[r.get_volume(), get_pressure(r.get_stress()), norm(r.get_cell()[:, 0]), norm(r.get_cell()[:, 1]), norm(r.get_cell()[:, 2])] for r in systems]).T # Estimate the initial guess assuming b0p=1 # Limiting volumes v1 = min(pvdat[0]) v2 = max(pvdat[0]) # The pressure is falling with the growing volume p2 = min(pvdat[1]) p1 = max(pvdat[1]) b0 = (p1*v1-p2*v2)/(v2-v1) v0 = v1*(p1+b0)/b0 # Initial guess p0 = [v0, b0, 1] # Fitting try : p1, succ = optimize.curve_fit(BMEOS, pvdat[0], pvdat[1], p0) except (ValueError, RuntimeError, optimize.OptimizeWarning) as ex: raise RuntimeError('Calculation failed') cryst.bm_eos = p1 cryst.pv = pvdat return cryst.bm_eos
[ "def", "get_BM_EOS", "(", "cryst", ",", "systems", ")", ":", "pvdat", "=", "array", "(", "[", "[", "r", ".", "get_volume", "(", ")", ",", "get_pressure", "(", "r", ".", "get_stress", "(", ")", ")", ",", "norm", "(", "r", ".", "get_cell", "(", ")"...
Calculate Birch-Murnaghan Equation of State for the crystal. The B-M equation of state is defined by: .. math:: P(V)= \\frac{B_0}{B'_0}\\left[ \\left({\\frac{V}{V_0}}\\right)^{-B'_0} - 1 \\right] It's coefficients are estimated using n single-point structures ganerated from the crystal (cryst) by the scan_volumes function between two relative volumes. The BM EOS is fitted to the computed points by least squares method. The returned value is a list of fitted parameters: :math:`V_0, B_0, B_0'` if the fit succeded. If the fitting fails the ``RuntimeError('Calculation failed')`` is raised. The data from the calculation and fit is stored in the bm_eos and pv members of cryst for future reference. You have to provide properly optimized structures in cryst and systems list. :param cryst: Atoms object, basic structure :param systems: A list of calculated structures :returns: tuple of EOS parameters :math:`V_0, B_0, B_0'`.
[ "Calculate", "Birch", "-", "Murnaghan", "Equation", "of", "State", "for", "the", "crystal", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L386-L440
train
26,506
jochym/Elastic
elastic/elastic.py
get_elementary_deformations
def get_elementary_deformations(cryst, n=5, d=2): '''Generate elementary deformations for elastic tensor calculation. The deformations are created based on the symmetry of the crystal and are limited to the non-equivalet axes of the crystal. :param cryst: Atoms object, basic structure :param n: integer, number of deformations per non-equivalent axis :param d: float, size of the maximum deformation in percent and degrees :returns: list of deformed structures ''' # Deformation look-up table # Perhaps the number of deformations for trigonal # system could be reduced to [0,3] but better safe then sorry deform = { "Cubic": [[0, 3], regular], "Hexagonal": [[0, 2, 3, 5], hexagonal], "Trigonal": [[0, 1, 2, 3, 4, 5], trigonal], "Tetragonal": [[0, 2, 3, 5], tetragonal], "Orthorombic": [[0, 1, 2, 3, 4, 5], orthorombic], "Monoclinic": [[0, 1, 2, 3, 4, 5], monoclinic], "Triclinic": [[0, 1, 2, 3, 4, 5], triclinic] } lattyp, brav, sg_name, sg_nr = get_lattice_type(cryst) # Decide which deformations should be used axis, symm = deform[brav] systems = [] for a in axis: if a < 3: # tetragonal deformation for dx in linspace(-d, d, n): systems.append( get_cart_deformed_cell(cryst, axis=a, size=dx)) elif a < 6: # sheer deformation (skip the zero angle) for dx in linspace(d/10.0, d, n): systems.append( get_cart_deformed_cell(cryst, axis=a, size=dx)) return systems
python
def get_elementary_deformations(cryst, n=5, d=2): '''Generate elementary deformations for elastic tensor calculation. The deformations are created based on the symmetry of the crystal and are limited to the non-equivalet axes of the crystal. :param cryst: Atoms object, basic structure :param n: integer, number of deformations per non-equivalent axis :param d: float, size of the maximum deformation in percent and degrees :returns: list of deformed structures ''' # Deformation look-up table # Perhaps the number of deformations for trigonal # system could be reduced to [0,3] but better safe then sorry deform = { "Cubic": [[0, 3], regular], "Hexagonal": [[0, 2, 3, 5], hexagonal], "Trigonal": [[0, 1, 2, 3, 4, 5], trigonal], "Tetragonal": [[0, 2, 3, 5], tetragonal], "Orthorombic": [[0, 1, 2, 3, 4, 5], orthorombic], "Monoclinic": [[0, 1, 2, 3, 4, 5], monoclinic], "Triclinic": [[0, 1, 2, 3, 4, 5], triclinic] } lattyp, brav, sg_name, sg_nr = get_lattice_type(cryst) # Decide which deformations should be used axis, symm = deform[brav] systems = [] for a in axis: if a < 3: # tetragonal deformation for dx in linspace(-d, d, n): systems.append( get_cart_deformed_cell(cryst, axis=a, size=dx)) elif a < 6: # sheer deformation (skip the zero angle) for dx in linspace(d/10.0, d, n): systems.append( get_cart_deformed_cell(cryst, axis=a, size=dx)) return systems
[ "def", "get_elementary_deformations", "(", "cryst", ",", "n", "=", "5", ",", "d", "=", "2", ")", ":", "# Deformation look-up table", "# Perhaps the number of deformations for trigonal", "# system could be reduced to [0,3] but better safe then sorry", "deform", "=", "{", "\"Cu...
Generate elementary deformations for elastic tensor calculation. The deformations are created based on the symmetry of the crystal and are limited to the non-equivalet axes of the crystal. :param cryst: Atoms object, basic structure :param n: integer, number of deformations per non-equivalent axis :param d: float, size of the maximum deformation in percent and degrees :returns: list of deformed structures
[ "Generate", "elementary", "deformations", "for", "elastic", "tensor", "calculation", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L443-L482
train
26,507
jochym/Elastic
elastic/elastic.py
get_cart_deformed_cell
def get_cart_deformed_cell(base_cryst, axis=0, size=1): '''Return the cell deformed along one of the cartesian directions Creates new deformed structure. The deformation is based on the base structure and is performed along single axis. The axis is specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = yz, xz, xy. The size of the deformation is in percent and degrees, respectively. :param base_cryst: structure to be deformed :param axis: direction of deformation :param size: size of the deformation :returns: new, deformed structure ''' cryst = Atoms(base_cryst) uc = base_cryst.get_cell() s = size/100.0 L = diag(ones(3)) if axis < 3: L[axis, axis] += s else: if axis == 3: L[1, 2] += s elif axis == 4: L[0, 2] += s else: L[0, 1] += s uc = dot(uc, L) cryst.set_cell(uc, scale_atoms=True) # print(cryst.get_cell()) # print(uc) return cryst
python
def get_cart_deformed_cell(base_cryst, axis=0, size=1): '''Return the cell deformed along one of the cartesian directions Creates new deformed structure. The deformation is based on the base structure and is performed along single axis. The axis is specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = yz, xz, xy. The size of the deformation is in percent and degrees, respectively. :param base_cryst: structure to be deformed :param axis: direction of deformation :param size: size of the deformation :returns: new, deformed structure ''' cryst = Atoms(base_cryst) uc = base_cryst.get_cell() s = size/100.0 L = diag(ones(3)) if axis < 3: L[axis, axis] += s else: if axis == 3: L[1, 2] += s elif axis == 4: L[0, 2] += s else: L[0, 1] += s uc = dot(uc, L) cryst.set_cell(uc, scale_atoms=True) # print(cryst.get_cell()) # print(uc) return cryst
[ "def", "get_cart_deformed_cell", "(", "base_cryst", ",", "axis", "=", "0", ",", "size", "=", "1", ")", ":", "cryst", "=", "Atoms", "(", "base_cryst", ")", "uc", "=", "base_cryst", ".", "get_cell", "(", ")", "s", "=", "size", "/", "100.0", "L", "=", ...
Return the cell deformed along one of the cartesian directions Creates new deformed structure. The deformation is based on the base structure and is performed along single axis. The axis is specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = yz, xz, xy. The size of the deformation is in percent and degrees, respectively. :param base_cryst: structure to be deformed :param axis: direction of deformation :param size: size of the deformation :returns: new, deformed structure
[ "Return", "the", "cell", "deformed", "along", "one", "of", "the", "cartesian", "directions" ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L669-L700
train
26,508
jochym/Elastic
elastic/elastic.py
get_strain
def get_strain(cryst, refcell=None): '''Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param refcell: reference, undeformed structure :returns: 6-vector of strain tensor in the Voight notation ''' if refcell is None: refcell = cryst du = cryst.get_cell()-refcell.get_cell() m = refcell.get_cell() m = inv(m) u = dot(m, du) u = (u+u.T)/2 return array([u[0, 0], u[1, 1], u[2, 2], u[2, 1], u[2, 0], u[1, 0]])
python
def get_strain(cryst, refcell=None): '''Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param refcell: reference, undeformed structure :returns: 6-vector of strain tensor in the Voight notation ''' if refcell is None: refcell = cryst du = cryst.get_cell()-refcell.get_cell() m = refcell.get_cell() m = inv(m) u = dot(m, du) u = (u+u.T)/2 return array([u[0, 0], u[1, 1], u[2, 2], u[2, 1], u[2, 0], u[1, 0]])
[ "def", "get_strain", "(", "cryst", ",", "refcell", "=", "None", ")", ":", "if", "refcell", "is", "None", ":", "refcell", "=", "cryst", "du", "=", "cryst", ".", "get_cell", "(", ")", "-", "refcell", ".", "get_cell", "(", ")", "m", "=", "refcell", "....
Calculate strain tensor in the Voight notation Computes the strain tensor in the Voight notation as a conventional 6-vector. The calculation is done with respect to the crystal geometry passed in refcell parameter. :param cryst: deformed structure :param refcell: reference, undeformed structure :returns: 6-vector of strain tensor in the Voight notation
[ "Calculate", "strain", "tensor", "in", "the", "Voight", "notation" ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/elastic.py#L703-L722
train
26,509
jochym/Elastic
parcalc/parcalc.py
work_dir
def work_dir(path): ''' Context menager for executing commands in some working directory. Returns to the previous wd when finished. Usage: >>> with work_dir(path): ... subprocess.call('git status') ''' starting_directory = os.getcwd() try: os.chdir(path) yield finally: os.chdir(starting_directory)
python
def work_dir(path): ''' Context menager for executing commands in some working directory. Returns to the previous wd when finished. Usage: >>> with work_dir(path): ... subprocess.call('git status') ''' starting_directory = os.getcwd() try: os.chdir(path) yield finally: os.chdir(starting_directory)
[ "def", "work_dir", "(", "path", ")", ":", "starting_directory", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "path", ")", "yield", "finally", ":", "os", ".", "chdir", "(", "starting_directory", ")" ]
Context menager for executing commands in some working directory. Returns to the previous wd when finished. Usage: >>> with work_dir(path): ... subprocess.call('git status')
[ "Context", "menager", "for", "executing", "commands", "in", "some", "working", "directory", ".", "Returns", "to", "the", "previous", "wd", "when", "finished", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L79-L94
train
26,510
jochym/Elastic
parcalc/parcalc.py
ClusterVasp.prepare_calc_dir
def prepare_calc_dir(self): ''' Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup. ''' with open("vasprun.conf","w") as f: f.write('NODES="nodes=%s:ppn=%d"\n' % (self.nodes, self.ppn)) f.write('BLOCK=%d\n' % (self.block,)) if self.ncl : f.write('NCL=%d\n' % (1,))
python
def prepare_calc_dir(self): ''' Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup. ''' with open("vasprun.conf","w") as f: f.write('NODES="nodes=%s:ppn=%d"\n' % (self.nodes, self.ppn)) f.write('BLOCK=%d\n' % (self.block,)) if self.ncl : f.write('NCL=%d\n' % (1,))
[ "def", "prepare_calc_dir", "(", "self", ")", ":", "with", "open", "(", "\"vasprun.conf\"", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "'NODES=\"nodes=%s:ppn=%d\"\\n'", "%", "(", "self", ".", "nodes", ",", "self", ".", "ppn", ")", ")", "...
Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup.
[ "Prepare", "the", "calculation", "directory", "for", "VASP", "execution", ".", "This", "needs", "to", "be", "re", "-", "implemented", "for", "each", "local", "setup", ".", "The", "following", "code", "reflects", "just", "my", "particular", "setup", "." ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L114-L124
train
26,511
jochym/Elastic
parcalc/parcalc.py
ClusterVasp.calc_finished
def calc_finished(self): ''' Check if the lockfile is in the calculation directory. It is removed by the script at the end regardless of the success of the calculation. This is totally tied to implementation and you need to implement your own scheme! ''' #print_stack(limit=5) if not self.calc_running : #print('Calc running:',self.calc_running) return True else: # The calc is marked as running check if this is still true # We do it by external scripts. You need to write these # scripts for your own system. # See examples/scripts directory for examples. with work_dir(self.working_dir) : o=check_output(['check-job']) #print('Status',o) if o[0] in b'R' : # Still running - we do nothing to preserve the state return False else : # The job is not running maybe it finished maybe crashed # We hope for the best at this point ad pass to the # Standard update function return True
python
def calc_finished(self): ''' Check if the lockfile is in the calculation directory. It is removed by the script at the end regardless of the success of the calculation. This is totally tied to implementation and you need to implement your own scheme! ''' #print_stack(limit=5) if not self.calc_running : #print('Calc running:',self.calc_running) return True else: # The calc is marked as running check if this is still true # We do it by external scripts. You need to write these # scripts for your own system. # See examples/scripts directory for examples. with work_dir(self.working_dir) : o=check_output(['check-job']) #print('Status',o) if o[0] in b'R' : # Still running - we do nothing to preserve the state return False else : # The job is not running maybe it finished maybe crashed # We hope for the best at this point ad pass to the # Standard update function return True
[ "def", "calc_finished", "(", "self", ")", ":", "#print_stack(limit=5)", "if", "not", "self", ".", "calc_running", ":", "#print('Calc running:',self.calc_running)", "return", "True", "else", ":", "# The calc is marked as running check if this is still true", "# We do it by exter...
Check if the lockfile is in the calculation directory. It is removed by the script at the end regardless of the success of the calculation. This is totally tied to implementation and you need to implement your own scheme!
[ "Check", "if", "the", "lockfile", "is", "in", "the", "calculation", "directory", ".", "It", "is", "removed", "by", "the", "script", "at", "the", "end", "regardless", "of", "the", "success", "of", "the", "calculation", ".", "This", "is", "totally", "tied", ...
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L127-L153
train
26,512
jochym/Elastic
parcalc/parcalc.py
RemoteCalculator.run_calculation
def run_calculation(self, atoms=None, properties=['energy'], system_changes=all_changes): ''' Internal calculation executor. We cannot use FileIOCalculator directly since we need to support remote execution. This calculator is different from others. It prepares the directory, launches the remote process and raises the exception to signal that we need to come back for results when the job is finished. ''' self.calc.calculate(self, atoms, properties, system_changes) self.write_input(self.atoms, properties, system_changes) if self.command is None: raise RuntimeError('Please configure Remote calculator!') olddir = os.getcwd() errorcode=0 try: os.chdir(self.directory) output = subprocess.check_output(self.command, shell=True) self.jobid=output.split()[0] self.submited=True #print "Job %s submitted. Waiting for it." % (self.jobid) # Waiting loop. To be removed. except subprocess.CalledProcessError as e: errorcode=e.returncode finally: os.chdir(olddir) if errorcode: raise RuntimeError('%s returned an error: %d' % (self.name, errorcode)) self.read_results()
python
def run_calculation(self, atoms=None, properties=['energy'], system_changes=all_changes): ''' Internal calculation executor. We cannot use FileIOCalculator directly since we need to support remote execution. This calculator is different from others. It prepares the directory, launches the remote process and raises the exception to signal that we need to come back for results when the job is finished. ''' self.calc.calculate(self, atoms, properties, system_changes) self.write_input(self.atoms, properties, system_changes) if self.command is None: raise RuntimeError('Please configure Remote calculator!') olddir = os.getcwd() errorcode=0 try: os.chdir(self.directory) output = subprocess.check_output(self.command, shell=True) self.jobid=output.split()[0] self.submited=True #print "Job %s submitted. Waiting for it." % (self.jobid) # Waiting loop. To be removed. except subprocess.CalledProcessError as e: errorcode=e.returncode finally: os.chdir(olddir) if errorcode: raise RuntimeError('%s returned an error: %d' % (self.name, errorcode)) self.read_results()
[ "def", "run_calculation", "(", "self", ",", "atoms", "=", "None", ",", "properties", "=", "[", "'energy'", "]", ",", "system_changes", "=", "all_changes", ")", ":", "self", ".", "calc", ".", "calculate", "(", "self", ",", "atoms", ",", "properties", ",",...
Internal calculation executor. We cannot use FileIOCalculator directly since we need to support remote execution. This calculator is different from others. It prepares the directory, launches the remote process and raises the exception to signal that we need to come back for results when the job is finished.
[ "Internal", "calculation", "executor", ".", "We", "cannot", "use", "FileIOCalculator", "directly", "since", "we", "need", "to", "support", "remote", "execution", ".", "This", "calculator", "is", "different", "from", "others", ".", "It", "prepares", "the", "direc...
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/parcalc/parcalc.py#L425-L457
train
26,513
jochym/Elastic
elastic/cli/elastic.py
gen
def gen(ctx, num, lo, hi, size, struct): '''Generate deformed structures''' frmt = ctx.parent.params['frmt'] action = ctx.parent.params['action'] cryst = ase.io.read(struct, format=frmt) fn_tmpl = action if frmt == 'vasp': fn_tmpl += '_%03d.POSCAR' kwargs = {'vasp5': True, 'direct': True} elif frmt == 'abinit': fn_tmpl += '_%03d.abinit' kwargs = {} if verbose: from elastic.elastic import get_lattice_type nr, brav, sg, sgn = get_lattice_type(cryst) echo('%s lattice (%s): %s' % (brav, sg, cryst.get_chemical_formula())) if action == 'cij': echo('Generating {:d} deformations of {:.1f}(%/degs.) per axis'.format( num, size)) elif action == 'eos': echo('Generating {:d} deformations from {:.3f} to {:.3f} of V0'.format( num, lo, hi)) if action == 'cij': systems = elastic.get_elementary_deformations(cryst, n=num, d=size) elif action == 'eos': systems = elastic.scan_volumes(cryst, n=num, lo=lo, hi=hi) systems.insert(0, cryst) if verbose: echo('Writing %d deformation files.' % len(systems)) for n, s in enumerate(systems): ase.io.write(fn_tmpl % n, s, format=frmt, **kwargs)
python
def gen(ctx, num, lo, hi, size, struct): '''Generate deformed structures''' frmt = ctx.parent.params['frmt'] action = ctx.parent.params['action'] cryst = ase.io.read(struct, format=frmt) fn_tmpl = action if frmt == 'vasp': fn_tmpl += '_%03d.POSCAR' kwargs = {'vasp5': True, 'direct': True} elif frmt == 'abinit': fn_tmpl += '_%03d.abinit' kwargs = {} if verbose: from elastic.elastic import get_lattice_type nr, brav, sg, sgn = get_lattice_type(cryst) echo('%s lattice (%s): %s' % (brav, sg, cryst.get_chemical_formula())) if action == 'cij': echo('Generating {:d} deformations of {:.1f}(%/degs.) per axis'.format( num, size)) elif action == 'eos': echo('Generating {:d} deformations from {:.3f} to {:.3f} of V0'.format( num, lo, hi)) if action == 'cij': systems = elastic.get_elementary_deformations(cryst, n=num, d=size) elif action == 'eos': systems = elastic.scan_volumes(cryst, n=num, lo=lo, hi=hi) systems.insert(0, cryst) if verbose: echo('Writing %d deformation files.' % len(systems)) for n, s in enumerate(systems): ase.io.write(fn_tmpl % n, s, format=frmt, **kwargs)
[ "def", "gen", "(", "ctx", ",", "num", ",", "lo", ",", "hi", ",", "size", ",", "struct", ")", ":", "frmt", "=", "ctx", ".", "parent", ".", "params", "[", "'frmt'", "]", "action", "=", "ctx", ".", "parent", ".", "params", "[", "'action'", "]", "c...
Generate deformed structures
[ "Generate", "deformed", "structures" ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/cli/elastic.py#L83-L117
train
26,514
jochym/Elastic
elastic/cli/elastic.py
proc
def proc(ctx, files): '''Process calculated structures''' def calc_reader(fn, verb): if verb: echo('Reading: {:<60s}\r'.format(fn), nl=False, err=True) return ase.io.read(fn) action = ctx.parent.params['action'] systems = [calc_reader(calc, verbose) for calc in files] if verbose : echo('', err=True) if action == 'cij': cij = elastic.get_elastic_tensor(systems[0], systems=systems[1:]) msv = cij[1][3].max() eps = 1e-4 if verbose: echo('Cij solution\n'+30*'-') echo(' Solution rank: {:2d}{}'.format( cij[1][2], ' (undetermined)' if cij[1][2] < len(cij[0]) else '')) if cij[1][2] == len(cij[0]): echo(' Square of residuals: {:7.2g}'.format(cij[1][1])) echo(' Relative singular values:') for sv in cij[1][3]/msv: echo('{:7.4f}{}'.format( sv, '* ' if (sv) < eps else ' '), nl=False) echo('\n\nElastic tensor (GPa):') for dsc in elastic.elastic.get_cij_order(systems[0]): echo('{: >7s} '.format(dsc), nl=False) echo('\n'+30*'-') for c, sv in zip(cij[0], cij[1][3]/msv): echo('{:7.2f}{}'.format( c/ase.units.GPa, '* ' if sv < eps else ' '), nl=False) echo() elif action == 'eos': eos = elastic.get_BM_EOS(systems[0], systems=systems[1:]) eos[1] /= ase.units.GPa if verbose: echo('# %7s (A^3) %7s (GPa) %7s' % ("V0", "B0", "B0'")) echo(' %7.2f %7.2f %7.2f' % tuple(eos))
python
def proc(ctx, files): '''Process calculated structures''' def calc_reader(fn, verb): if verb: echo('Reading: {:<60s}\r'.format(fn), nl=False, err=True) return ase.io.read(fn) action = ctx.parent.params['action'] systems = [calc_reader(calc, verbose) for calc in files] if verbose : echo('', err=True) if action == 'cij': cij = elastic.get_elastic_tensor(systems[0], systems=systems[1:]) msv = cij[1][3].max() eps = 1e-4 if verbose: echo('Cij solution\n'+30*'-') echo(' Solution rank: {:2d}{}'.format( cij[1][2], ' (undetermined)' if cij[1][2] < len(cij[0]) else '')) if cij[1][2] == len(cij[0]): echo(' Square of residuals: {:7.2g}'.format(cij[1][1])) echo(' Relative singular values:') for sv in cij[1][3]/msv: echo('{:7.4f}{}'.format( sv, '* ' if (sv) < eps else ' '), nl=False) echo('\n\nElastic tensor (GPa):') for dsc in elastic.elastic.get_cij_order(systems[0]): echo('{: >7s} '.format(dsc), nl=False) echo('\n'+30*'-') for c, sv in zip(cij[0], cij[1][3]/msv): echo('{:7.2f}{}'.format( c/ase.units.GPa, '* ' if sv < eps else ' '), nl=False) echo() elif action == 'eos': eos = elastic.get_BM_EOS(systems[0], systems=systems[1:]) eos[1] /= ase.units.GPa if verbose: echo('# %7s (A^3) %7s (GPa) %7s' % ("V0", "B0", "B0'")) echo(' %7.2f %7.2f %7.2f' % tuple(eos))
[ "def", "proc", "(", "ctx", ",", "files", ")", ":", "def", "calc_reader", "(", "fn", ",", "verb", ")", ":", "if", "verb", ":", "echo", "(", "'Reading: {:<60s}\\r'", ".", "format", "(", "fn", ")", ",", "nl", "=", "False", ",", "err", "=", "True", "...
Process calculated structures
[ "Process", "calculated", "structures" ]
8daae37d0c48aab8dfb1de2839dab02314817f95
https://github.com/jochym/Elastic/blob/8daae37d0c48aab8dfb1de2839dab02314817f95/elastic/cli/elastic.py#L123-L163
train
26,515
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/admin.py
EntryPlaceholderAdmin.save_model
def save_model(self, request, entry, form, change): """ Fill the content field with the interpretation of the placeholder """ context = RequestContext(request) try: content = render_placeholder(entry.content_placeholder, context) entry.content = content or '' except KeyError: # https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61 entry.content = '' super(EntryPlaceholderAdmin, self).save_model( request, entry, form, change)
python
def save_model(self, request, entry, form, change): """ Fill the content field with the interpretation of the placeholder """ context = RequestContext(request) try: content = render_placeholder(entry.content_placeholder, context) entry.content = content or '' except KeyError: # https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61 entry.content = '' super(EntryPlaceholderAdmin, self).save_model( request, entry, form, change)
[ "def", "save_model", "(", "self", ",", "request", ",", "entry", ",", "form", ",", "change", ")", ":", "context", "=", "RequestContext", "(", "request", ")", "try", ":", "content", "=", "render_placeholder", "(", "entry", ".", "content_placeholder", ",", "c...
Fill the content field with the interpretation of the placeholder
[ "Fill", "the", "content", "field", "with", "the", "interpretation", "of", "the", "placeholder" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/admin.py#L22-L35
train
26,516
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
EntryMenu.get_nodes
def get_nodes(self, request): """ Return menu's node for entries """ nodes = [] archives = [] attributes = {'hidden': HIDE_ENTRY_MENU} for entry in Entry.published.all(): year = entry.creation_date.strftime('%Y') month = entry.creation_date.strftime('%m') month_text = format(entry.creation_date, 'b').capitalize() day = entry.creation_date.strftime('%d') key_archive_year = 'year-%s' % year key_archive_month = 'month-%s-%s' % (year, month) key_archive_day = 'day-%s-%s-%s' % (year, month, day) if key_archive_year not in archives: nodes.append(NavigationNode( year, reverse('zinnia:entry_archive_year', args=[year]), key_archive_year, attr=attributes)) archives.append(key_archive_year) if key_archive_month not in archives: nodes.append(NavigationNode( month_text, reverse('zinnia:entry_archive_month', args=[year, month]), key_archive_month, key_archive_year, attr=attributes)) archives.append(key_archive_month) if key_archive_day not in archives: nodes.append(NavigationNode( day, reverse('zinnia:entry_archive_day', args=[year, month, day]), key_archive_day, key_archive_month, attr=attributes)) archives.append(key_archive_day) nodes.append(NavigationNode(entry.title, entry.get_absolute_url(), entry.pk, key_archive_day)) return nodes
python
def get_nodes(self, request): """ Return menu's node for entries """ nodes = [] archives = [] attributes = {'hidden': HIDE_ENTRY_MENU} for entry in Entry.published.all(): year = entry.creation_date.strftime('%Y') month = entry.creation_date.strftime('%m') month_text = format(entry.creation_date, 'b').capitalize() day = entry.creation_date.strftime('%d') key_archive_year = 'year-%s' % year key_archive_month = 'month-%s-%s' % (year, month) key_archive_day = 'day-%s-%s-%s' % (year, month, day) if key_archive_year not in archives: nodes.append(NavigationNode( year, reverse('zinnia:entry_archive_year', args=[year]), key_archive_year, attr=attributes)) archives.append(key_archive_year) if key_archive_month not in archives: nodes.append(NavigationNode( month_text, reverse('zinnia:entry_archive_month', args=[year, month]), key_archive_month, key_archive_year, attr=attributes)) archives.append(key_archive_month) if key_archive_day not in archives: nodes.append(NavigationNode( day, reverse('zinnia:entry_archive_day', args=[year, month, day]), key_archive_day, key_archive_month, attr=attributes)) archives.append(key_archive_day) nodes.append(NavigationNode(entry.title, entry.get_absolute_url(), entry.pk, key_archive_day)) return nodes
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "archives", "=", "[", "]", "attributes", "=", "{", "'hidden'", ":", "HIDE_ENTRY_MENU", "}", "for", "entry", "in", "Entry", ".", "published", ".", "all", "(", ")", ":",...
Return menu's node for entries
[ "Return", "menu", "s", "node", "for", "entries" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L26-L67
train
26,517
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
CategoryMenu.get_nodes
def get_nodes(self, request): """ Return menu's node for categories """ nodes = [] nodes.append(NavigationNode(_('Categories'), reverse('zinnia:category_list'), 'categories')) for category in Category.objects.all(): nodes.append(NavigationNode(category.title, category.get_absolute_url(), category.pk, 'categories')) return nodes
python
def get_nodes(self, request): """ Return menu's node for categories """ nodes = [] nodes.append(NavigationNode(_('Categories'), reverse('zinnia:category_list'), 'categories')) for category in Category.objects.all(): nodes.append(NavigationNode(category.title, category.get_absolute_url(), category.pk, 'categories')) return nodes
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "nodes", ".", "append", "(", "NavigationNode", "(", "_", "(", "'Categories'", ")", ",", "reverse", "(", "'zinnia:category_list'", ")", ",", "'categories'", ")", ")", "for"...
Return menu's node for categories
[ "Return", "menu", "s", "node", "for", "categories" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L76-L88
train
26,518
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
AuthorMenu.get_nodes
def get_nodes(self, request): """ Return menu's node for authors """ nodes = [] nodes.append(NavigationNode(_('Authors'), reverse('zinnia:author_list'), 'authors')) for author in Author.published.all(): nodes.append(NavigationNode(author.__str__(), author.get_absolute_url(), author.pk, 'authors')) return nodes
python
def get_nodes(self, request): """ Return menu's node for authors """ nodes = [] nodes.append(NavigationNode(_('Authors'), reverse('zinnia:author_list'), 'authors')) for author in Author.published.all(): nodes.append(NavigationNode(author.__str__(), author.get_absolute_url(), author.pk, 'authors')) return nodes
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "nodes", ".", "append", "(", "NavigationNode", "(", "_", "(", "'Authors'", ")", ",", "reverse", "(", "'zinnia:author_list'", ")", ",", "'authors'", ")", ")", "for", "aut...
Return menu's node for authors
[ "Return", "menu", "s", "node", "for", "authors" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L97-L109
train
26,519
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
TagMenu.get_nodes
def get_nodes(self, request): """ Return menu's node for tags """ nodes = [] nodes.append(NavigationNode(_('Tags'), reverse('zinnia:tag_list'), 'tags')) for tag in tags_published(): nodes.append(NavigationNode(tag.name, reverse('zinnia:tag_detail', args=[tag.name]), tag.pk, 'tags')) return nodes
python
def get_nodes(self, request): """ Return menu's node for tags """ nodes = [] nodes.append(NavigationNode(_('Tags'), reverse('zinnia:tag_list'), 'tags')) for tag in tags_published(): nodes.append(NavigationNode(tag.name, reverse('zinnia:tag_detail', args=[tag.name]), tag.pk, 'tags')) return nodes
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "nodes", ".", "append", "(", "NavigationNode", "(", "_", "(", "'Tags'", ")", ",", "reverse", "(", "'zinnia:tag_list'", ")", ",", "'tags'", ")", ")", "for", "tag", "in"...
Return menu's node for tags
[ "Return", "menu", "s", "node", "for", "tags" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L118-L130
train
26,520
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/menu.py
EntryModifier.modify
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): """ Modify nodes of a menu """ if breadcrumb: return nodes for node in nodes: if node.attr.get('hidden'): node.visible = False return nodes
python
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): """ Modify nodes of a menu """ if breadcrumb: return nodes for node in nodes: if node.attr.get('hidden'): node.visible = False return nodes
[ "def", "modify", "(", "self", ",", "request", ",", "nodes", ",", "namespace", ",", "root_id", ",", "post_cut", ",", "breadcrumb", ")", ":", "if", "breadcrumb", ":", "return", "nodes", "for", "node", "in", "nodes", ":", "if", "node", ".", "attr", ".", ...
Modify nodes of a menu
[ "Modify", "nodes", "of", "a", "menu" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/menu.py#L140-L149
train
26,521
django-blog-zinnia/cmsplugin-zinnia
cmsplugin_zinnia/placeholder.py
PlaceholderEntry.acquire_context
def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None request = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if not request and 'request' in args: request = alocals['request'] if 'context' in args: return alocals['context'] finally: del frame return RequestContext(request)
python
def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None request = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if not request and 'request' in args: request = alocals['request'] if 'context' in args: return alocals['context'] finally: del frame return RequestContext(request)
[ "def", "acquire_context", "(", "self", ")", ":", "frame", "=", "None", "request", "=", "None", "try", ":", "for", "f", "in", "inspect", ".", "stack", "(", ")", "[", "1", ":", "]", ":", "frame", "=", "f", "[", "0", "]", "args", ",", "varargs", "...
Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome !
[ "Inspect", "the", "stack", "to", "acquire", "the", "current", "context", "used", "to", "render", "the", "placeholder", ".", "I", "m", "really", "sorry", "for", "this", "but", "if", "you", "have", "a", "better", "way", "you", "are", "welcome", "!" ]
7613c0d9ae29affe9ab97527e4b6d5bef124afdc
https://github.com/django-blog-zinnia/cmsplugin-zinnia/blob/7613c0d9ae29affe9ab97527e4b6d5bef124afdc/cmsplugin_zinnia/placeholder.py#L20-L40
train
26,522
duointeractive/sea-cucumber
seacucumber/util.py
get_boto_ses_connection
def get_boto_ses_connection(): """ Shortcut for instantiating and returning a boto SESConnection object. :rtype: boto.ses.SESConnection :returns: A boto SESConnection object, from which email sending is done. """ access_key_id = getattr( settings, 'CUCUMBER_SES_ACCESS_KEY_ID', getattr(settings, 'AWS_ACCESS_KEY_ID', None)) access_key = getattr( settings, 'CUCUMBER_SES_SECRET_ACCESS_KEY', getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)) region_name = getattr( settings, 'CUCUMBER_SES_REGION_NAME', getattr(settings, 'AWS_SES_REGION_NAME', None)) if region_name != None: return boto.ses.connect_to_region( region_name, aws_access_key_id=access_key_id, aws_secret_access_key=access_key, ) else: return boto.connect_ses( aws_access_key_id=access_key_id, aws_secret_access_key=access_key, )
python
def get_boto_ses_connection(): """ Shortcut for instantiating and returning a boto SESConnection object. :rtype: boto.ses.SESConnection :returns: A boto SESConnection object, from which email sending is done. """ access_key_id = getattr( settings, 'CUCUMBER_SES_ACCESS_KEY_ID', getattr(settings, 'AWS_ACCESS_KEY_ID', None)) access_key = getattr( settings, 'CUCUMBER_SES_SECRET_ACCESS_KEY', getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)) region_name = getattr( settings, 'CUCUMBER_SES_REGION_NAME', getattr(settings, 'AWS_SES_REGION_NAME', None)) if region_name != None: return boto.ses.connect_to_region( region_name, aws_access_key_id=access_key_id, aws_secret_access_key=access_key, ) else: return boto.connect_ses( aws_access_key_id=access_key_id, aws_secret_access_key=access_key, )
[ "def", "get_boto_ses_connection", "(", ")", ":", "access_key_id", "=", "getattr", "(", "settings", ",", "'CUCUMBER_SES_ACCESS_KEY_ID'", ",", "getattr", "(", "settings", ",", "'AWS_ACCESS_KEY_ID'", ",", "None", ")", ")", "access_key", "=", "getattr", "(", "settings...
Shortcut for instantiating and returning a boto SESConnection object. :rtype: boto.ses.SESConnection :returns: A boto SESConnection object, from which email sending is done.
[ "Shortcut", "for", "instantiating", "and", "returning", "a", "boto", "SESConnection", "object", "." ]
069637e2cbab561116e23b6723cfc30e779fce03
https://github.com/duointeractive/sea-cucumber/blob/069637e2cbab561116e23b6723cfc30e779fce03/seacucumber/util.py#L21-L49
train
26,523
duointeractive/sea-cucumber
seacucumber/tasks.py
SendEmailTask.run
def run(self, from_email, recipients, message): """ This does the dirty work. Connects to Amazon SES via boto and fires off the message. :param str from_email: The email address the message will show as originating from. :param list recipients: A list of email addresses to send the message to. :param str message: The body of the message. """ self._open_ses_conn() try: # We use the send_raw_email func here because the Django # EmailMessage object we got these values from constructs all of # the headers and such. self.connection.send_raw_email( source=from_email, destinations=recipients, raw_message=dkim_sign(message), ) except SESAddressBlacklistedError, exc: # Blacklisted users are those which delivery failed for in the # last 24 hours. They'll eventually be automatically removed from # the blacklist, but for now, this address is marked as # undeliverable to. logger.warning( 'Attempted to email a blacklisted user: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESDomainEndsWithDotError, exc: # Domains ending in a dot are simply invalid. logger.warning( 'Invalid recipient, ending in dot: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESLocalAddressCharacterError, exc: # Invalid character, usually in the sender "name". logger.warning( 'Local address contains control or whitespace: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESIllegalAddressError, exc: # A clearly mal-formed address. logger.warning( 'Illegal address: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except Exception, exc: # Something else happened that we haven't explicitly forbade # retry attempts for. #noinspection PyUnresolvedReferences logger.error( 'Something went wrong; retrying: %s' % recipients, exc_info=exc, extra={'trace': True} ) self.retry(exc=exc) else: logger.info('An email has been successfully sent: %s' % recipients) # We shouldn't ever block long enough to see this, but here it is # just in case (for debugging?). return True
python
def run(self, from_email, recipients, message): """ This does the dirty work. Connects to Amazon SES via boto and fires off the message. :param str from_email: The email address the message will show as originating from. :param list recipients: A list of email addresses to send the message to. :param str message: The body of the message. """ self._open_ses_conn() try: # We use the send_raw_email func here because the Django # EmailMessage object we got these values from constructs all of # the headers and such. self.connection.send_raw_email( source=from_email, destinations=recipients, raw_message=dkim_sign(message), ) except SESAddressBlacklistedError, exc: # Blacklisted users are those which delivery failed for in the # last 24 hours. They'll eventually be automatically removed from # the blacklist, but for now, this address is marked as # undeliverable to. logger.warning( 'Attempted to email a blacklisted user: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESDomainEndsWithDotError, exc: # Domains ending in a dot are simply invalid. logger.warning( 'Invalid recipient, ending in dot: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESLocalAddressCharacterError, exc: # Invalid character, usually in the sender "name". logger.warning( 'Local address contains control or whitespace: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESIllegalAddressError, exc: # A clearly mal-formed address. logger.warning( 'Illegal address: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except Exception, exc: # Something else happened that we haven't explicitly forbade # retry attempts for. #noinspection PyUnresolvedReferences logger.error( 'Something went wrong; retrying: %s' % recipients, exc_info=exc, extra={'trace': True} ) self.retry(exc=exc) else: logger.info('An email has been successfully sent: %s' % recipients) # We shouldn't ever block long enough to see this, but here it is # just in case (for debugging?). return True
[ "def", "run", "(", "self", ",", "from_email", ",", "recipients", ",", "message", ")", ":", "self", ".", "_open_ses_conn", "(", ")", "try", ":", "# We use the send_raw_email func here because the Django", "# EmailMessage object we got these values from constructs all of", "#...
This does the dirty work. Connects to Amazon SES via boto and fires off the message. :param str from_email: The email address the message will show as originating from. :param list recipients: A list of email addresses to send the message to. :param str message: The body of the message.
[ "This", "does", "the", "dirty", "work", ".", "Connects", "to", "Amazon", "SES", "via", "boto", "and", "fires", "off", "the", "message", "." ]
069637e2cbab561116e23b6723cfc30e779fce03
https://github.com/duointeractive/sea-cucumber/blob/069637e2cbab561116e23b6723cfc30e779fce03/seacucumber/tasks.py#L28-L99
train
26,524
duointeractive/sea-cucumber
seacucumber/management/commands/ses_usage.py
Command.handle
def handle(self, *args, **options): """ Renders the output by piecing together a few methods that do the dirty work. """ # AWS SES connection, which can be re-used for each query needed. conn = get_boto_ses_connection() self._print_quota(conn) self._print_daily_stats(conn)
python
def handle(self, *args, **options): """ Renders the output by piecing together a few methods that do the dirty work. """ # AWS SES connection, which can be re-used for each query needed. conn = get_boto_ses_connection() self._print_quota(conn) self._print_daily_stats(conn)
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# AWS SES connection, which can be re-used for each query needed.", "conn", "=", "get_boto_ses_connection", "(", ")", "self", ".", "_print_quota", "(", "conn", ")", "self", ".", ...
Renders the output by piecing together a few methods that do the dirty work.
[ "Renders", "the", "output", "by", "piecing", "together", "a", "few", "methods", "that", "do", "the", "dirty", "work", "." ]
069637e2cbab561116e23b6723cfc30e779fce03
https://github.com/duointeractive/sea-cucumber/blob/069637e2cbab561116e23b6723cfc30e779fce03/seacucumber/management/commands/ses_usage.py#L14-L22
train
26,525
duointeractive/sea-cucumber
seacucumber/management/commands/ses_usage.py
Command._print_quota
def _print_quota(self, conn): """ Prints some basic quota statistics. """ quota = conn.get_send_quota() quota = quota['GetSendQuotaResponse']['GetSendQuotaResult'] print "--- SES Quota ---" print " 24 Hour Quota: %s" % quota['Max24HourSend'] print " Sent (Last 24 hours): %s" % quota['SentLast24Hours'] print " Max sending rate: %s/sec" % quota['MaxSendRate']
python
def _print_quota(self, conn): """ Prints some basic quota statistics. """ quota = conn.get_send_quota() quota = quota['GetSendQuotaResponse']['GetSendQuotaResult'] print "--- SES Quota ---" print " 24 Hour Quota: %s" % quota['Max24HourSend'] print " Sent (Last 24 hours): %s" % quota['SentLast24Hours'] print " Max sending rate: %s/sec" % quota['MaxSendRate']
[ "def", "_print_quota", "(", "self", ",", "conn", ")", ":", "quota", "=", "conn", ".", "get_send_quota", "(", ")", "quota", "=", "quota", "[", "'GetSendQuotaResponse'", "]", "[", "'GetSendQuotaResult'", "]", "print", "\"--- SES Quota ---\"", "print", "\" 24 Hour...
Prints some basic quota statistics.
[ "Prints", "some", "basic", "quota", "statistics", "." ]
069637e2cbab561116e23b6723cfc30e779fce03
https://github.com/duointeractive/sea-cucumber/blob/069637e2cbab561116e23b6723cfc30e779fce03/seacucumber/management/commands/ses_usage.py#L24-L34
train
26,526
dwavesystems/dwave-tabu
tabu/sampler.py
TabuSampler.sample
def sample(self, bqm, init_solution=None, tenure=None, scale_factor=1, timeout=20, num_reads=1): """Run a tabu search on a given binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): The binary quadratic model (BQM) to be sampled. init_solution (:obj:`~dimod.SampleSet`, optional): Single sample that sets an initial state for all the problem variables. Default is a random initial state. tenure (int, optional): Tabu tenure, which is the length of the tabu list, or number of recently explored solutions kept in memory. Default is a quarter of the number of problem variables up to a maximum value of 20. scale_factor (number, optional): Scaling factor for linear and quadratic biases in the BQM. Internally, the BQM is converted to a QUBO matrix, and elements are stored as long ints using ``internal_q = long int (q * scale_factor)``. timeout (int, optional): Total running time in milliseconds. num_reads (int, optional): Number of reads. Each run of the tabu algorithm generates a sample. Returns: :obj:`~dimod.SampleSet`: A `dimod` :obj:`.~dimod.SampleSet` object. Examples: This example provides samples for a two-variable QUBO model. >>> from tabu import TabuSampler >>> import dimod >>> sampler = TabuSampler() >>> Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} >>> bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=0.0) >>> samples = sampler.sample(bqm) >>> samples.record[0].energy -1.0 """ # input checking and defaults calculation # TODO: one "read" per sample in init_solution sampleset if init_solution is not None: if not isinstance(init_solution, dimod.SampleSet): raise TypeError("'init_solution' should be a 'dimod.SampleSet' instance") if len(init_solution.record) < 1: raise ValueError("'init_solution' should contain at least one sample") if len(init_solution.record[0].sample) != len(bqm): raise ValueError("'init_solution' sample dimension different from BQM") init_sample = self._bqm_sample_to_tabu_sample( init_solution.change_vartype(dimod.BINARY, inplace=False).record[0].sample, bqm.binary) else: init_sample = None if not bqm: return dimod.SampleSet.from_samples([], energy=0, vartype=bqm.vartype) if tenure is None: tenure = max(min(20, len(bqm) // 4), 0) if not isinstance(tenure, int): raise TypeError("'tenure' should be an integer in range [0, num_vars - 1]") if not 0 <= tenure < len(bqm): raise ValueError("'tenure' should be an integer in range [0, num_vars - 1]") if not isinstance(num_reads, int): raise TypeError("'num_reads' should be a positive integer") if num_reads < 1: raise ValueError("'num_reads' should be a positive integer") qubo = self._bqm_to_tabu_qubo(bqm.binary) # run Tabu search samples = [] energies = [] for _ in range(num_reads): if init_sample is None: init_sample = self._bqm_sample_to_tabu_sample(self._random_sample(bqm.binary), bqm.binary) r = TabuSearch(qubo, init_sample, tenure, scale_factor, timeout) sample = self._tabu_sample_to_bqm_sample(list(r.bestSolution()), bqm.binary) energy = bqm.binary.energy(sample) samples.append(sample) energies.append(energy) response = dimod.SampleSet.from_samples( samples, energy=energies, vartype=dimod.BINARY) response.change_vartype(bqm.vartype, inplace=True) return response
python
def sample(self, bqm, init_solution=None, tenure=None, scale_factor=1, timeout=20, num_reads=1): """Run a tabu search on a given binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): The binary quadratic model (BQM) to be sampled. init_solution (:obj:`~dimod.SampleSet`, optional): Single sample that sets an initial state for all the problem variables. Default is a random initial state. tenure (int, optional): Tabu tenure, which is the length of the tabu list, or number of recently explored solutions kept in memory. Default is a quarter of the number of problem variables up to a maximum value of 20. scale_factor (number, optional): Scaling factor for linear and quadratic biases in the BQM. Internally, the BQM is converted to a QUBO matrix, and elements are stored as long ints using ``internal_q = long int (q * scale_factor)``. timeout (int, optional): Total running time in milliseconds. num_reads (int, optional): Number of reads. Each run of the tabu algorithm generates a sample. Returns: :obj:`~dimod.SampleSet`: A `dimod` :obj:`.~dimod.SampleSet` object. Examples: This example provides samples for a two-variable QUBO model. >>> from tabu import TabuSampler >>> import dimod >>> sampler = TabuSampler() >>> Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} >>> bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=0.0) >>> samples = sampler.sample(bqm) >>> samples.record[0].energy -1.0 """ # input checking and defaults calculation # TODO: one "read" per sample in init_solution sampleset if init_solution is not None: if not isinstance(init_solution, dimod.SampleSet): raise TypeError("'init_solution' should be a 'dimod.SampleSet' instance") if len(init_solution.record) < 1: raise ValueError("'init_solution' should contain at least one sample") if len(init_solution.record[0].sample) != len(bqm): raise ValueError("'init_solution' sample dimension different from BQM") init_sample = self._bqm_sample_to_tabu_sample( init_solution.change_vartype(dimod.BINARY, inplace=False).record[0].sample, bqm.binary) else: init_sample = None if not bqm: return dimod.SampleSet.from_samples([], energy=0, vartype=bqm.vartype) if tenure is None: tenure = max(min(20, len(bqm) // 4), 0) if not isinstance(tenure, int): raise TypeError("'tenure' should be an integer in range [0, num_vars - 1]") if not 0 <= tenure < len(bqm): raise ValueError("'tenure' should be an integer in range [0, num_vars - 1]") if not isinstance(num_reads, int): raise TypeError("'num_reads' should be a positive integer") if num_reads < 1: raise ValueError("'num_reads' should be a positive integer") qubo = self._bqm_to_tabu_qubo(bqm.binary) # run Tabu search samples = [] energies = [] for _ in range(num_reads): if init_sample is None: init_sample = self._bqm_sample_to_tabu_sample(self._random_sample(bqm.binary), bqm.binary) r = TabuSearch(qubo, init_sample, tenure, scale_factor, timeout) sample = self._tabu_sample_to_bqm_sample(list(r.bestSolution()), bqm.binary) energy = bqm.binary.energy(sample) samples.append(sample) energies.append(energy) response = dimod.SampleSet.from_samples( samples, energy=energies, vartype=dimod.BINARY) response.change_vartype(bqm.vartype, inplace=True) return response
[ "def", "sample", "(", "self", ",", "bqm", ",", "init_solution", "=", "None", ",", "tenure", "=", "None", ",", "scale_factor", "=", "1", ",", "timeout", "=", "20", ",", "num_reads", "=", "1", ")", ":", "# input checking and defaults calculation", "# TODO: one...
Run a tabu search on a given binary quadratic model. Args: bqm (:obj:`~dimod.BinaryQuadraticModel`): The binary quadratic model (BQM) to be sampled. init_solution (:obj:`~dimod.SampleSet`, optional): Single sample that sets an initial state for all the problem variables. Default is a random initial state. tenure (int, optional): Tabu tenure, which is the length of the tabu list, or number of recently explored solutions kept in memory. Default is a quarter of the number of problem variables up to a maximum value of 20. scale_factor (number, optional): Scaling factor for linear and quadratic biases in the BQM. Internally, the BQM is converted to a QUBO matrix, and elements are stored as long ints using ``internal_q = long int (q * scale_factor)``. timeout (int, optional): Total running time in milliseconds. num_reads (int, optional): Number of reads. Each run of the tabu algorithm generates a sample. Returns: :obj:`~dimod.SampleSet`: A `dimod` :obj:`.~dimod.SampleSet` object. Examples: This example provides samples for a two-variable QUBO model. >>> from tabu import TabuSampler >>> import dimod >>> sampler = TabuSampler() >>> Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2} >>> bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=0.0) >>> samples = sampler.sample(bqm) >>> samples.record[0].energy -1.0
[ "Run", "a", "tabu", "search", "on", "a", "given", "binary", "quadratic", "model", "." ]
3397479343426a1e20ebf5b90593043904433eea
https://github.com/dwavesystems/dwave-tabu/blob/3397479343426a1e20ebf5b90593043904433eea/tabu/sampler.py#L53-L139
train
26,527
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.upload_from_url
def upload_from_url(self, url): """ Upload a GIF from a URL. """ self.check_token() params = {'fetchUrl': url} r = requests.get(FETCH_URL_ENDPOINT, params=params) if r.status_code != 200: raise GfycatClientError('Error fetching the URL', r.status_code) response = r.json() if 'error' in response: raise GfycatClientError(response['error']) return response
python
def upload_from_url(self, url): """ Upload a GIF from a URL. """ self.check_token() params = {'fetchUrl': url} r = requests.get(FETCH_URL_ENDPOINT, params=params) if r.status_code != 200: raise GfycatClientError('Error fetching the URL', r.status_code) response = r.json() if 'error' in response: raise GfycatClientError(response['error']) return response
[ "def", "upload_from_url", "(", "self", ",", "url", ")", ":", "self", ".", "check_token", "(", ")", "params", "=", "{", "'fetchUrl'", ":", "url", "}", "r", "=", "requests", ".", "get", "(", "FETCH_URL_ENDPOINT", ",", "params", "=", "params", ")", "if", ...
Upload a GIF from a URL.
[ "Upload", "a", "GIF", "from", "a", "URL", "." ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L23-L39
train
26,528
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.upload_from_file
def upload_from_file(self, filename): """ Upload a local file to Gfycat """ key = str(uuid.uuid4())[:8] form = [('key', key), ('acl', ACL), ('AWSAccessKeyId', AWS_ACCESS_KEY_ID), ('success_action_status', SUCCESS_ACTION_STATUS), ('signature', SIGNATURE), ('Content-Type', CONTENT_TYPE), ('policy', POLICY)] data = dict(form) files = {'file': open(filename, 'rb')} r = requests.post(FILE_UPLOAD_ENDPOINT, data=data, files=files) if r.status_code != 200: raise GfycatClientError('Error uploading the GIF', r.status_code) info = self.uploaded_file_info(key) while 'timeout' in info.get('error', '').lower(): time.sleep(2) info = self.uploaded_file_info(key) if 'error' in info: raise GfycatClientError(info['error']) return info
python
def upload_from_file(self, filename): """ Upload a local file to Gfycat """ key = str(uuid.uuid4())[:8] form = [('key', key), ('acl', ACL), ('AWSAccessKeyId', AWS_ACCESS_KEY_ID), ('success_action_status', SUCCESS_ACTION_STATUS), ('signature', SIGNATURE), ('Content-Type', CONTENT_TYPE), ('policy', POLICY)] data = dict(form) files = {'file': open(filename, 'rb')} r = requests.post(FILE_UPLOAD_ENDPOINT, data=data, files=files) if r.status_code != 200: raise GfycatClientError('Error uploading the GIF', r.status_code) info = self.uploaded_file_info(key) while 'timeout' in info.get('error', '').lower(): time.sleep(2) info = self.uploaded_file_info(key) if 'error' in info: raise GfycatClientError(info['error']) return info
[ "def", "upload_from_file", "(", "self", ",", "filename", ")", ":", "key", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "[", ":", "8", "]", "form", "=", "[", "(", "'key'", ",", "key", ")", ",", "(", "'acl'", ",", "ACL", ")", ",", "(",...
Upload a local file to Gfycat
[ "Upload", "a", "local", "file", "to", "Gfycat" ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L41-L69
train
26,529
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.uploaded_file_info
def uploaded_file_info(self, key): """ Get information about an uploaded GIF. """ r = requests.get(FILE_UPLOAD_STATUS_ENDPOINT + key) if r.status_code != 200: raise GfycatClientError('Unable to check the status', r.status_code) return r.json()
python
def uploaded_file_info(self, key): """ Get information about an uploaded GIF. """ r = requests.get(FILE_UPLOAD_STATUS_ENDPOINT + key) if r.status_code != 200: raise GfycatClientError('Unable to check the status', r.status_code) return r.json()
[ "def", "uploaded_file_info", "(", "self", ",", "key", ")", ":", "r", "=", "requests", ".", "get", "(", "FILE_UPLOAD_STATUS_ENDPOINT", "+", "key", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "GfycatClientError", "(", "'Unable to check the sta...
Get information about an uploaded GIF.
[ "Get", "information", "about", "an", "uploaded", "GIF", "." ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L71-L80
train
26,530
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.query_gfy
def query_gfy(self, gfyname): """ Query a gfy name for URLs and more information. """ self.check_token() r = requests.get(QUERY_ENDPOINT + gfyname, headers=self.headers) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientError('Bad response from Gfycat', r.status_code) elif ERROR_KEY in response: raise GfycatClientError(response[ERROR_KEY], r.status_code) return response
python
def query_gfy(self, gfyname): """ Query a gfy name for URLs and more information. """ self.check_token() r = requests.get(QUERY_ENDPOINT + gfyname, headers=self.headers) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientError('Bad response from Gfycat', r.status_code) elif ERROR_KEY in response: raise GfycatClientError(response[ERROR_KEY], r.status_code) return response
[ "def", "query_gfy", "(", "self", ",", "gfyname", ")", ":", "self", ".", "check_token", "(", ")", "r", "=", "requests", ".", "get", "(", "QUERY_ENDPOINT", "+", "gfyname", ",", "headers", "=", "self", ".", "headers", ")", "response", "=", "r", ".", "js...
Query a gfy name for URLs and more information.
[ "Query", "a", "gfy", "name", "for", "URLs", "and", "more", "information", "." ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L82-L98
train
26,531
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.check_link
def check_link(self, link): """ Check if a link has been already converted. """ r = requests.get(CHECK_LINK_ENDPOINT + link) if r.status_code != 200: raise GfycatClientError('Unable to check the link', r.status_code) return r.json()
python
def check_link(self, link): """ Check if a link has been already converted. """ r = requests.get(CHECK_LINK_ENDPOINT + link) if r.status_code != 200: raise GfycatClientError('Unable to check the link', r.status_code) return r.json()
[ "def", "check_link", "(", "self", ",", "link", ")", ":", "r", "=", "requests", ".", "get", "(", "CHECK_LINK_ENDPOINT", "+", "link", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "GfycatClientError", "(", "'Unable to check the link'", ",", ...
Check if a link has been already converted.
[ "Check", "if", "a", "link", "has", "been", "already", "converted", "." ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L100-L109
train
26,532
ankeshanand/py-gfycat
gfycat/client.py
GfycatClient.get_token
def get_token(self): """ Gets the authorization token """ payload = {'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret} r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={'content-type': 'application/json'}) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientError('Error fetching the OAUTH URL', r.status_code) elif ERROR_KEY in response: raise GfycatClientError(response[ERROR_KEY], r.status_code) self.token_type = response['token_type'] self.access_token = response['access_token'] self.expires_in = response['expires_in'] self.expires_at = time.time() + self.expires_in - 5 self.headers = {'content-type': 'application/json','Authorization': self.token_type + ' ' + self.access_token}
python
def get_token(self): """ Gets the authorization token """ payload = {'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret} r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={'content-type': 'application/json'}) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientError('Error fetching the OAUTH URL', r.status_code) elif ERROR_KEY in response: raise GfycatClientError(response[ERROR_KEY], r.status_code) self.token_type = response['token_type'] self.access_token = response['access_token'] self.expires_in = response['expires_in'] self.expires_at = time.time() + self.expires_in - 5 self.headers = {'content-type': 'application/json','Authorization': self.token_type + ' ' + self.access_token}
[ "def", "get_token", "(", "self", ")", ":", "payload", "=", "{", "'grant_type'", ":", "'client_credentials'", ",", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", "}", "r", "=", "requests", ".", "post",...
Gets the authorization token
[ "Gets", "the", "authorization", "token" ]
74759a88fc59db1c5b270331b24442bc5f4c38e9
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L118-L137
train
26,533
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.dict
def dict(self): """ dictionary representation of the metadata. :return: dictionary representation of the metadata :rtype: dict """ metadata = {} properties = {} for name, prop in list(self.properties.items()): properties[name] = prop.dict metadata['properties'] = properties return metadata
python
def dict(self): """ dictionary representation of the metadata. :return: dictionary representation of the metadata :rtype: dict """ metadata = {} properties = {} for name, prop in list(self.properties.items()): properties[name] = prop.dict metadata['properties'] = properties return metadata
[ "def", "dict", "(", "self", ")", ":", "metadata", "=", "{", "}", "properties", "=", "{", "}", "for", "name", ",", "prop", "in", "list", "(", "self", ".", "properties", ".", "items", "(", ")", ")", ":", "properties", "[", "name", "]", "=", "prop",...
dictionary representation of the metadata. :return: dictionary representation of the metadata :rtype: dict
[ "dictionary", "representation", "of", "the", "metadata", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L251-L263
train
26,534
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.json
def json(self): """ json representation of the metadata. :return: json representation of the metadata :rtype: str """ json_dumps = json.dumps( self.dict, indent=2, sort_keys=True, separators=(',', ': '), cls=MetadataEncoder ) if not json_dumps.endswith('\n'): json_dumps += '\n' return json_dumps
python
def json(self): """ json representation of the metadata. :return: json representation of the metadata :rtype: str """ json_dumps = json.dumps( self.dict, indent=2, sort_keys=True, separators=(',', ': '), cls=MetadataEncoder ) if not json_dumps.endswith('\n'): json_dumps += '\n' return json_dumps
[ "def", "json", "(", "self", ")", ":", "json_dumps", "=", "json", ".", "dumps", "(", "self", ".", "dict", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "','", ",", "': '", ")", ",", "cls", "=", "MetadataEncoder...
json representation of the metadata. :return: json representation of the metadata :rtype: str
[ "json", "representation", "of", "the", "metadata", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L287-L303
train
26,535
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata._read_json_file
def _read_json_file(self): """ read metadata from a json file. :return: the parsed json dict :rtype: dict """ with open(self.json_uri) as metadata_file: try: metadata = json.load(metadata_file) return metadata except ValueError: message = tr('the file %s does not appear to be valid JSON') message = message % self.json_uri raise MetadataReadError(message)
python
def _read_json_file(self): """ read metadata from a json file. :return: the parsed json dict :rtype: dict """ with open(self.json_uri) as metadata_file: try: metadata = json.load(metadata_file) return metadata except ValueError: message = tr('the file %s does not appear to be valid JSON') message = message % self.json_uri raise MetadataReadError(message)
[ "def", "_read_json_file", "(", "self", ")", ":", "with", "open", "(", "self", ".", "json_uri", ")", "as", "metadata_file", ":", "try", ":", "metadata", "=", "json", ".", "load", "(", "metadata_file", ")", "return", "metadata", "except", "ValueError", ":", ...
read metadata from a json file. :return: the parsed json dict :rtype: dict
[ "read", "metadata", "from", "a", "json", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L330-L344
train
26,536
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata._read_json_db
def _read_json_db(self): """ read metadata from a json string stored in a DB. :return: the parsed json dict :rtype: dict """ try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'json') except HashNotFoundError: return {} try: metadata = json.loads(metadata_str) return metadata except ValueError: message = tr('the file DB entry for %s does not appear to be ' 'valid JSON') message %= self.layer_uri raise MetadataReadError(message)
python
def _read_json_db(self): """ read metadata from a json string stored in a DB. :return: the parsed json dict :rtype: dict """ try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'json') except HashNotFoundError: return {} try: metadata = json.loads(metadata_str) return metadata except ValueError: message = tr('the file DB entry for %s does not appear to be ' 'valid JSON') message %= self.layer_uri raise MetadataReadError(message)
[ "def", "_read_json_db", "(", "self", ")", ":", "try", ":", "metadata_str", "=", "self", ".", "db_io", ".", "read_metadata_from_uri", "(", "self", ".", "layer_uri", ",", "'json'", ")", "except", "HashNotFoundError", ":", "return", "{", "}", "try", ":", "met...
read metadata from a json string stored in a DB. :return: the parsed json dict :rtype: dict
[ "read", "metadata", "from", "a", "json", "string", "stored", "in", "a", "DB", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L346-L365
train
26,537
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata._read_xml_file
def _read_xml_file(self): """ read metadata from an xml file. :return: the root element of the xml :rtype: ElementTree.Element """ # this raises a IOError if the file doesn't exist root = ElementTree.parse(self.xml_uri) root.getroot() return root
python
def _read_xml_file(self): """ read metadata from an xml file. :return: the root element of the xml :rtype: ElementTree.Element """ # this raises a IOError if the file doesn't exist root = ElementTree.parse(self.xml_uri) root.getroot() return root
[ "def", "_read_xml_file", "(", "self", ")", ":", "# this raises a IOError if the file doesn't exist", "root", "=", "ElementTree", ".", "parse", "(", "self", ".", "xml_uri", ")", "root", ".", "getroot", "(", ")", "return", "root" ]
read metadata from an xml file. :return: the root element of the xml :rtype: ElementTree.Element
[ "read", "metadata", "from", "an", "xml", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L388-L398
train
26,538
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata._read_xml_db
def _read_xml_db(self): """ read metadata from an xml string stored in a DB. :return: the root element of the xml :rtype: ElementTree.Element """ try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'xml') root = ElementTree.fromstring(metadata_str) return root except HashNotFoundError: return None
python
def _read_xml_db(self): """ read metadata from an xml string stored in a DB. :return: the root element of the xml :rtype: ElementTree.Element """ try: metadata_str = self.db_io.read_metadata_from_uri( self.layer_uri, 'xml') root = ElementTree.fromstring(metadata_str) return root except HashNotFoundError: return None
[ "def", "_read_xml_db", "(", "self", ")", ":", "try", ":", "metadata_str", "=", "self", ".", "db_io", ".", "read_metadata_from_uri", "(", "self", ".", "layer_uri", ",", "'xml'", ")", "root", "=", "ElementTree", ".", "fromstring", "(", "metadata_str", ")", "...
read metadata from an xml string stored in a DB. :return: the root element of the xml :rtype: ElementTree.Element
[ "read", "metadata", "from", "an", "xml", "string", "stored", "in", "a", "DB", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L400-L413
train
26,539
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.set
def set(self, name, value, xml_path): """ Create a new metadata property. The accepted type depends on the property type which is determined by the xml_path :param name: the name of the property :type name: str :param value: the value of the property :type value: :param xml_path: the xml path where the property should be stored. This is split on / and the last element is used to determine the property type :type xml_path: str """ xml_type = xml_path.split('/')[-1] # check if the desired type is supported try: property_class = TYPE_CONVERSIONS[xml_type] except KeyError: raise KeyError('The xml type %s is not supported yet' % xml_type) try: metadata_property = property_class(name, value, xml_path) self._properties[name] = metadata_property self.set_last_update_to_now() except TypeError: if self.reading_ancillary_files: # we are parsing files so we want to accept as much as # possible without raising exceptions pass else: raise
python
def set(self, name, value, xml_path): """ Create a new metadata property. The accepted type depends on the property type which is determined by the xml_path :param name: the name of the property :type name: str :param value: the value of the property :type value: :param xml_path: the xml path where the property should be stored. This is split on / and the last element is used to determine the property type :type xml_path: str """ xml_type = xml_path.split('/')[-1] # check if the desired type is supported try: property_class = TYPE_CONVERSIONS[xml_type] except KeyError: raise KeyError('The xml type %s is not supported yet' % xml_type) try: metadata_property = property_class(name, value, xml_path) self._properties[name] = metadata_property self.set_last_update_to_now() except TypeError: if self.reading_ancillary_files: # we are parsing files so we want to accept as much as # possible without raising exceptions pass else: raise
[ "def", "set", "(", "self", ",", "name", ",", "value", ",", "xml_path", ")", ":", "xml_type", "=", "xml_path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "# check if the desired type is supported", "try", ":", "property_class", "=", "TYPE_CONVERSIONS"...
Create a new metadata property. The accepted type depends on the property type which is determined by the xml_path :param name: the name of the property :type name: str :param value: the value of the property :type value: :param xml_path: the xml path where the property should be stored. This is split on / and the last element is used to determine the property type :type xml_path: str
[ "Create", "a", "new", "metadata", "property", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L531-L565
train
26,540
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.write_to_file
def write_to_file(self, destination_path): """ Writes the metadata json or xml to a file. :param destination_path: the file path the file format is inferred from the destination_path extension. :type destination_path: str :return: the written metadata :rtype: str """ file_format = os.path.splitext(destination_path)[1][1:] metadata = self.get_writable_metadata(file_format) with open(destination_path, 'w', encoding='utf-8') as f: f.write(metadata) return metadata
python
def write_to_file(self, destination_path): """ Writes the metadata json or xml to a file. :param destination_path: the file path the file format is inferred from the destination_path extension. :type destination_path: str :return: the written metadata :rtype: str """ file_format = os.path.splitext(destination_path)[1][1:] metadata = self.get_writable_metadata(file_format) with open(destination_path, 'w', encoding='utf-8') as f: f.write(metadata) return metadata
[ "def", "write_to_file", "(", "self", ",", "destination_path", ")", ":", "file_format", "=", "os", ".", "path", ".", "splitext", "(", "destination_path", ")", "[", "1", "]", "[", "1", ":", "]", "metadata", "=", "self", ".", "get_writable_metadata", "(", "...
Writes the metadata json or xml to a file. :param destination_path: the file path the file format is inferred from the destination_path extension. :type destination_path: str :return: the written metadata :rtype: str
[ "Writes", "the", "metadata", "json", "or", "xml", "to", "a", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L584-L600
train
26,541
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.get_writable_metadata
def get_writable_metadata(self, file_format): """ Convert the metadata to a writable form. :param file_format: the needed format can be json or xml :type file_format: str :return: the dupled metadata :rtype: str """ if file_format == 'json': metadata = self.json elif file_format == 'xml': metadata = self.xml else: raise TypeError('The requested file type (%s) is not yet supported' % file_format) return metadata
python
def get_writable_metadata(self, file_format): """ Convert the metadata to a writable form. :param file_format: the needed format can be json or xml :type file_format: str :return: the dupled metadata :rtype: str """ if file_format == 'json': metadata = self.json elif file_format == 'xml': metadata = self.xml else: raise TypeError('The requested file type (%s) is not yet supported' % file_format) return metadata
[ "def", "get_writable_metadata", "(", "self", ",", "file_format", ")", ":", "if", "file_format", "==", "'json'", ":", "metadata", "=", "self", ".", "json", "elif", "file_format", "==", "'xml'", ":", "metadata", "=", "self", ".", "xml", "else", ":", "raise",...
Convert the metadata to a writable form. :param file_format: the needed format can be json or xml :type file_format: str :return: the dupled metadata :rtype: str
[ "Convert", "the", "metadata", "to", "a", "writable", "form", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L625-L641
train
26,542
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.read_from_ancillary_file
def read_from_ancillary_file(self, custom_xml=None): """ try to read xml and json from existing files or db. This is used when instantiating a new metadata object. We explicitly check if a custom XML was passed so we give it priority on the JSON. If no custom XML is passed, JSON has priority :param custom_xml: the path to a custom xml file :type custom_xml: str """ if custom_xml and os.path.isfile(self.xml_uri): self.read_xml() else: if not self.read_json(): self.read_xml()
python
def read_from_ancillary_file(self, custom_xml=None): """ try to read xml and json from existing files or db. This is used when instantiating a new metadata object. We explicitly check if a custom XML was passed so we give it priority on the JSON. If no custom XML is passed, JSON has priority :param custom_xml: the path to a custom xml file :type custom_xml: str """ if custom_xml and os.path.isfile(self.xml_uri): self.read_xml() else: if not self.read_json(): self.read_xml()
[ "def", "read_from_ancillary_file", "(", "self", ",", "custom_xml", "=", "None", ")", ":", "if", "custom_xml", "and", "os", ".", "path", ".", "isfile", "(", "self", ".", "xml_uri", ")", ":", "self", ".", "read_xml", "(", ")", "else", ":", "if", "not", ...
try to read xml and json from existing files or db. This is used when instantiating a new metadata object. We explicitly check if a custom XML was passed so we give it priority on the JSON. If no custom XML is passed, JSON has priority :param custom_xml: the path to a custom xml file :type custom_xml: str
[ "try", "to", "read", "xml", "and", "json", "from", "existing", "files", "or", "db", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L643-L659
train
26,543
inasafe/inasafe
safe/metadata/base_metadata.py
BaseMetadata.update_from_dict
def update_from_dict(self, keywords): """Set properties of metadata using key and value from keywords :param keywords: A dictionary of keywords (key, value). :type keywords: dict """ for key, value in list(keywords.items()): setattr(self, key, value)
python
def update_from_dict(self, keywords): """Set properties of metadata using key and value from keywords :param keywords: A dictionary of keywords (key, value). :type keywords: dict """ for key, value in list(keywords.items()): setattr(self, key, value)
[ "def", "update_from_dict", "(", "self", ",", "keywords", ")", ":", "for", "key", ",", "value", "in", "list", "(", "keywords", ".", "items", "(", ")", ")", ":", "setattr", "(", "self", ",", "key", ",", "value", ")" ]
Set properties of metadata using key and value from keywords :param keywords: A dictionary of keywords (key, value). :type keywords: dict
[ "Set", "properties", "of", "metadata", "using", "key", "and", "value", "from", "keywords" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L671-L679
train
26,544
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.accept
def accept(self): """Process the layer for multi buffering and generate a new layer. .. note:: This is called on OK click. """ # set parameter from dialog input_layer = self.layer.currentLayer() output_path = self.output_form.text() radius = self.get_classification() # monkey patch keywords so layer works on multi buffering function input_layer.keywords = {'inasafe_fields': {}} # run multi buffering self.output_layer = multi_buffering(input_layer, radius) # save output layer to data store and check whether user # provide the output path. if output_path: self.output_directory, self.output_filename = ( os.path.split(output_path)) self.output_filename, self.output_extension = ( os.path.splitext(self.output_filename)) # if user do not provide the output path, create a temporary file. else: self.output_directory = temp_dir(sub_dir='work') self.output_filename = ( unique_filename( prefix='hazard_layer', suffix='.geojson', dir=self.output_directory)) self.output_filename = os.path.split(self.output_filename)[1] self.output_filename, self.output_extension = ( os.path.splitext(self.output_filename)) self.data_store = Folder(self.output_directory) if self.output_extension == '.shp': self.data_store.default_vector_format = 'shp' elif self.output_extension == '.geojson': self.data_store.default_vector_format = 'geojson' self.data_store.add_layer(self.output_layer, self.output_filename) # add output layer to map canvas self.output_layer = self.data_store.layer(self.output_filename) QgsProject.instance().addMapLayers( [self.output_layer]) self.iface.setActiveLayer(self.output_layer) self.iface.zoomToActiveLayer() self.done(QtWidgets.QDialog.Accepted) if self.keyword_wizard_checkbox.isChecked(): self.launch_keyword_wizard()
python
def accept(self): """Process the layer for multi buffering and generate a new layer. .. note:: This is called on OK click. """ # set parameter from dialog input_layer = self.layer.currentLayer() output_path = self.output_form.text() radius = self.get_classification() # monkey patch keywords so layer works on multi buffering function input_layer.keywords = {'inasafe_fields': {}} # run multi buffering self.output_layer = multi_buffering(input_layer, radius) # save output layer to data store and check whether user # provide the output path. if output_path: self.output_directory, self.output_filename = ( os.path.split(output_path)) self.output_filename, self.output_extension = ( os.path.splitext(self.output_filename)) # if user do not provide the output path, create a temporary file. else: self.output_directory = temp_dir(sub_dir='work') self.output_filename = ( unique_filename( prefix='hazard_layer', suffix='.geojson', dir=self.output_directory)) self.output_filename = os.path.split(self.output_filename)[1] self.output_filename, self.output_extension = ( os.path.splitext(self.output_filename)) self.data_store = Folder(self.output_directory) if self.output_extension == '.shp': self.data_store.default_vector_format = 'shp' elif self.output_extension == '.geojson': self.data_store.default_vector_format = 'geojson' self.data_store.add_layer(self.output_layer, self.output_filename) # add output layer to map canvas self.output_layer = self.data_store.layer(self.output_filename) QgsProject.instance().addMapLayers( [self.output_layer]) self.iface.setActiveLayer(self.output_layer) self.iface.zoomToActiveLayer() self.done(QtWidgets.QDialog.Accepted) if self.keyword_wizard_checkbox.isChecked(): self.launch_keyword_wizard()
[ "def", "accept", "(", "self", ")", ":", "# set parameter from dialog", "input_layer", "=", "self", ".", "layer", ".", "currentLayer", "(", ")", "output_path", "=", "self", ".", "output_form", ".", "text", "(", ")", "radius", "=", "self", ".", "get_classifica...
Process the layer for multi buffering and generate a new layer. .. note:: This is called on OK click.
[ "Process", "the", "layer", "for", "multi", "buffering", "and", "generate", "a", "new", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L104-L156
train
26,545
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.on_directory_button_tool_clicked
def on_directory_button_tool_clicked(self): """Autoconnect slot activated when directory button is clicked.""" # noinspection PyCallByClass,PyTypeChecker # set up parameter from dialog input_path = self.layer.currentLayer().source() input_directory, self.output_filename = os.path.split(input_path) file_extension = os.path.splitext(self.output_filename)[1] self.output_filename = os.path.splitext(self.output_filename)[0] # show Qt file directory dialog output_path, __ = QtWidgets.QFileDialog.getSaveFileName( self, self.tr('Output file'), '%s_multi_buffer%s' % ( os.path.join(input_directory, self.output_filename), file_extension), 'GeoJSON (*.geojson);;Shapefile (*.shp)') # set selected path to the dialog self.output_form.setText(output_path)
python
def on_directory_button_tool_clicked(self): """Autoconnect slot activated when directory button is clicked.""" # noinspection PyCallByClass,PyTypeChecker # set up parameter from dialog input_path = self.layer.currentLayer().source() input_directory, self.output_filename = os.path.split(input_path) file_extension = os.path.splitext(self.output_filename)[1] self.output_filename = os.path.splitext(self.output_filename)[0] # show Qt file directory dialog output_path, __ = QtWidgets.QFileDialog.getSaveFileName( self, self.tr('Output file'), '%s_multi_buffer%s' % ( os.path.join(input_directory, self.output_filename), file_extension), 'GeoJSON (*.geojson);;Shapefile (*.shp)') # set selected path to the dialog self.output_form.setText(output_path)
[ "def", "on_directory_button_tool_clicked", "(", "self", ")", ":", "# noinspection PyCallByClass,PyTypeChecker", "# set up parameter from dialog", "input_path", "=", "self", ".", "layer", ".", "currentLayer", "(", ")", ".", "source", "(", ")", "input_directory", ",", "se...
Autoconnect slot activated when directory button is clicked.
[ "Autoconnect", "slot", "activated", "when", "directory", "button", "is", "clicked", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L159-L176
train
26,546
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.get_output_from_input
def get_output_from_input(self): """Populate output form with default output path based on input layer. """ input_path = self.layer.currentLayer().source() output_path = ( os.path.splitext(input_path)[0] + '_multi_buffer' + os.path.splitext(input_path)[1]) self.output_form.setText(output_path)
python
def get_output_from_input(self): """Populate output form with default output path based on input layer. """ input_path = self.layer.currentLayer().source() output_path = ( os.path.splitext(input_path)[0] + '_multi_buffer' + os.path.splitext(input_path)[1]) self.output_form.setText(output_path)
[ "def", "get_output_from_input", "(", "self", ")", ":", "input_path", "=", "self", ".", "layer", ".", "currentLayer", "(", ")", ".", "source", "(", ")", "output_path", "=", "(", "os", ".", "path", ".", "splitext", "(", "input_path", ")", "[", "0", "]", ...
Populate output form with default output path based on input layer.
[ "Populate", "output", "form", "with", "default", "output", "path", "based", "on", "input", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L178-L185
train
26,547
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.populate_hazard_classification
def populate_hazard_classification(self): """Populate hazard classification on hazard class form.""" new_class = { 'value': self.radius_form.value(), 'name': self.class_form.text()} self.classification.append(new_class) self.classification = sorted( self.classification, key=itemgetter('value')) self.hazard_class_form.clear() for item in self.classification: new_item = '{value} - {name}'.format( value=item['value'], name=item['name']) self.hazard_class_form.addItem(new_item) self.radius_form.setValue(0) self.class_form.clear() self.ok_button_status()
python
def populate_hazard_classification(self): """Populate hazard classification on hazard class form.""" new_class = { 'value': self.radius_form.value(), 'name': self.class_form.text()} self.classification.append(new_class) self.classification = sorted( self.classification, key=itemgetter('value')) self.hazard_class_form.clear() for item in self.classification: new_item = '{value} - {name}'.format( value=item['value'], name=item['name']) self.hazard_class_form.addItem(new_item) self.radius_form.setValue(0) self.class_form.clear() self.ok_button_status()
[ "def", "populate_hazard_classification", "(", "self", ")", ":", "new_class", "=", "{", "'value'", ":", "self", ".", "radius_form", ".", "value", "(", ")", ",", "'name'", ":", "self", ".", "class_form", ".", "text", "(", ")", "}", "self", ".", "classifica...
Populate hazard classification on hazard class form.
[ "Populate", "hazard", "classification", "on", "hazard", "class", "form", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L187-L204
train
26,548
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.remove_selected_classification
def remove_selected_classification(self): """Remove selected item on hazard class form.""" removed_classes = self.hazard_class_form.selectedItems() current_item = self.hazard_class_form.currentItem() removed_index = self.hazard_class_form.indexFromItem(current_item) del self.classification[removed_index.row()] for item in removed_classes: self.hazard_class_form.takeItem( self.hazard_class_form.row(item))
python
def remove_selected_classification(self): """Remove selected item on hazard class form.""" removed_classes = self.hazard_class_form.selectedItems() current_item = self.hazard_class_form.currentItem() removed_index = self.hazard_class_form.indexFromItem(current_item) del self.classification[removed_index.row()] for item in removed_classes: self.hazard_class_form.takeItem( self.hazard_class_form.row(item))
[ "def", "remove_selected_classification", "(", "self", ")", ":", "removed_classes", "=", "self", ".", "hazard_class_form", ".", "selectedItems", "(", ")", "current_item", "=", "self", ".", "hazard_class_form", ".", "currentItem", "(", ")", "removed_index", "=", "se...
Remove selected item on hazard class form.
[ "Remove", "selected", "item", "on", "hazard", "class", "form", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L206-L214
train
26,549
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.get_classification
def get_classification(self): """Get all hazard class created by user. :return: Hazard class definition created by user. :rtype: OrderedDict """ classification_dictionary = {} for item in self.classification: classification_dictionary[item['value']] = item['name'] classification_dictionary = OrderedDict( sorted(classification_dictionary.items())) return classification_dictionary
python
def get_classification(self): """Get all hazard class created by user. :return: Hazard class definition created by user. :rtype: OrderedDict """ classification_dictionary = {} for item in self.classification: classification_dictionary[item['value']] = item['name'] classification_dictionary = OrderedDict( sorted(classification_dictionary.items())) return classification_dictionary
[ "def", "get_classification", "(", "self", ")", ":", "classification_dictionary", "=", "{", "}", "for", "item", "in", "self", ".", "classification", ":", "classification_dictionary", "[", "item", "[", "'value'", "]", "]", "=", "item", "[", "'name'", "]", "cla...
Get all hazard class created by user. :return: Hazard class definition created by user. :rtype: OrderedDict
[ "Get", "all", "hazard", "class", "created", "by", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L216-L229
train
26,550
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.directory_button_status
def directory_button_status(self): """Function to enable or disable directory button.""" if self.layer.currentLayer(): self.directory_button.setEnabled(True) else: self.directory_button.setEnabled(False)
python
def directory_button_status(self): """Function to enable or disable directory button.""" if self.layer.currentLayer(): self.directory_button.setEnabled(True) else: self.directory_button.setEnabled(False)
[ "def", "directory_button_status", "(", "self", ")", ":", "if", "self", ".", "layer", ".", "currentLayer", "(", ")", ":", "self", ".", "directory_button", ".", "setEnabled", "(", "True", ")", "else", ":", "self", ".", "directory_button", ".", "setEnabled", ...
Function to enable or disable directory button.
[ "Function", "to", "enable", "or", "disable", "directory", "button", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L231-L236
train
26,551
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.add_class_button_status
def add_class_button_status(self): """Function to enable or disable add class button.""" if self.class_form.text() and self.radius_form.value() >= 0: self.add_class_button.setEnabled(True) else: self.add_class_button.setEnabled(False)
python
def add_class_button_status(self): """Function to enable or disable add class button.""" if self.class_form.text() and self.radius_form.value() >= 0: self.add_class_button.setEnabled(True) else: self.add_class_button.setEnabled(False)
[ "def", "add_class_button_status", "(", "self", ")", ":", "if", "self", ".", "class_form", ".", "text", "(", ")", "and", "self", ".", "radius_form", ".", "value", "(", ")", ">=", "0", ":", "self", ".", "add_class_button", ".", "setEnabled", "(", "True", ...
Function to enable or disable add class button.
[ "Function", "to", "enable", "or", "disable", "add", "class", "button", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L238-L243
train
26,552
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.ok_button_status
def ok_button_status(self): """Function to enable or disable OK button.""" if not self.layer.currentLayer(): self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(False) elif (self.hazard_class_form.count() > 0 and self.layer.currentLayer().name() and len(self.output_form.text()) >= 0): self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(True) else: self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
python
def ok_button_status(self): """Function to enable or disable OK button.""" if not self.layer.currentLayer(): self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(False) elif (self.hazard_class_form.count() > 0 and self.layer.currentLayer().name() and len(self.output_form.text()) >= 0): self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(True) else: self.button_box.button( QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
[ "def", "ok_button_status", "(", "self", ")", ":", "if", "not", "self", ".", "layer", ".", "currentLayer", "(", ")", ":", "self", ".", "button_box", ".", "button", "(", "QtWidgets", ".", "QDialogButtonBox", ".", "Ok", ")", ".", "setEnabled", "(", "False",...
Function to enable or disable OK button.
[ "Function", "to", "enable", "or", "disable", "OK", "button", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L245-L257
train
26,553
inasafe/inasafe
safe/gui/tools/multi_buffer_dialog.py
MultiBufferDialog.help_toggled
def help_toggled(self, flag): """Show or hide the help tab in the stacked widget. :param flag: Flag indicating whether help should be shown or hidden. :type flag: bool """ if flag: self.help_button.setText(self.tr('Hide Help')) self.show_help() else: self.help_button.setText(self.tr('Show Help')) self.hide_help()
python
def help_toggled(self, flag): """Show or hide the help tab in the stacked widget. :param flag: Flag indicating whether help should be shown or hidden. :type flag: bool """ if flag: self.help_button.setText(self.tr('Hide Help')) self.show_help() else: self.help_button.setText(self.tr('Show Help')) self.hide_help()
[ "def", "help_toggled", "(", "self", ",", "flag", ")", ":", "if", "flag", ":", "self", ".", "help_button", ".", "setText", "(", "self", ".", "tr", "(", "'Hide Help'", ")", ")", "self", ".", "show_help", "(", ")", "else", ":", "self", ".", "help_button...
Show or hide the help tab in the stacked widget. :param flag: Flag indicating whether help should be shown or hidden. :type flag: bool
[ "Show", "or", "hide", "the", "help", "tab", "in", "the", "stacked", "widget", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L260-L271
train
26,554
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
convert_mmi_data
def convert_mmi_data( grid_xml_path, title, source, output_path=None, algorithm=None, algorithm_filename_flag=True, smoothing_method=NONE_SMOOTHING, smooth_sigma=0.9, extra_keywords=None ): """Convenience function to convert a single file. :param grid_xml_path: Path to the xml shake grid file. :type grid_xml_path: str :param title: The title of the earthquake. :type title: str :param source: The source of the shake data. :type source: str :param place_layer: Nearby cities/places. :type place_layer: QgsVectorLayer :param place_name: Column name that indicates name of the cities. :type place_name: str :param place_population: Column name that indicates number of population. :type place_population: str :param output_path: Specify which path to use as an alternative to the default. :type output_path: str :param algorithm: Type of algorithm to be used. :type algorithm: str :param algorithm_filename_flag: Flag whether to use the algorithm in the output file's name. :type algorithm_filename_flag: bool :param smoothing_method: Smoothing method. One of None, Numpy, Scipy. :type smoothing_method: basestring :param smooth_sigma: parameter for gaussian filter used in smoothing function. :type smooth_sigma: float :returns: A path to the resulting raster file. :rtype: str """ LOGGER.debug(grid_xml_path) LOGGER.debug(output_path) if output_path is not None: output_dir, output_basename = os.path.split(output_path) output_basename, _ = os.path.splitext(output_basename) LOGGER.debug( 'output_dir : ' + output_dir + 'output_basename : ' + output_basename) else: output_dir = output_path output_basename = None converter = ShakeGrid( title, source, grid_xml_path, output_dir=output_dir, output_basename=output_basename, algorithm_filename_flag=algorithm_filename_flag, smoothing_method=smoothing_method, smooth_sigma=smooth_sigma, extra_keywords=extra_keywords ) return converter.mmi_to_raster(force_flag=True, algorithm=algorithm)
python
def convert_mmi_data( grid_xml_path, title, source, output_path=None, algorithm=None, algorithm_filename_flag=True, smoothing_method=NONE_SMOOTHING, smooth_sigma=0.9, extra_keywords=None ): """Convenience function to convert a single file. :param grid_xml_path: Path to the xml shake grid file. :type grid_xml_path: str :param title: The title of the earthquake. :type title: str :param source: The source of the shake data. :type source: str :param place_layer: Nearby cities/places. :type place_layer: QgsVectorLayer :param place_name: Column name that indicates name of the cities. :type place_name: str :param place_population: Column name that indicates number of population. :type place_population: str :param output_path: Specify which path to use as an alternative to the default. :type output_path: str :param algorithm: Type of algorithm to be used. :type algorithm: str :param algorithm_filename_flag: Flag whether to use the algorithm in the output file's name. :type algorithm_filename_flag: bool :param smoothing_method: Smoothing method. One of None, Numpy, Scipy. :type smoothing_method: basestring :param smooth_sigma: parameter for gaussian filter used in smoothing function. :type smooth_sigma: float :returns: A path to the resulting raster file. :rtype: str """ LOGGER.debug(grid_xml_path) LOGGER.debug(output_path) if output_path is not None: output_dir, output_basename = os.path.split(output_path) output_basename, _ = os.path.splitext(output_basename) LOGGER.debug( 'output_dir : ' + output_dir + 'output_basename : ' + output_basename) else: output_dir = output_path output_basename = None converter = ShakeGrid( title, source, grid_xml_path, output_dir=output_dir, output_basename=output_basename, algorithm_filename_flag=algorithm_filename_flag, smoothing_method=smoothing_method, smooth_sigma=smooth_sigma, extra_keywords=extra_keywords ) return converter.mmi_to_raster(force_flag=True, algorithm=algorithm)
[ "def", "convert_mmi_data", "(", "grid_xml_path", ",", "title", ",", "source", ",", "output_path", "=", "None", ",", "algorithm", "=", "None", ",", "algorithm_filename_flag", "=", "True", ",", "smoothing_method", "=", "NONE_SMOOTHING", ",", "smooth_sigma", "=", "...
Convenience function to convert a single file. :param grid_xml_path: Path to the xml shake grid file. :type grid_xml_path: str :param title: The title of the earthquake. :type title: str :param source: The source of the shake data. :type source: str :param place_layer: Nearby cities/places. :type place_layer: QgsVectorLayer :param place_name: Column name that indicates name of the cities. :type place_name: str :param place_population: Column name that indicates number of population. :type place_population: str :param output_path: Specify which path to use as an alternative to the default. :type output_path: str :param algorithm: Type of algorithm to be used. :type algorithm: str :param algorithm_filename_flag: Flag whether to use the algorithm in the output file's name. :type algorithm_filename_flag: bool :param smoothing_method: Smoothing method. One of None, Numpy, Scipy. :type smoothing_method: basestring :param smooth_sigma: parameter for gaussian filter used in smoothing function. :type smooth_sigma: float :returns: A path to the resulting raster file. :rtype: str
[ "Convenience", "function", "to", "convert", "a", "single", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L990-L1065
train
26,555
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.extract_date_time
def extract_date_time(self, the_time_stamp): """Extract the parts of a date given a timestamp as per below example. :param the_time_stamp: The 'event_timestamp' attribute from grid.xml. :type the_time_stamp: str # now separate out its parts # >>> e = "2012-08-07T01:55:12WIB" #>>> e[0:10] #'2012-08-07' #>>> e[12:-3] #'01:55:11' #>>> e[-3:] #'WIB' (WIB = Western Indonesian Time) """ date_tokens = the_time_stamp[0:10].split('-') self.year = int(date_tokens[0]) self.month = int(date_tokens[1]) self.day = int(date_tokens[2]) time_tokens = the_time_stamp[11:19].split(':') self.hour = int(time_tokens[0]) self.minute = int(time_tokens[1]) self.second = int(time_tokens[2]) # right now only handles Indonesian Timezones tz_dict = { 'WIB': 'Asia/Jakarta', 'WITA': 'Asia/Makassar', 'WIT': 'Asia/Jayapura' } if self.time_zone in tz_dict: self.time_zone = tz_dict.get(self.time_zone, self.time_zone) # noinspection PyBroadException try: if not self.time_zone: # default to utc if empty tzinfo = pytz.utc else: tzinfo = timezone(self.time_zone) except BaseException: tzinfo = pytz.utc self.time = datetime( self.year, self.month, self.day, self.hour, self.minute, self.second) # For now realtime always uses Western Indonesia Time self.time = tzinfo.localize(self.time)
python
def extract_date_time(self, the_time_stamp): """Extract the parts of a date given a timestamp as per below example. :param the_time_stamp: The 'event_timestamp' attribute from grid.xml. :type the_time_stamp: str # now separate out its parts # >>> e = "2012-08-07T01:55:12WIB" #>>> e[0:10] #'2012-08-07' #>>> e[12:-3] #'01:55:11' #>>> e[-3:] #'WIB' (WIB = Western Indonesian Time) """ date_tokens = the_time_stamp[0:10].split('-') self.year = int(date_tokens[0]) self.month = int(date_tokens[1]) self.day = int(date_tokens[2]) time_tokens = the_time_stamp[11:19].split(':') self.hour = int(time_tokens[0]) self.minute = int(time_tokens[1]) self.second = int(time_tokens[2]) # right now only handles Indonesian Timezones tz_dict = { 'WIB': 'Asia/Jakarta', 'WITA': 'Asia/Makassar', 'WIT': 'Asia/Jayapura' } if self.time_zone in tz_dict: self.time_zone = tz_dict.get(self.time_zone, self.time_zone) # noinspection PyBroadException try: if not self.time_zone: # default to utc if empty tzinfo = pytz.utc else: tzinfo = timezone(self.time_zone) except BaseException: tzinfo = pytz.utc self.time = datetime( self.year, self.month, self.day, self.hour, self.minute, self.second) # For now realtime always uses Western Indonesia Time self.time = tzinfo.localize(self.time)
[ "def", "extract_date_time", "(", "self", ",", "the_time_stamp", ")", ":", "date_tokens", "=", "the_time_stamp", "[", "0", ":", "10", "]", ".", "split", "(", "'-'", ")", "self", ".", "year", "=", "int", "(", "date_tokens", "[", "0", "]", ")", "self", ...
Extract the parts of a date given a timestamp as per below example. :param the_time_stamp: The 'event_timestamp' attribute from grid.xml. :type the_time_stamp: str # now separate out its parts # >>> e = "2012-08-07T01:55:12WIB" #>>> e[0:10] #'2012-08-07' #>>> e[12:-3] #'01:55:11' #>>> e[-3:] #'WIB' (WIB = Western Indonesian Time)
[ "Extract", "the", "parts", "of", "a", "date", "given", "a", "timestamp", "as", "per", "below", "example", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L170-L222
train
26,556
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.grid_file_path
def grid_file_path(self): """Validate that grid file path points to a file. :return: The grid xml file path. :rtype: str :raises: GridXmlFileNotFoundError """ if os.path.isfile(self.grid_xml_path): return self.grid_xml_path else: raise GridXmlFileNotFoundError
python
def grid_file_path(self): """Validate that grid file path points to a file. :return: The grid xml file path. :rtype: str :raises: GridXmlFileNotFoundError """ if os.path.isfile(self.grid_xml_path): return self.grid_xml_path else: raise GridXmlFileNotFoundError
[ "def", "grid_file_path", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "grid_xml_path", ")", ":", "return", "self", ".", "grid_xml_path", "else", ":", "raise", "GridXmlFileNotFoundError" ]
Validate that grid file path points to a file. :return: The grid xml file path. :rtype: str :raises: GridXmlFileNotFoundError
[ "Validate", "that", "grid", "file", "path", "points", "to", "a", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L380-L391
train
26,557
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.mmi_to_delimited_text
def mmi_to_delimited_text(self): """Return the mmi data as a delimited test string. :returns: A delimited text string that can easily be written to disk for e.g. use by gdal_grid. :rtype: str The returned string will look like this:: 123.0750,01.7900,1 123.1000,01.7900,1.14 123.1250,01.7900,1.15 123.1500,01.7900,1.16 etc... """ delimited_text = 'lon,lat,mmi\n' for row in self.mmi_data: delimited_text += '%s,%s,%s\n' % (row[0], row[1], row[2]) return delimited_text
python
def mmi_to_delimited_text(self): """Return the mmi data as a delimited test string. :returns: A delimited text string that can easily be written to disk for e.g. use by gdal_grid. :rtype: str The returned string will look like this:: 123.0750,01.7900,1 123.1000,01.7900,1.14 123.1250,01.7900,1.15 123.1500,01.7900,1.16 etc... """ delimited_text = 'lon,lat,mmi\n' for row in self.mmi_data: delimited_text += '%s,%s,%s\n' % (row[0], row[1], row[2]) return delimited_text
[ "def", "mmi_to_delimited_text", "(", "self", ")", ":", "delimited_text", "=", "'lon,lat,mmi\\n'", "for", "row", "in", "self", ".", "mmi_data", ":", "delimited_text", "+=", "'%s,%s,%s\\n'", "%", "(", "row", "[", "0", "]", ",", "row", "[", "1", "]", ",", "...
Return the mmi data as a delimited test string. :returns: A delimited text string that can easily be written to disk for e.g. use by gdal_grid. :rtype: str The returned string will look like this:: 123.0750,01.7900,1 123.1000,01.7900,1.14 123.1250,01.7900,1.15 123.1500,01.7900,1.16 etc...
[ "Return", "the", "mmi", "data", "as", "a", "delimited", "test", "string", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L393-L411
train
26,558
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.mmi_to_delimited_file
def mmi_to_delimited_file(self, force_flag=True): """Save mmi_data to delimited text file suitable for gdal_grid. The output file will be of the same format as strings returned from :func:`mmi_to_delimited_text`. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :returns: The absolute file system path to the delimited text file. :rtype: str .. note:: An accompanying .csvt will be created which gdal uses to determine field types. The csvt will contain the following string: "Real","Real","Real". These types will be used in other conversion operations. For example to convert the csv to a shp you would do:: ogr2ogr -select mmi -a_srs EPSG:4326 mmi.shp mmi.vrt mmi """ LOGGER.debug('mmi_to_delimited_text requested.') csv_path = os.path.join( self.output_dir, 'mmi.csv') # short circuit if the csv is already created. if os.path.exists(csv_path) and force_flag is not True: return csv_path csv_file = open(csv_path, 'w') csv_file.write(self.mmi_to_delimited_text()) csv_file.close() # Also write the .csvt which contains metadata about field types csvt_path = os.path.join( self.output_dir, self.output_basename + '.csvt') csvt_file = open(csvt_path, 'w') csvt_file.write('"Real","Real","Real"') csvt_file.close() return csv_path
python
def mmi_to_delimited_file(self, force_flag=True): """Save mmi_data to delimited text file suitable for gdal_grid. The output file will be of the same format as strings returned from :func:`mmi_to_delimited_text`. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :returns: The absolute file system path to the delimited text file. :rtype: str .. note:: An accompanying .csvt will be created which gdal uses to determine field types. The csvt will contain the following string: "Real","Real","Real". These types will be used in other conversion operations. For example to convert the csv to a shp you would do:: ogr2ogr -select mmi -a_srs EPSG:4326 mmi.shp mmi.vrt mmi """ LOGGER.debug('mmi_to_delimited_text requested.') csv_path = os.path.join( self.output_dir, 'mmi.csv') # short circuit if the csv is already created. if os.path.exists(csv_path) and force_flag is not True: return csv_path csv_file = open(csv_path, 'w') csv_file.write(self.mmi_to_delimited_text()) csv_file.close() # Also write the .csvt which contains metadata about field types csvt_path = os.path.join( self.output_dir, self.output_basename + '.csvt') csvt_file = open(csvt_path, 'w') csvt_file.write('"Real","Real","Real"') csvt_file.close() return csv_path
[ "def", "mmi_to_delimited_file", "(", "self", ",", "force_flag", "=", "True", ")", ":", "LOGGER", ".", "debug", "(", "'mmi_to_delimited_text requested.'", ")", "csv_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_dir", ",", "'mmi.csv'", ...
Save mmi_data to delimited text file suitable for gdal_grid. The output file will be of the same format as strings returned from :func:`mmi_to_delimited_text`. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :returns: The absolute file system path to the delimited text file. :rtype: str .. note:: An accompanying .csvt will be created which gdal uses to determine field types. The csvt will contain the following string: "Real","Real","Real". These types will be used in other conversion operations. For example to convert the csv to a shp you would do:: ogr2ogr -select mmi -a_srs EPSG:4326 mmi.shp mmi.vrt mmi
[ "Save", "mmi_data", "to", "delimited", "text", "file", "suitable", "for", "gdal_grid", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L413-L451
train
26,559
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.mmi_to_vrt
def mmi_to_vrt(self, force_flag=True): """Save the mmi_data to an ogr vrt text file. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :returns: The absolute file system path to the .vrt text file. :rtype: str :raises: None """ # Ensure the delimited mmi file exists LOGGER.debug('mmi_to_vrt requested.') vrt_path = os.path.join( self.output_dir, self.output_basename + '.vrt') # short circuit if the vrt is already created. if os.path.exists(vrt_path) and force_flag is not True: return vrt_path csv_path = self.mmi_to_delimited_file(True) vrt_string = ( '<OGRVRTDataSource>' ' <OGRVRTLayer name="mmi">' ' <SrcDataSource>%s</SrcDataSource>' ' <GeometryType>wkbPoint</GeometryType>' ' <GeometryField encoding="PointFromColumns"' ' x="lon" y="lat" z="mmi"/>' ' </OGRVRTLayer>' '</OGRVRTDataSource>' % csv_path) with codecs.open(vrt_path, 'w', encoding='utf-8') as f: f.write(vrt_string) return vrt_path
python
def mmi_to_vrt(self, force_flag=True): """Save the mmi_data to an ogr vrt text file. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :returns: The absolute file system path to the .vrt text file. :rtype: str :raises: None """ # Ensure the delimited mmi file exists LOGGER.debug('mmi_to_vrt requested.') vrt_path = os.path.join( self.output_dir, self.output_basename + '.vrt') # short circuit if the vrt is already created. if os.path.exists(vrt_path) and force_flag is not True: return vrt_path csv_path = self.mmi_to_delimited_file(True) vrt_string = ( '<OGRVRTDataSource>' ' <OGRVRTLayer name="mmi">' ' <SrcDataSource>%s</SrcDataSource>' ' <GeometryType>wkbPoint</GeometryType>' ' <GeometryField encoding="PointFromColumns"' ' x="lon" y="lat" z="mmi"/>' ' </OGRVRTLayer>' '</OGRVRTDataSource>' % csv_path) with codecs.open(vrt_path, 'w', encoding='utf-8') as f: f.write(vrt_string) return vrt_path
[ "def", "mmi_to_vrt", "(", "self", ",", "force_flag", "=", "True", ")", ":", "# Ensure the delimited mmi file exists", "LOGGER", ".", "debug", "(", "'mmi_to_vrt requested.'", ")", "vrt_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_dir", ...
Save the mmi_data to an ogr vrt text file. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :returns: The absolute file system path to the .vrt text file. :rtype: str :raises: None
[ "Save", "the", "mmi_data", "to", "an", "ogr", "vrt", "text", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L453-L491
train
26,560
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid._run_command
def _run_command(self, command): """Run a command and raise any error as needed. This is a simple runner for executing gdal commands. :param command: A command string to be run. :type command: str :raises: Any exceptions will be propagated. """ try: my_result = call(command, shell=True) del my_result except CalledProcessError as e: LOGGER.exception('Running command failed %s' % command) message = ( 'Error while executing the following shell ' 'command: %s\nError message: %s' % (command, str(e))) # shameless hack - see https://github.com/AIFDR/inasafe/issues/141 if sys.platform == 'darwin': # Mac OS X if 'Errno 4' in str(e): # continue as the error seems to be non critical pass else: raise Exception(message) else: raise Exception(message)
python
def _run_command(self, command): """Run a command and raise any error as needed. This is a simple runner for executing gdal commands. :param command: A command string to be run. :type command: str :raises: Any exceptions will be propagated. """ try: my_result = call(command, shell=True) del my_result except CalledProcessError as e: LOGGER.exception('Running command failed %s' % command) message = ( 'Error while executing the following shell ' 'command: %s\nError message: %s' % (command, str(e))) # shameless hack - see https://github.com/AIFDR/inasafe/issues/141 if sys.platform == 'darwin': # Mac OS X if 'Errno 4' in str(e): # continue as the error seems to be non critical pass else: raise Exception(message) else: raise Exception(message)
[ "def", "_run_command", "(", "self", ",", "command", ")", ":", "try", ":", "my_result", "=", "call", "(", "command", ",", "shell", "=", "True", ")", "del", "my_result", "except", "CalledProcessError", "as", "e", ":", "LOGGER", ".", "exception", "(", "'Run...
Run a command and raise any error as needed. This is a simple runner for executing gdal commands. :param command: A command string to be run. :type command: str :raises: Any exceptions will be propagated.
[ "Run", "a", "command", "and", "raise", "any", "error", "as", "needed", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L493-L519
train
26,561
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.mmi_to_raster
def mmi_to_raster(self, force_flag=False, algorithm=USE_ASCII): """Convert the grid.xml's mmi column to a raster using gdal_grid. A geotiff file will be created. Unfortunately no python bindings exist for doing this so we are going to do it using a shell call. .. see also:: http://www.gdal.org/gdal_grid.html Example of the gdal_grid call we generate:: gdal_grid -zfield "mmi" -a invdist:power=2.0:smoothing=1.0 \ -txe 126.29 130.29 -tye 0.802 4.798 -outsize 400 400 -of GTiff \ -ot Float16 -l mmi mmi.vrt mmi.tif .. note:: It is assumed that gdal_grid is in your path. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :param algorithm: Which re-sampling algorithm to use. valid options are 'nearest' (for nearest neighbour), 'invdist' (for inverse distance), 'average' (for moving average). Defaults to 'nearest' if not specified. Note that passing re-sampling alg parameters is currently not supported. If None is passed it will be replaced with 'use_ascii'. 'use_ascii' algorithm will convert the mmi grid to ascii file then convert it to raster using gdal_translate. :type algorithm: str :returns: Path to the resulting tif file. :rtype: str .. note:: For interest you can also make quite beautiful smoothed raster using this: gdal_grid -zfield "mmi" -a_srs EPSG:4326 -a invdist:power=2.0:smoothing=1.0 -txe 122.45 126.45 -tye -2.21 1.79 -outsize 400 400 -of GTiff -ot Float16 -l mmi mmi.vrt mmi-trippy.tif """ LOGGER.debug('mmi_to_raster requested.') if algorithm is None: algorithm = USE_ASCII if self.algorithm_name: tif_path = os.path.join( self.output_dir, '%s-%s.tif' % ( self.output_basename, algorithm)) else: tif_path = os.path.join( self.output_dir, '%s.tif' % self.output_basename) # short circuit if the tif is already created. if os.path.exists(tif_path) and force_flag is not True: return tif_path if algorithm == USE_ASCII: # Convert to ascii ascii_path = self.mmi_to_ascii(True) # Creating command to convert to tif command = ( ( '%(gdal_translate)s -a_srs EPSG:4326 ' '"%(ascii)s" "%(tif)s"' ) % { 'gdal_translate': which('gdal_translate')[0], 'ascii': ascii_path, 'tif': tif_path } ) LOGGER.info('Created this gdal command:\n%s' % command) # Now run GDAL warp scottie... self._run_command(command) else: # Ensure the vrt mmi file exists (it will generate csv too if # needed) vrt_path = self.mmi_to_vrt(force_flag) # now generate the tif using default nearest neighbour # interpolation options. This gives us the same output as the # mmi.grd generated by the earthquake server. if INVDIST in algorithm: algorithm = 'invdist:power=2.0:smoothing=1.0' command = ( ( '%(gdal_grid)s -a %(alg)s -zfield "mmi" -txe %(xMin)s ' '%(xMax)s -tye %(yMin)s %(yMax)s -outsize %(dimX)i ' '%(dimY)i -of GTiff -ot Float16 -a_srs EPSG:4326 -l mmi ' '"%(vrt)s" "%(tif)s"' ) % { 'gdal_grid': which('gdal_grid')[0], 'alg': algorithm, 'xMin': self.x_minimum, 'xMax': self.x_maximum, 'yMin': self.y_minimum, 'yMax': self.y_maximum, 'dimX': self.columns, 'dimY': self.rows, 'vrt': vrt_path, 'tif': tif_path } ) LOGGER.info('Created this gdal command:\n%s' % command) # Now run GDAL warp scottie... self._run_command(command) # We will use keywords file name with simple algorithm name since # it will raise an error in windows related to having double # colon in path if INVDIST in algorithm: algorithm = 'invdist' # copy the keywords file from fixtures for this layer self.create_keyword_file(algorithm) # Lastly copy over the standard qml (QGIS Style file) for the mmi.tif if self.algorithm_name: qml_path = os.path.join( self.output_dir, '%s-%s.qml' % ( self.output_basename, algorithm)) else: qml_path = os.path.join( self.output_dir, '%s.qml' % self.output_basename) qml_source_path = resources_path('converter_data', 'mmi.qml') shutil.copyfile(qml_source_path, qml_path) return tif_path
python
def mmi_to_raster(self, force_flag=False, algorithm=USE_ASCII): """Convert the grid.xml's mmi column to a raster using gdal_grid. A geotiff file will be created. Unfortunately no python bindings exist for doing this so we are going to do it using a shell call. .. see also:: http://www.gdal.org/gdal_grid.html Example of the gdal_grid call we generate:: gdal_grid -zfield "mmi" -a invdist:power=2.0:smoothing=1.0 \ -txe 126.29 130.29 -tye 0.802 4.798 -outsize 400 400 -of GTiff \ -ot Float16 -l mmi mmi.vrt mmi.tif .. note:: It is assumed that gdal_grid is in your path. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :param algorithm: Which re-sampling algorithm to use. valid options are 'nearest' (for nearest neighbour), 'invdist' (for inverse distance), 'average' (for moving average). Defaults to 'nearest' if not specified. Note that passing re-sampling alg parameters is currently not supported. If None is passed it will be replaced with 'use_ascii'. 'use_ascii' algorithm will convert the mmi grid to ascii file then convert it to raster using gdal_translate. :type algorithm: str :returns: Path to the resulting tif file. :rtype: str .. note:: For interest you can also make quite beautiful smoothed raster using this: gdal_grid -zfield "mmi" -a_srs EPSG:4326 -a invdist:power=2.0:smoothing=1.0 -txe 122.45 126.45 -tye -2.21 1.79 -outsize 400 400 -of GTiff -ot Float16 -l mmi mmi.vrt mmi-trippy.tif """ LOGGER.debug('mmi_to_raster requested.') if algorithm is None: algorithm = USE_ASCII if self.algorithm_name: tif_path = os.path.join( self.output_dir, '%s-%s.tif' % ( self.output_basename, algorithm)) else: tif_path = os.path.join( self.output_dir, '%s.tif' % self.output_basename) # short circuit if the tif is already created. if os.path.exists(tif_path) and force_flag is not True: return tif_path if algorithm == USE_ASCII: # Convert to ascii ascii_path = self.mmi_to_ascii(True) # Creating command to convert to tif command = ( ( '%(gdal_translate)s -a_srs EPSG:4326 ' '"%(ascii)s" "%(tif)s"' ) % { 'gdal_translate': which('gdal_translate')[0], 'ascii': ascii_path, 'tif': tif_path } ) LOGGER.info('Created this gdal command:\n%s' % command) # Now run GDAL warp scottie... self._run_command(command) else: # Ensure the vrt mmi file exists (it will generate csv too if # needed) vrt_path = self.mmi_to_vrt(force_flag) # now generate the tif using default nearest neighbour # interpolation options. This gives us the same output as the # mmi.grd generated by the earthquake server. if INVDIST in algorithm: algorithm = 'invdist:power=2.0:smoothing=1.0' command = ( ( '%(gdal_grid)s -a %(alg)s -zfield "mmi" -txe %(xMin)s ' '%(xMax)s -tye %(yMin)s %(yMax)s -outsize %(dimX)i ' '%(dimY)i -of GTiff -ot Float16 -a_srs EPSG:4326 -l mmi ' '"%(vrt)s" "%(tif)s"' ) % { 'gdal_grid': which('gdal_grid')[0], 'alg': algorithm, 'xMin': self.x_minimum, 'xMax': self.x_maximum, 'yMin': self.y_minimum, 'yMax': self.y_maximum, 'dimX': self.columns, 'dimY': self.rows, 'vrt': vrt_path, 'tif': tif_path } ) LOGGER.info('Created this gdal command:\n%s' % command) # Now run GDAL warp scottie... self._run_command(command) # We will use keywords file name with simple algorithm name since # it will raise an error in windows related to having double # colon in path if INVDIST in algorithm: algorithm = 'invdist' # copy the keywords file from fixtures for this layer self.create_keyword_file(algorithm) # Lastly copy over the standard qml (QGIS Style file) for the mmi.tif if self.algorithm_name: qml_path = os.path.join( self.output_dir, '%s-%s.qml' % ( self.output_basename, algorithm)) else: qml_path = os.path.join( self.output_dir, '%s.qml' % self.output_basename) qml_source_path = resources_path('converter_data', 'mmi.qml') shutil.copyfile(qml_source_path, qml_path) return tif_path
[ "def", "mmi_to_raster", "(", "self", ",", "force_flag", "=", "False", ",", "algorithm", "=", "USE_ASCII", ")", ":", "LOGGER", ".", "debug", "(", "'mmi_to_raster requested.'", ")", "if", "algorithm", "is", "None", ":", "algorithm", "=", "USE_ASCII", "if", "se...
Convert the grid.xml's mmi column to a raster using gdal_grid. A geotiff file will be created. Unfortunately no python bindings exist for doing this so we are going to do it using a shell call. .. see also:: http://www.gdal.org/gdal_grid.html Example of the gdal_grid call we generate:: gdal_grid -zfield "mmi" -a invdist:power=2.0:smoothing=1.0 \ -txe 126.29 130.29 -tye 0.802 4.798 -outsize 400 400 -of GTiff \ -ot Float16 -l mmi mmi.vrt mmi.tif .. note:: It is assumed that gdal_grid is in your path. :param force_flag: Whether to force the regeneration of the output file. Defaults to False. :type force_flag: bool :param algorithm: Which re-sampling algorithm to use. valid options are 'nearest' (for nearest neighbour), 'invdist' (for inverse distance), 'average' (for moving average). Defaults to 'nearest' if not specified. Note that passing re-sampling alg parameters is currently not supported. If None is passed it will be replaced with 'use_ascii'. 'use_ascii' algorithm will convert the mmi grid to ascii file then convert it to raster using gdal_translate. :type algorithm: str :returns: Path to the resulting tif file. :rtype: str .. note:: For interest you can also make quite beautiful smoothed raster using this: gdal_grid -zfield "mmi" -a_srs EPSG:4326 -a invdist:power=2.0:smoothing=1.0 -txe 122.45 126.45 -tye -2.21 1.79 -outsize 400 400 -of GTiff -ot Float16 -l mmi mmi.vrt mmi-trippy.tif
[ "Convert", "the", "grid", ".", "xml", "s", "mmi", "column", "to", "a", "raster", "using", "gdal_grid", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L521-L654
train
26,562
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.mmi_to_shapefile
def mmi_to_shapefile(self, force_flag=False): """Convert grid.xml's mmi column to a vector shp file using ogr2ogr. An ESRI shape file will be created. :param force_flag: bool (Optional). Whether to force the regeneration of the output file. Defaults to False. :return: Path to the resulting tif file. :rtype: str Example of the ogr2ogr call we generate:: ogr2ogr -select mmi -a_srs EPSG:4326 mmi.shp mmi.vrt mmi .. note:: It is assumed that ogr2ogr is in your path. """ LOGGER.debug('mmi_to_shapefile requested.') shp_path = os.path.join( self.output_dir, '%s-points.shp' % self.output_basename) # Short circuit if the tif is already created. if os.path.exists(shp_path) and force_flag is not True: return shp_path # Ensure the vrt mmi file exists (it will generate csv too if needed) vrt_path = self.mmi_to_vrt(force_flag) # now generate the tif using default interpolation options binary_list = which('ogr2ogr') LOGGER.debug('Path for ogr2ogr: %s' % binary_list) if len(binary_list) < 1: raise CallGDALError( tr('ogr2ogr could not be found on your computer')) # Use the first matching gdalwarp found binary = binary_list[0] command = ( ('%(ogr2ogr)s -overwrite -select mmi -a_srs EPSG:4326 ' '%(shp)s %(vrt)s mmi') % { 'ogr2ogr': binary, 'shp': shp_path, 'vrt': vrt_path}) LOGGER.info('Created this ogr command:\n%s' % command) # Now run ogr2ogr ... # noinspection PyProtectedMember self._run_command(command) # Lastly copy over the standard qml (QGIS Style file) for the mmi.tif qml_path = os.path.join( self.output_dir, '%s-points.qml' % self.output_basename) source_qml = resources_path('converter_data', 'mmi-shape.qml') shutil.copyfile(source_qml, qml_path) return shp_path
python
def mmi_to_shapefile(self, force_flag=False): """Convert grid.xml's mmi column to a vector shp file using ogr2ogr. An ESRI shape file will be created. :param force_flag: bool (Optional). Whether to force the regeneration of the output file. Defaults to False. :return: Path to the resulting tif file. :rtype: str Example of the ogr2ogr call we generate:: ogr2ogr -select mmi -a_srs EPSG:4326 mmi.shp mmi.vrt mmi .. note:: It is assumed that ogr2ogr is in your path. """ LOGGER.debug('mmi_to_shapefile requested.') shp_path = os.path.join( self.output_dir, '%s-points.shp' % self.output_basename) # Short circuit if the tif is already created. if os.path.exists(shp_path) and force_flag is not True: return shp_path # Ensure the vrt mmi file exists (it will generate csv too if needed) vrt_path = self.mmi_to_vrt(force_flag) # now generate the tif using default interpolation options binary_list = which('ogr2ogr') LOGGER.debug('Path for ogr2ogr: %s' % binary_list) if len(binary_list) < 1: raise CallGDALError( tr('ogr2ogr could not be found on your computer')) # Use the first matching gdalwarp found binary = binary_list[0] command = ( ('%(ogr2ogr)s -overwrite -select mmi -a_srs EPSG:4326 ' '%(shp)s %(vrt)s mmi') % { 'ogr2ogr': binary, 'shp': shp_path, 'vrt': vrt_path}) LOGGER.info('Created this ogr command:\n%s' % command) # Now run ogr2ogr ... # noinspection PyProtectedMember self._run_command(command) # Lastly copy over the standard qml (QGIS Style file) for the mmi.tif qml_path = os.path.join( self.output_dir, '%s-points.qml' % self.output_basename) source_qml = resources_path('converter_data', 'mmi-shape.qml') shutil.copyfile(source_qml, qml_path) return shp_path
[ "def", "mmi_to_shapefile", "(", "self", ",", "force_flag", "=", "False", ")", ":", "LOGGER", ".", "debug", "(", "'mmi_to_shapefile requested.'", ")", "shp_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_dir", ",", "'%s-points.shp'", "%"...
Convert grid.xml's mmi column to a vector shp file using ogr2ogr. An ESRI shape file will be created. :param force_flag: bool (Optional). Whether to force the regeneration of the output file. Defaults to False. :return: Path to the resulting tif file. :rtype: str Example of the ogr2ogr call we generate:: ogr2ogr -select mmi -a_srs EPSG:4326 mmi.shp mmi.vrt mmi .. note:: It is assumed that ogr2ogr is in your path.
[ "Convert", "grid", ".", "xml", "s", "mmi", "column", "to", "a", "vector", "shp", "file", "using", "ogr2ogr", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L656-L710
train
26,563
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.create_keyword_file
def create_keyword_file(self, algorithm): """Create keyword file for the raster file created. Basically copy a template from keyword file in converter data and add extra keyword (usually a title) :param algorithm: Which re-sampling algorithm to use. valid options are 'nearest' (for nearest neighbour), 'invdist' (for inverse distance), 'average' (for moving average). Defaults to 'nearest' if not specified. Note that passing re-sampling alg parameters is currently not supported. If None is passed it will be replaced with 'nearest'. :type algorithm: str """ keyword_io = KeywordIO() # Set thresholds for each exposure mmi_default_classes = default_classification_thresholds( earthquake_mmi_scale ) mmi_default_threshold = { earthquake_mmi_scale['key']: { 'active': True, 'classes': mmi_default_classes } } generic_default_classes = default_classification_thresholds( generic_hazard_classes ) generic_default_threshold = { generic_hazard_classes['key']: { 'active': True, 'classes': generic_default_classes } } threshold_keyword = {} for exposure in exposure_all: # Not all exposure is supported by earthquake_mmi_scale if exposure in earthquake_mmi_scale['exposures']: threshold_keyword[exposure['key']] = mmi_default_threshold else: threshold_keyword[ exposure['key']] = generic_default_threshold extra_keywords = { extra_keyword_earthquake_latitude['key']: self.latitude, extra_keyword_earthquake_longitude['key']: self.longitude, extra_keyword_earthquake_magnitude['key']: self.magnitude, extra_keyword_earthquake_depth['key']: self.depth, extra_keyword_earthquake_description['key']: self.description, extra_keyword_earthquake_location['key']: self.location, extra_keyword_earthquake_event_time['key']: self.time.strftime( '%Y-%m-%dT%H:%M:%S'), extra_keyword_time_zone['key']: self.time_zone, extra_keyword_earthquake_x_minimum['key']: self.x_minimum, extra_keyword_earthquake_x_maximum['key']: self.x_maximum, extra_keyword_earthquake_y_minimum['key']: self.y_minimum, extra_keyword_earthquake_y_maximum['key']: self.y_maximum, extra_keyword_earthquake_event_id['key']: self.event_id } for key, value in list(self.extra_keywords.items()): extra_keywords[key] = value # Delete empty element. empty_keys = [] for key, value in list(extra_keywords.items()): if value is None: empty_keys.append(key) for empty_key in empty_keys: extra_keywords.pop(empty_key) keywords = { 'hazard': hazard_earthquake['key'], 'hazard_category': hazard_category_single_event['key'], 'keyword_version': inasafe_keyword_version, 'layer_geometry': layer_geometry_raster['key'], 'layer_mode': layer_mode_continuous['key'], 'layer_purpose': layer_purpose_hazard['key'], 'continuous_hazard_unit': unit_mmi['key'], 'classification': earthquake_mmi_scale['key'], 'thresholds': threshold_keyword, 'extra_keywords': extra_keywords, 'active_band': 1 } if self.algorithm_name: layer_path = os.path.join( self.output_dir, '%s-%s.tif' % ( self.output_basename, algorithm)) else: layer_path = os.path.join( self.output_dir, '%s.tif' % self.output_basename) # append title and source to the keywords file if len(self.title.strip()) == 0: keyword_title = self.output_basename else: keyword_title = self.title keywords['title'] = keyword_title hazard_layer = QgsRasterLayer(layer_path, keyword_title) if not hazard_layer.isValid(): raise InvalidLayerError() keyword_io.write_keywords(hazard_layer, keywords)
python
def create_keyword_file(self, algorithm): """Create keyword file for the raster file created. Basically copy a template from keyword file in converter data and add extra keyword (usually a title) :param algorithm: Which re-sampling algorithm to use. valid options are 'nearest' (for nearest neighbour), 'invdist' (for inverse distance), 'average' (for moving average). Defaults to 'nearest' if not specified. Note that passing re-sampling alg parameters is currently not supported. If None is passed it will be replaced with 'nearest'. :type algorithm: str """ keyword_io = KeywordIO() # Set thresholds for each exposure mmi_default_classes = default_classification_thresholds( earthquake_mmi_scale ) mmi_default_threshold = { earthquake_mmi_scale['key']: { 'active': True, 'classes': mmi_default_classes } } generic_default_classes = default_classification_thresholds( generic_hazard_classes ) generic_default_threshold = { generic_hazard_classes['key']: { 'active': True, 'classes': generic_default_classes } } threshold_keyword = {} for exposure in exposure_all: # Not all exposure is supported by earthquake_mmi_scale if exposure in earthquake_mmi_scale['exposures']: threshold_keyword[exposure['key']] = mmi_default_threshold else: threshold_keyword[ exposure['key']] = generic_default_threshold extra_keywords = { extra_keyword_earthquake_latitude['key']: self.latitude, extra_keyword_earthquake_longitude['key']: self.longitude, extra_keyword_earthquake_magnitude['key']: self.magnitude, extra_keyword_earthquake_depth['key']: self.depth, extra_keyword_earthquake_description['key']: self.description, extra_keyword_earthquake_location['key']: self.location, extra_keyword_earthquake_event_time['key']: self.time.strftime( '%Y-%m-%dT%H:%M:%S'), extra_keyword_time_zone['key']: self.time_zone, extra_keyword_earthquake_x_minimum['key']: self.x_minimum, extra_keyword_earthquake_x_maximum['key']: self.x_maximum, extra_keyword_earthquake_y_minimum['key']: self.y_minimum, extra_keyword_earthquake_y_maximum['key']: self.y_maximum, extra_keyword_earthquake_event_id['key']: self.event_id } for key, value in list(self.extra_keywords.items()): extra_keywords[key] = value # Delete empty element. empty_keys = [] for key, value in list(extra_keywords.items()): if value is None: empty_keys.append(key) for empty_key in empty_keys: extra_keywords.pop(empty_key) keywords = { 'hazard': hazard_earthquake['key'], 'hazard_category': hazard_category_single_event['key'], 'keyword_version': inasafe_keyword_version, 'layer_geometry': layer_geometry_raster['key'], 'layer_mode': layer_mode_continuous['key'], 'layer_purpose': layer_purpose_hazard['key'], 'continuous_hazard_unit': unit_mmi['key'], 'classification': earthquake_mmi_scale['key'], 'thresholds': threshold_keyword, 'extra_keywords': extra_keywords, 'active_band': 1 } if self.algorithm_name: layer_path = os.path.join( self.output_dir, '%s-%s.tif' % ( self.output_basename, algorithm)) else: layer_path = os.path.join( self.output_dir, '%s.tif' % self.output_basename) # append title and source to the keywords file if len(self.title.strip()) == 0: keyword_title = self.output_basename else: keyword_title = self.title keywords['title'] = keyword_title hazard_layer = QgsRasterLayer(layer_path, keyword_title) if not hazard_layer.isValid(): raise InvalidLayerError() keyword_io.write_keywords(hazard_layer, keywords)
[ "def", "create_keyword_file", "(", "self", ",", "algorithm", ")", ":", "keyword_io", "=", "KeywordIO", "(", ")", "# Set thresholds for each exposure", "mmi_default_classes", "=", "default_classification_thresholds", "(", "earthquake_mmi_scale", ")", "mmi_default_threshold", ...
Create keyword file for the raster file created. Basically copy a template from keyword file in converter data and add extra keyword (usually a title) :param algorithm: Which re-sampling algorithm to use. valid options are 'nearest' (for nearest neighbour), 'invdist' (for inverse distance), 'average' (for moving average). Defaults to 'nearest' if not specified. Note that passing re-sampling alg parameters is currently not supported. If None is passed it will be replaced with 'nearest'. :type algorithm: str
[ "Create", "keyword", "file", "for", "the", "raster", "file", "created", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L850-L956
train
26,564
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
ShakeGrid.mmi_to_ascii
def mmi_to_ascii(self, force_flag=False): """Convert grid.xml mmi column to a ascii raster file.""" ascii_path = os.path.join( self.output_dir, '%s.asc' % self.output_basename) # Short circuit if the tif is already created. if os.path.exists(ascii_path) and force_flag is not True: return ascii_path cell_size = (self.x_maximum - self.x_minimum) / (self.rows - 1) asc_file = open(ascii_path, 'w') asc_file.write('ncols %d\n' % self.columns) asc_file.write('nrows %d\n' % self.rows) asc_file.write('xllcorner %.3f\n' % self.x_minimum) asc_file.write('yllcorner %.3f\n' % self.y_minimum) asc_file.write('cellsize %.3f\n' % cell_size) asc_file.write('nodata_value -9999\n') cell_string = '' cell_values = np.reshape( [v[2] for v in self.mmi_data], (self.rows, self.columns)) for i in range(self.rows): for j in range(self.columns): cell_string += '%.3f ' % cell_values[i][j] cell_string += '\n' asc_file.write(cell_string) asc_file.close() return ascii_path
python
def mmi_to_ascii(self, force_flag=False): """Convert grid.xml mmi column to a ascii raster file.""" ascii_path = os.path.join( self.output_dir, '%s.asc' % self.output_basename) # Short circuit if the tif is already created. if os.path.exists(ascii_path) and force_flag is not True: return ascii_path cell_size = (self.x_maximum - self.x_minimum) / (self.rows - 1) asc_file = open(ascii_path, 'w') asc_file.write('ncols %d\n' % self.columns) asc_file.write('nrows %d\n' % self.rows) asc_file.write('xllcorner %.3f\n' % self.x_minimum) asc_file.write('yllcorner %.3f\n' % self.y_minimum) asc_file.write('cellsize %.3f\n' % cell_size) asc_file.write('nodata_value -9999\n') cell_string = '' cell_values = np.reshape( [v[2] for v in self.mmi_data], (self.rows, self.columns)) for i in range(self.rows): for j in range(self.columns): cell_string += '%.3f ' % cell_values[i][j] cell_string += '\n' asc_file.write(cell_string) asc_file.close() return ascii_path
[ "def", "mmi_to_ascii", "(", "self", ",", "force_flag", "=", "False", ")", ":", "ascii_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_dir", ",", "'%s.asc'", "%", "self", ".", "output_basename", ")", "# Short circuit if the tif is already ...
Convert grid.xml mmi column to a ascii raster file.
[ "Convert", "grid", ".", "xml", "mmi", "column", "to", "a", "ascii", "raster", "file", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L958-L987
train
26,565
inasafe/inasafe
safe/gui/tools/wizard/step_fc85_summary.py
StepFcSummary.set_widgets
def set_widgets(self): """Set widgets on the Summary tab.""" if self.parent.aggregation_layer: aggr = self.parent.aggregation_layer.name() else: aggr = self.tr('no aggregation') html = self.tr('Please ensure the following information ' 'is correct and press Run.') # TODO: update this to use InaSAFE message API rather... html += '<br/><table cellspacing="4">' html += ('<tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td colspan="3"></td>' '</tr>' % ( self.tr('hazard layer').capitalize().replace( ' ', '&nbsp;'), self.parent.hazard_layer.name(), self.tr('exposure layer').capitalize().replace( ' ', '&nbsp;'), self.parent.exposure_layer.name(), self.tr('aggregation layer').capitalize().replace( ' ', '&nbsp;'), aggr)) self.lblSummary.setText(html)
python
def set_widgets(self): """Set widgets on the Summary tab.""" if self.parent.aggregation_layer: aggr = self.parent.aggregation_layer.name() else: aggr = self.tr('no aggregation') html = self.tr('Please ensure the following information ' 'is correct and press Run.') # TODO: update this to use InaSAFE message API rather... html += '<br/><table cellspacing="4">' html += ('<tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td colspan="3"></td>' '</tr>' % ( self.tr('hazard layer').capitalize().replace( ' ', '&nbsp;'), self.parent.hazard_layer.name(), self.tr('exposure layer').capitalize().replace( ' ', '&nbsp;'), self.parent.exposure_layer.name(), self.tr('aggregation layer').capitalize().replace( ' ', '&nbsp;'), aggr)) self.lblSummary.setText(html)
[ "def", "set_widgets", "(", "self", ")", ":", "if", "self", ".", "parent", ".", "aggregation_layer", ":", "aggr", "=", "self", ".", "parent", ".", "aggregation_layer", ".", "name", "(", ")", "else", ":", "aggr", "=", "self", ".", "tr", "(", "'no aggrega...
Set widgets on the Summary tab.
[ "Set", "widgets", "on", "the", "Summary", "tab", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc85_summary.py#L40-L70
train
26,566
inasafe/inasafe
safe/gis/generic_expressions.py
inasafe_analysis_summary_field_value
def inasafe_analysis_summary_field_value(field, feature, parent): """Retrieve a value from a field in the analysis summary layer. e.g. inasafe_analysis_summary_field_value('total_not_exposed') -> 3 """ _ = feature, parent # NOQA project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) registry = QgsProject.instance() key = provenance_layer_analysis_impacted_id['provenance_key'] if not project_context_scope.hasVariable(key): return None layer = registry.mapLayer(project_context_scope.variable(key)) if not layer: return None index = layer.fields().lookupField(field) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
python
def inasafe_analysis_summary_field_value(field, feature, parent): """Retrieve a value from a field in the analysis summary layer. e.g. inasafe_analysis_summary_field_value('total_not_exposed') -> 3 """ _ = feature, parent # NOQA project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) registry = QgsProject.instance() key = provenance_layer_analysis_impacted_id['provenance_key'] if not project_context_scope.hasVariable(key): return None layer = registry.mapLayer(project_context_scope.variable(key)) if not layer: return None index = layer.fields().lookupField(field) if index < 0: return None feature = next(layer.getFeatures()) return feature[index]
[ "def", "inasafe_analysis_summary_field_value", "(", "field", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "project_context_scope", "=", "QgsExpressionContextUtils", ".", "projectScope", "(", "QgsProject", ".", "instance", "(...
Retrieve a value from a field in the analysis summary layer. e.g. inasafe_analysis_summary_field_value('total_not_exposed') -> 3
[ "Retrieve", "a", "value", "from", "a", "field", "in", "the", "analysis", "summary", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/generic_expressions.py#L50-L74
train
26,567
inasafe/inasafe
safe/gis/generic_expressions.py
inasafe_sub_analysis_summary_field_value
def inasafe_sub_analysis_summary_field_value( exposure_key, field, feature, parent): """Retrieve a value from field in the specified exposure analysis layer. """ _ = feature, parent # NOQA project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) project = QgsProject.instance() key = ('{provenance}__{exposure}').format( provenance=provenance_multi_exposure_analysis_summary_layers_id[ 'provenance_key'], exposure=exposure_key) if not project_context_scope.hasVariable(key): return None analysis_summary_layer = project.mapLayer( project_context_scope.variable(key)) if not analysis_summary_layer: return None index = analysis_summary_layer.fields().lookupField(field) if index < 0: return None feature = next(analysis_summary_layer.getFeatures()) return feature[index]
python
def inasafe_sub_analysis_summary_field_value( exposure_key, field, feature, parent): """Retrieve a value from field in the specified exposure analysis layer. """ _ = feature, parent # NOQA project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) project = QgsProject.instance() key = ('{provenance}__{exposure}').format( provenance=provenance_multi_exposure_analysis_summary_layers_id[ 'provenance_key'], exposure=exposure_key) if not project_context_scope.hasVariable(key): return None analysis_summary_layer = project.mapLayer( project_context_scope.variable(key)) if not analysis_summary_layer: return None index = analysis_summary_layer.fields().lookupField(field) if index < 0: return None feature = next(analysis_summary_layer.getFeatures()) return feature[index]
[ "def", "inasafe_sub_analysis_summary_field_value", "(", "exposure_key", ",", "field", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "project_context_scope", "=", "QgsExpressionContextUtils", ".", "projectScope", "(", "QgsProjec...
Retrieve a value from field in the specified exposure analysis layer.
[ "Retrieve", "a", "value", "from", "field", "in", "the", "specified", "exposure", "analysis", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/generic_expressions.py#L89-L116
train
26,568
inasafe/inasafe
safe/gis/generic_expressions.py
inasafe_exposure_summary_field_values
def inasafe_exposure_summary_field_values(field, feature, parent): """Retrieve all values from a field in the exposure summary layer. """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField(field) if index < 0: return None values = [] for feat in layer.getFeatures(): value = feat[index] values.append(value) return str(values)
python
def inasafe_exposure_summary_field_values(field, feature, parent): """Retrieve all values from a field in the exposure summary layer. """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return None index = layer.fields().lookupField(field) if index < 0: return None values = [] for feat in layer.getFeatures(): value = feat[index] values.append(value) return str(values)
[ "def", "inasafe_exposure_summary_field_values", "(", "field", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "layer", "=", "exposure_summary_layer", "(", ")", "if", "not", "layer", ":", "return", "None", "index", "=", ...
Retrieve all values from a field in the exposure summary layer.
[ "Retrieve", "all", "values", "from", "a", "field", "in", "the", "exposure", "summary", "layer", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/generic_expressions.py#L130-L148
train
26,569
inasafe/inasafe
safe/gis/generic_expressions.py
inasafe_place_value_name
def inasafe_place_value_name(number, feature, parent): """Given a number, it will return the place value name. For instance: * inasafe_place_value_name(10) -> Ten \n * inasafe_place_value_name(1700) -> Thousand It needs to be used with inasafe_place_value_coefficient. """ _ = feature, parent # NOQA if number is None: return None rounded_number = round_affected_number( number, use_rounding=True, use_population_rounding=True ) value, unit = denomination(rounded_number, 1000) if not unit: return None else: return unit['name']
python
def inasafe_place_value_name(number, feature, parent): """Given a number, it will return the place value name. For instance: * inasafe_place_value_name(10) -> Ten \n * inasafe_place_value_name(1700) -> Thousand It needs to be used with inasafe_place_value_coefficient. """ _ = feature, parent # NOQA if number is None: return None rounded_number = round_affected_number( number, use_rounding=True, use_population_rounding=True ) value, unit = denomination(rounded_number, 1000) if not unit: return None else: return unit['name']
[ "def", "inasafe_place_value_name", "(", "number", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "if", "number", "is", "None", ":", "return", "None", "rounded_number", "=", "round_affected_number", "(", "number", ",", ...
Given a number, it will return the place value name. For instance: * inasafe_place_value_name(10) -> Ten \n * inasafe_place_value_name(1700) -> Thousand It needs to be used with inasafe_place_value_coefficient.
[ "Given", "a", "number", "it", "will", "return", "the", "place", "value", "name", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/generic_expressions.py#L164-L185
train
26,570
inasafe/inasafe
safe/gis/generic_expressions.py
inasafe_place_value_coefficient
def inasafe_place_value_coefficient(number, feature, parent): """Given a number, it will return the coefficient of the place value name. For instance: * inasafe_place_value_coefficient(10) -> 1 * inasafe_place_value_coefficient(1700) -> 1.7 It needs to be used with inasafe_number_denomination_unit. """ _ = feature, parent # NOQA if number >= 0: rounded_number = round_affected_number( number, use_rounding=True, use_population_rounding=True ) min_number = 1000 value, unit = denomination(rounded_number, min_number) if number < min_number: rounded_number = int(round(value, 1)) else: rounded_number = round(value, 1) return str(rounded_number) else: return None
python
def inasafe_place_value_coefficient(number, feature, parent): """Given a number, it will return the coefficient of the place value name. For instance: * inasafe_place_value_coefficient(10) -> 1 * inasafe_place_value_coefficient(1700) -> 1.7 It needs to be used with inasafe_number_denomination_unit. """ _ = feature, parent # NOQA if number >= 0: rounded_number = round_affected_number( number, use_rounding=True, use_population_rounding=True ) min_number = 1000 value, unit = denomination(rounded_number, min_number) if number < min_number: rounded_number = int(round(value, 1)) else: rounded_number = round(value, 1) return str(rounded_number) else: return None
[ "def", "inasafe_place_value_coefficient", "(", "number", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "if", "number", ">=", "0", ":", "rounded_number", "=", "round_affected_number", "(", "number", ",", "use_rounding", ...
Given a number, it will return the coefficient of the place value name. For instance: * inasafe_place_value_coefficient(10) -> 1 * inasafe_place_value_coefficient(1700) -> 1.7 It needs to be used with inasafe_number_denomination_unit.
[ "Given", "a", "number", "it", "will", "return", "the", "coefficient", "of", "the", "place", "value", "name", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/generic_expressions.py#L201-L226
train
26,571
inasafe/inasafe
safe/gis/generic_expressions.py
inasafe_place_value_percentage
def inasafe_place_value_percentage(number, total, feature, parent): """Given a number and total, it will return the percentage of the number to the total. For instance: * inasafe_place_value_percentage(inasafe_analysis_summary_field_value( 'female_displaced'), inasafe_analysis_summary_field_value('displaced')) -> will calculate the percentage of female displaced count to total displaced count. It also can be used by pure number (int, float). """ _ = feature, parent # NOQA if number < 0: return None percentage_format = '{percentage}%' percentage = round((float(number) / float(total)) * 100, 1) return percentage_format.format(percentage=percentage)
python
def inasafe_place_value_percentage(number, total, feature, parent): """Given a number and total, it will return the percentage of the number to the total. For instance: * inasafe_place_value_percentage(inasafe_analysis_summary_field_value( 'female_displaced'), inasafe_analysis_summary_field_value('displaced')) -> will calculate the percentage of female displaced count to total displaced count. It also can be used by pure number (int, float). """ _ = feature, parent # NOQA if number < 0: return None percentage_format = '{percentage}%' percentage = round((float(number) / float(total)) * 100, 1) return percentage_format.format(percentage=percentage)
[ "def", "inasafe_place_value_percentage", "(", "number", ",", "total", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "if", "number", "<", "0", ":", "return", "None", "percentage_format", "=", "'{percentage}%'", "percenta...
Given a number and total, it will return the percentage of the number to the total. For instance: * inasafe_place_value_percentage(inasafe_analysis_summary_field_value( 'female_displaced'), inasafe_analysis_summary_field_value('displaced')) -> will calculate the percentage of female displaced count to total displaced count. It also can be used by pure number (int, float).
[ "Given", "a", "number", "and", "total", "it", "will", "return", "the", "percentage", "of", "the", "number", "to", "the", "total", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/generic_expressions.py#L246-L263
train
26,572
inasafe/inasafe
safe/gis/generic_expressions.py
beautify_date
def beautify_date(inasafe_time, feature, parent): """Given an InaSAFE analysis time, it will convert it to a date with year-month-date format. For instance: * beautify_date( @start_datetime ) -> will convert datetime provided by qgis_variable. """ _ = feature, parent # NOQA datetime_object = parse(inasafe_time) date = datetime_object.strftime('%Y-%m-%d') return date
python
def beautify_date(inasafe_time, feature, parent): """Given an InaSAFE analysis time, it will convert it to a date with year-month-date format. For instance: * beautify_date( @start_datetime ) -> will convert datetime provided by qgis_variable. """ _ = feature, parent # NOQA datetime_object = parse(inasafe_time) date = datetime_object.strftime('%Y-%m-%d') return date
[ "def", "beautify_date", "(", "inasafe_time", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "datetime_object", "=", "parse", "(", "inasafe_time", ")", "date", "=", "datetime_object", ".", "strftime", "(", "'%Y-%m-%d'", ...
Given an InaSAFE analysis time, it will convert it to a date with year-month-date format. For instance: * beautify_date( @start_datetime ) -> will convert datetime provided by qgis_variable.
[ "Given", "an", "InaSAFE", "analysis", "time", "it", "will", "convert", "it", "to", "a", "date", "with", "year", "-", "month", "-", "date", "format", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/generic_expressions.py#L279-L290
train
26,573
inasafe/inasafe
safe/gis/generic_expressions.py
hazard_extra_keyword
def hazard_extra_keyword(keyword, feature, parent): """Given a keyword, it will return the value of the keyword from the hazard layer's extra keywords. For instance: * hazard_extra_keyword( 'depth' ) -> will return the value of 'depth' in current hazard layer's extra keywords. """ _ = feature, parent # NOQA hazard_layer_path = QgsExpressionContextUtils. \ projectScope(QgsProject.instance()).variable( 'hazard_layer') hazard_layer = load_layer(hazard_layer_path)[0] keywords = KeywordIO.read_keywords(hazard_layer) extra_keywords = keywords.get('extra_keywords') if extra_keywords: value = extra_keywords.get(keyword) if value: value_definition = definition(value) if value_definition: return value_definition['name'] return value else: return tr('Keyword %s is not found' % keyword) return tr('No extra keywords found')
python
def hazard_extra_keyword(keyword, feature, parent): """Given a keyword, it will return the value of the keyword from the hazard layer's extra keywords. For instance: * hazard_extra_keyword( 'depth' ) -> will return the value of 'depth' in current hazard layer's extra keywords. """ _ = feature, parent # NOQA hazard_layer_path = QgsExpressionContextUtils. \ projectScope(QgsProject.instance()).variable( 'hazard_layer') hazard_layer = load_layer(hazard_layer_path)[0] keywords = KeywordIO.read_keywords(hazard_layer) extra_keywords = keywords.get('extra_keywords') if extra_keywords: value = extra_keywords.get(keyword) if value: value_definition = definition(value) if value_definition: return value_definition['name'] return value else: return tr('Keyword %s is not found' % keyword) return tr('No extra keywords found')
[ "def", "hazard_extra_keyword", "(", "keyword", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "hazard_layer_path", "=", "QgsExpressionContextUtils", ".", "projectScope", "(", "QgsProject", ".", "instance", "(", ")", ")", ...
Given a keyword, it will return the value of the keyword from the hazard layer's extra keywords. For instance: * hazard_extra_keyword( 'depth' ) -> will return the value of 'depth' in current hazard layer's extra keywords.
[ "Given", "a", "keyword", "it", "will", "return", "the", "value", "of", "the", "keyword", "from", "the", "hazard", "layer", "s", "extra", "keywords", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/generic_expressions.py#L339-L363
train
26,574
inasafe/inasafe
safe/messaging/item/numbered_list.py
NumberedList.to_html
def to_html(self): """Render a Text MessageElement as html Args: None Returns: Str the html representation of the Text MessageElement Raises: Errors are propagated """ if self.items is None: return else: html = '<ol%s>\n' % self.html_attributes() for item in self.items: html += '<li>%s</li>\n' % item.to_html() html += '</ol>' return html
python
def to_html(self): """Render a Text MessageElement as html Args: None Returns: Str the html representation of the Text MessageElement Raises: Errors are propagated """ if self.items is None: return else: html = '<ol%s>\n' % self.html_attributes() for item in self.items: html += '<li>%s</li>\n' % item.to_html() html += '</ol>' return html
[ "def", "to_html", "(", "self", ")", ":", "if", "self", ".", "items", "is", "None", ":", "return", "else", ":", "html", "=", "'<ol%s>\\n'", "%", "self", ".", "html_attributes", "(", ")", "for", "item", "in", "self", ".", "items", ":", "html", "+=", ...
Render a Text MessageElement as html Args: None Returns: Str the html representation of the Text MessageElement Raises: Errors are propagated
[ "Render", "a", "Text", "MessageElement", "as", "html" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/numbered_list.py#L51-L70
train
26,575
inasafe/inasafe
safe/gis/vector/prepare_vector_layer.py
_check_value_mapping
def _check_value_mapping(layer, exposure_key=None): """Loop over the exposure type field and check if the value map is correct. :param layer: The layer :type layer: QgsVectorLayer :param exposure_key: The exposure key. :type exposure_key: str """ index = layer.fields().lookupField(exposure_type_field['field_name']) unique_exposure = layer.uniqueValues(index) if layer.keywords['layer_purpose'] == layer_purpose_hazard['key']: if not exposure_key: message = tr('Hazard value mapping missing exposure key.') raise InvalidKeywordsForProcessingAlgorithm(message) value_map = active_thresholds_value_maps(layer.keywords, exposure_key) else: value_map = layer.keywords.get('value_map') if not value_map: # The exposure do not have a value_map, we can skip the layer. return layer if layer.keywords['layer_purpose'] == layer_purpose_hazard['key']: if not exposure_key: message = tr('Hazard classification is missing exposure key.') raise InvalidKeywordsForProcessingAlgorithm(message) classification = active_classification(layer.keywords, exposure_key) else: classification = layer.keywords['classification'] exposure_classification = definition(classification) other = None if exposure_classification['key'] != data_driven_classes['key']: other = exposure_classification['classes'][-1]['key'] exposure_mapped = [] for group in list(value_map.values()): exposure_mapped.extend(group) diff = list(unique_exposure - set(exposure_mapped)) if other in list(value_map.keys()): value_map[other].extend(diff) else: value_map[other] = diff layer.keywords['value_map'] = value_map layer.keywords['classification'] = classification return layer
python
def _check_value_mapping(layer, exposure_key=None): """Loop over the exposure type field and check if the value map is correct. :param layer: The layer :type layer: QgsVectorLayer :param exposure_key: The exposure key. :type exposure_key: str """ index = layer.fields().lookupField(exposure_type_field['field_name']) unique_exposure = layer.uniqueValues(index) if layer.keywords['layer_purpose'] == layer_purpose_hazard['key']: if not exposure_key: message = tr('Hazard value mapping missing exposure key.') raise InvalidKeywordsForProcessingAlgorithm(message) value_map = active_thresholds_value_maps(layer.keywords, exposure_key) else: value_map = layer.keywords.get('value_map') if not value_map: # The exposure do not have a value_map, we can skip the layer. return layer if layer.keywords['layer_purpose'] == layer_purpose_hazard['key']: if not exposure_key: message = tr('Hazard classification is missing exposure key.') raise InvalidKeywordsForProcessingAlgorithm(message) classification = active_classification(layer.keywords, exposure_key) else: classification = layer.keywords['classification'] exposure_classification = definition(classification) other = None if exposure_classification['key'] != data_driven_classes['key']: other = exposure_classification['classes'][-1]['key'] exposure_mapped = [] for group in list(value_map.values()): exposure_mapped.extend(group) diff = list(unique_exposure - set(exposure_mapped)) if other in list(value_map.keys()): value_map[other].extend(diff) else: value_map[other] = diff layer.keywords['value_map'] = value_map layer.keywords['classification'] = classification return layer
[ "def", "_check_value_mapping", "(", "layer", ",", "exposure_key", "=", "None", ")", ":", "index", "=", "layer", ".", "fields", "(", ")", ".", "lookupField", "(", "exposure_type_field", "[", "'field_name'", "]", ")", "unique_exposure", "=", "layer", ".", "uni...
Loop over the exposure type field and check if the value map is correct. :param layer: The layer :type layer: QgsVectorLayer :param exposure_key: The exposure key. :type exposure_key: str
[ "Loop", "over", "the", "exposure", "type", "field", "and", "check", "if", "the", "value", "map", "is", "correct", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/prepare_vector_layer.py#L132-L182
train
26,576
inasafe/inasafe
safe/gis/vector/prepare_vector_layer.py
clean_inasafe_fields
def clean_inasafe_fields(layer): """Clean inasafe_fields based on keywords. 1. Must use standard field names. 2. Sum up list of fields' value and put in the standard field name. 3. Remove un-used fields. :param layer: The layer :type layer: QgsVectorLayer """ fields = [] # Exposure if layer.keywords['layer_purpose'] == layer_purpose_exposure['key']: fields = get_fields( layer.keywords['layer_purpose'], layer.keywords['exposure']) # Hazard elif layer.keywords['layer_purpose'] == layer_purpose_hazard['key']: fields = get_fields( layer.keywords['layer_purpose'], layer.keywords['hazard']) # Aggregation elif layer.keywords['layer_purpose'] == layer_purpose_aggregation['key']: fields = get_fields( layer.keywords['layer_purpose']) # Add displaced_field definition to expected_fields # for minimum needs calculator. # If there is no displaced_field keyword, then pass try: if layer.keywords['inasafe_fields'][displaced_field['key']]: fields.append(displaced_field) except KeyError: pass expected_fields = {field['key']: field['field_name'] for field in fields} # Convert the field name and sum up if needed new_keywords = {} for key, val in list(layer.keywords.get('inasafe_fields').items()): if key in expected_fields: if isinstance(val, str): val = [val] sum_fields(layer, key, val) new_keywords[key] = expected_fields[key] # Houra, InaSAFE keywords match our concepts ! layer.keywords['inasafe_fields'].update(new_keywords) to_remove = [] # Remove unnecessary fields (the one that is not in the inasafe_fields) for field in layer.fields().toList(): if field.name() not in list(layer.keywords['inasafe_fields'].values()): to_remove.append(field.name()) remove_fields(layer, to_remove) LOGGER.debug( 'Fields which have been removed from %s : %s' % (layer.keywords['layer_purpose'], ' '.join(to_remove)))
python
def clean_inasafe_fields(layer): """Clean inasafe_fields based on keywords. 1. Must use standard field names. 2. Sum up list of fields' value and put in the standard field name. 3. Remove un-used fields. :param layer: The layer :type layer: QgsVectorLayer """ fields = [] # Exposure if layer.keywords['layer_purpose'] == layer_purpose_exposure['key']: fields = get_fields( layer.keywords['layer_purpose'], layer.keywords['exposure']) # Hazard elif layer.keywords['layer_purpose'] == layer_purpose_hazard['key']: fields = get_fields( layer.keywords['layer_purpose'], layer.keywords['hazard']) # Aggregation elif layer.keywords['layer_purpose'] == layer_purpose_aggregation['key']: fields = get_fields( layer.keywords['layer_purpose']) # Add displaced_field definition to expected_fields # for minimum needs calculator. # If there is no displaced_field keyword, then pass try: if layer.keywords['inasafe_fields'][displaced_field['key']]: fields.append(displaced_field) except KeyError: pass expected_fields = {field['key']: field['field_name'] for field in fields} # Convert the field name and sum up if needed new_keywords = {} for key, val in list(layer.keywords.get('inasafe_fields').items()): if key in expected_fields: if isinstance(val, str): val = [val] sum_fields(layer, key, val) new_keywords[key] = expected_fields[key] # Houra, InaSAFE keywords match our concepts ! layer.keywords['inasafe_fields'].update(new_keywords) to_remove = [] # Remove unnecessary fields (the one that is not in the inasafe_fields) for field in layer.fields().toList(): if field.name() not in list(layer.keywords['inasafe_fields'].values()): to_remove.append(field.name()) remove_fields(layer, to_remove) LOGGER.debug( 'Fields which have been removed from %s : %s' % (layer.keywords['layer_purpose'], ' '.join(to_remove)))
[ "def", "clean_inasafe_fields", "(", "layer", ")", ":", "fields", "=", "[", "]", "# Exposure", "if", "layer", ".", "keywords", "[", "'layer_purpose'", "]", "==", "layer_purpose_exposure", "[", "'key'", "]", ":", "fields", "=", "get_fields", "(", "layer", ".",...
Clean inasafe_fields based on keywords. 1. Must use standard field names. 2. Sum up list of fields' value and put in the standard field name. 3. Remove un-used fields. :param layer: The layer :type layer: QgsVectorLayer
[ "Clean", "inasafe_fields", "based", "on", "keywords", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/prepare_vector_layer.py#L186-L243
train
26,577
inasafe/inasafe
safe/gis/vector/prepare_vector_layer.py
_size_is_needed
def _size_is_needed(layer): """Checker if we need the size field. :param layer: The layer to test. :type layer: QgsVectorLayer :return: If we need the size field. :rtype: bool """ exposure = layer.keywords.get('exposure') if not exposure: # The layer is not an exposure. return False indivisible_exposure_keys = [f['key'] for f in indivisible_exposure] if exposure in indivisible_exposure_keys: # The exposure is not divisible, We don't need to compute the size. return False if layer.geometryType() == QgsWkbTypes.PointGeometry: # The exposure is a point layer. We don't need to compute the size. return False # The layer is divisible and not a point layer. # We need to check if some fields are absolute. fields = layer.keywords['inasafe_fields'] absolute_field_keys = [f['key'] for f in count_fields] for field in fields: if field in absolute_field_keys: return True else: return False
python
def _size_is_needed(layer): """Checker if we need the size field. :param layer: The layer to test. :type layer: QgsVectorLayer :return: If we need the size field. :rtype: bool """ exposure = layer.keywords.get('exposure') if not exposure: # The layer is not an exposure. return False indivisible_exposure_keys = [f['key'] for f in indivisible_exposure] if exposure in indivisible_exposure_keys: # The exposure is not divisible, We don't need to compute the size. return False if layer.geometryType() == QgsWkbTypes.PointGeometry: # The exposure is a point layer. We don't need to compute the size. return False # The layer is divisible and not a point layer. # We need to check if some fields are absolute. fields = layer.keywords['inasafe_fields'] absolute_field_keys = [f['key'] for f in count_fields] for field in fields: if field in absolute_field_keys: return True else: return False
[ "def", "_size_is_needed", "(", "layer", ")", ":", "exposure", "=", "layer", ".", "keywords", ".", "get", "(", "'exposure'", ")", "if", "not", "exposure", ":", "# The layer is not an exposure.", "return", "False", "indivisible_exposure_keys", "=", "[", "f", "[", ...
Checker if we need the size field. :param layer: The layer to test. :type layer: QgsVectorLayer :return: If we need the size field. :rtype: bool
[ "Checker", "if", "we", "need", "the", "size", "field", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/prepare_vector_layer.py#L246-L280
train
26,578
inasafe/inasafe
safe/gis/vector/prepare_vector_layer.py
_remove_features
def _remove_features(layer): """Remove features which do not have information for InaSAFE or an invalid geometry. :param layer: The vector layer. :type layer: QgsVectorLayer """ # Get the layer purpose of the layer. layer_purpose = layer.keywords['layer_purpose'] layer_subcategory = layer.keywords.get(layer_purpose) compulsory_field = get_compulsory_fields(layer_purpose, layer_subcategory) inasafe_fields = layer.keywords['inasafe_fields'] # Compulsory fields can be list of field name or single field name. # We need to iterate through all of them field_names = inasafe_fields.get(compulsory_field['key']) if not isinstance(field_names, list): field_names = [field_names] for field_name in field_names: if not field_name: message = 'Keyword %s is missing from %s' % ( compulsory_field['key'], layer_purpose) raise InvalidKeywordsForProcessingAlgorithm(message) index = layer.fields().lookupField(field_name) request = QgsFeatureRequest() request.setSubsetOfAttributes([field_name], layer.fields()) layer.startEditing() i = 0 for feature in layer.getFeatures(request): feat_attr = feature.attributes()[index] if (feat_attr is None or (hasattr(feat_attr, 'isNull') and feat_attr.isNull())): if layer_purpose == 'hazard': # Remove the feature if the hazard is null. layer.deleteFeature(feature.id()) i += 1 elif layer_purpose == 'aggregation': # Put the ID if the value is null. layer.changeAttributeValue( feature.id(), index, str(feature.id())) elif layer_purpose == 'exposure': # Put an empty value, the value mapping will take care of # it in the 'other' group. layer.changeAttributeValue( feature.id(), index, '') # Check if there is en empty geometry. geometry = feature.geometry() if not geometry: layer.deleteFeature(feature.id()) i += 1 continue # Check if the geometry is empty. if geometry.isEmpty(): layer.deleteFeature(feature.id()) i += 1 continue # Check if the geometry is valid. if not geometry.isGeosValid(): # polygonize can produce some invalid geometries # For instance a polygon like this, sharing a same point : # _______ # | ___|__ # | |__| | # |________| # layer.deleteFeature(feature.id()) # i += 1 pass # TODO We need to add more tests # like checking if the value is in the value_mapping. layer.commitChanges() if i: LOGGER.critical( 'Features which have been removed from %s : %s' % (layer.keywords['layer_purpose'], i)) else: LOGGER.info( 'No feature has been removed from %s during the vector layer ' 'preparation' % layer.keywords['layer_purpose'])
python
def _remove_features(layer): """Remove features which do not have information for InaSAFE or an invalid geometry. :param layer: The vector layer. :type layer: QgsVectorLayer """ # Get the layer purpose of the layer. layer_purpose = layer.keywords['layer_purpose'] layer_subcategory = layer.keywords.get(layer_purpose) compulsory_field = get_compulsory_fields(layer_purpose, layer_subcategory) inasafe_fields = layer.keywords['inasafe_fields'] # Compulsory fields can be list of field name or single field name. # We need to iterate through all of them field_names = inasafe_fields.get(compulsory_field['key']) if not isinstance(field_names, list): field_names = [field_names] for field_name in field_names: if not field_name: message = 'Keyword %s is missing from %s' % ( compulsory_field['key'], layer_purpose) raise InvalidKeywordsForProcessingAlgorithm(message) index = layer.fields().lookupField(field_name) request = QgsFeatureRequest() request.setSubsetOfAttributes([field_name], layer.fields()) layer.startEditing() i = 0 for feature in layer.getFeatures(request): feat_attr = feature.attributes()[index] if (feat_attr is None or (hasattr(feat_attr, 'isNull') and feat_attr.isNull())): if layer_purpose == 'hazard': # Remove the feature if the hazard is null. layer.deleteFeature(feature.id()) i += 1 elif layer_purpose == 'aggregation': # Put the ID if the value is null. layer.changeAttributeValue( feature.id(), index, str(feature.id())) elif layer_purpose == 'exposure': # Put an empty value, the value mapping will take care of # it in the 'other' group. layer.changeAttributeValue( feature.id(), index, '') # Check if there is en empty geometry. geometry = feature.geometry() if not geometry: layer.deleteFeature(feature.id()) i += 1 continue # Check if the geometry is empty. if geometry.isEmpty(): layer.deleteFeature(feature.id()) i += 1 continue # Check if the geometry is valid. if not geometry.isGeosValid(): # polygonize can produce some invalid geometries # For instance a polygon like this, sharing a same point : # _______ # | ___|__ # | |__| | # |________| # layer.deleteFeature(feature.id()) # i += 1 pass # TODO We need to add more tests # like checking if the value is in the value_mapping. layer.commitChanges() if i: LOGGER.critical( 'Features which have been removed from %s : %s' % (layer.keywords['layer_purpose'], i)) else: LOGGER.info( 'No feature has been removed from %s during the vector layer ' 'preparation' % layer.keywords['layer_purpose'])
[ "def", "_remove_features", "(", "layer", ")", ":", "# Get the layer purpose of the layer.", "layer_purpose", "=", "layer", ".", "keywords", "[", "'layer_purpose'", "]", "layer_subcategory", "=", "layer", ".", "keywords", ".", "get", "(", "layer_purpose", ")", "compu...
Remove features which do not have information for InaSAFE or an invalid geometry. :param layer: The vector layer. :type layer: QgsVectorLayer
[ "Remove", "features", "which", "do", "not", "have", "information", "for", "InaSAFE", "or", "an", "invalid", "geometry", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/prepare_vector_layer.py#L284-L368
train
26,579
inasafe/inasafe
safe/gis/vector/prepare_vector_layer.py
_add_id_column
def _add_id_column(layer): """Add an ID column if it's not present in the attribute table. :param layer: The vector layer. :type layer: QgsVectorLayer """ layer_purpose = layer.keywords['layer_purpose'] mapping = { layer_purpose_exposure['key']: exposure_id_field, layer_purpose_hazard['key']: hazard_id_field, layer_purpose_aggregation['key']: aggregation_id_field } has_id_column = False for layer_type, field in list(mapping.items()): if layer_purpose == layer_type: safe_id = field if layer.keywords['inasafe_fields'].get(field['key']): has_id_column = True break if not has_id_column: LOGGER.info( 'We add an ID column in {purpose}'.format(purpose=layer_purpose)) layer.startEditing() id_field = QgsField() id_field.setName(safe_id['field_name']) if isinstance(safe_id['type'], list): # Use the first element in the list of type id_field.setType(safe_id['type'][0]) else: id_field.setType(safe_id['type'][0]) id_field.setPrecision(safe_id['precision']) id_field.setLength(safe_id['length']) layer.addAttribute(id_field) new_index = layer.fields().lookupField(id_field.name()) for feature in layer.getFeatures(): layer.changeAttributeValue( feature.id(), new_index, feature.id()) layer.commitChanges() layer.keywords['inasafe_fields'][safe_id['key']] = ( safe_id['field_name'])
python
def _add_id_column(layer): """Add an ID column if it's not present in the attribute table. :param layer: The vector layer. :type layer: QgsVectorLayer """ layer_purpose = layer.keywords['layer_purpose'] mapping = { layer_purpose_exposure['key']: exposure_id_field, layer_purpose_hazard['key']: hazard_id_field, layer_purpose_aggregation['key']: aggregation_id_field } has_id_column = False for layer_type, field in list(mapping.items()): if layer_purpose == layer_type: safe_id = field if layer.keywords['inasafe_fields'].get(field['key']): has_id_column = True break if not has_id_column: LOGGER.info( 'We add an ID column in {purpose}'.format(purpose=layer_purpose)) layer.startEditing() id_field = QgsField() id_field.setName(safe_id['field_name']) if isinstance(safe_id['type'], list): # Use the first element in the list of type id_field.setType(safe_id['type'][0]) else: id_field.setType(safe_id['type'][0]) id_field.setPrecision(safe_id['precision']) id_field.setLength(safe_id['length']) layer.addAttribute(id_field) new_index = layer.fields().lookupField(id_field.name()) for feature in layer.getFeatures(): layer.changeAttributeValue( feature.id(), new_index, feature.id()) layer.commitChanges() layer.keywords['inasafe_fields'][safe_id['key']] = ( safe_id['field_name'])
[ "def", "_add_id_column", "(", "layer", ")", ":", "layer_purpose", "=", "layer", ".", "keywords", "[", "'layer_purpose'", "]", "mapping", "=", "{", "layer_purpose_exposure", "[", "'key'", "]", ":", "exposure_id_field", ",", "layer_purpose_hazard", "[", "'key'", "...
Add an ID column if it's not present in the attribute table. :param layer: The vector layer. :type layer: QgsVectorLayer
[ "Add", "an", "ID", "column", "if", "it", "s", "not", "present", "in", "the", "attribute", "table", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/prepare_vector_layer.py#L372-L420
train
26,580
inasafe/inasafe
safe/gis/vector/prepare_vector_layer.py
_add_default_exposure_class
def _add_default_exposure_class(layer): """The layer doesn't have an exposure class, we need to add it. :param layer: The vector layer. :type layer: QgsVectorLayer """ layer.startEditing() field = create_field_from_definition(exposure_class_field) layer.keywords['inasafe_fields'][exposure_class_field['key']] = ( exposure_class_field['field_name']) layer.addAttribute(field) index = layer.fields().lookupField(exposure_class_field['field_name']) exposure = layer.keywords['exposure'] request = QgsFeatureRequest() request.setFlags(QgsFeatureRequest.NoGeometry) for feature in layer.getFeatures(request): layer.changeAttributeValue(feature.id(), index, exposure) layer.commitChanges() return
python
def _add_default_exposure_class(layer): """The layer doesn't have an exposure class, we need to add it. :param layer: The vector layer. :type layer: QgsVectorLayer """ layer.startEditing() field = create_field_from_definition(exposure_class_field) layer.keywords['inasafe_fields'][exposure_class_field['key']] = ( exposure_class_field['field_name']) layer.addAttribute(field) index = layer.fields().lookupField(exposure_class_field['field_name']) exposure = layer.keywords['exposure'] request = QgsFeatureRequest() request.setFlags(QgsFeatureRequest.NoGeometry) for feature in layer.getFeatures(request): layer.changeAttributeValue(feature.id(), index, exposure) layer.commitChanges() return
[ "def", "_add_default_exposure_class", "(", "layer", ")", ":", "layer", ".", "startEditing", "(", ")", "field", "=", "create_field_from_definition", "(", "exposure_class_field", ")", "layer", ".", "keywords", "[", "'inasafe_fields'", "]", "[", "exposure_class_field", ...
The layer doesn't have an exposure class, we need to add it. :param layer: The vector layer. :type layer: QgsVectorLayer
[ "The", "layer", "doesn", "t", "have", "an", "exposure", "class", "we", "need", "to", "add", "it", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/prepare_vector_layer.py#L424-L447
train
26,581
inasafe/inasafe
safe/gis/vector/prepare_vector_layer.py
sum_fields
def sum_fields(layer, output_field_key, input_fields): """Sum the value of input_fields and put it as output_field. :param layer: The vector layer. :type layer: QgsVectorLayer :param output_field_key: The output field definition key. :type output_field_key: basestring :param input_fields: List of input fields' name. :type input_fields: list """ field_definition = definition(output_field_key) output_field_name = field_definition['field_name'] # If the fields only has one element if len(input_fields) == 1: # Name is different, copy it if input_fields[0] != output_field_name: to_rename = {input_fields[0]: output_field_name} # We copy only, it will be deleted later. # We can't rename the field, we need to copy it as the same # field might be used many times in the FMT tool. copy_fields(layer, to_rename) else: # Name is same, do nothing return else: # Creating expression # Put field name in a double quote. See #4248 input_fields = ['"%s"' % f for f in input_fields] string_expression = ' + '.join(input_fields) sum_expression = QgsExpression(string_expression) context = QgsExpressionContext() context.setFields(layer.fields()) sum_expression.prepare(context) # Get the output field index output_idx = layer.fields().lookupField(output_field_name) # Output index is not found layer.startEditing() if output_idx == -1: output_field = create_field_from_definition(field_definition) layer.addAttribute(output_field) output_idx = layer.fields().lookupField(output_field_name) # Iterate to all features for feature in layer.getFeatures(): context.setFeature(feature) result = sum_expression.evaluate(context) feature[output_idx] = result layer.updateFeature(feature) layer.commitChanges()
python
def sum_fields(layer, output_field_key, input_fields): """Sum the value of input_fields and put it as output_field. :param layer: The vector layer. :type layer: QgsVectorLayer :param output_field_key: The output field definition key. :type output_field_key: basestring :param input_fields: List of input fields' name. :type input_fields: list """ field_definition = definition(output_field_key) output_field_name = field_definition['field_name'] # If the fields only has one element if len(input_fields) == 1: # Name is different, copy it if input_fields[0] != output_field_name: to_rename = {input_fields[0]: output_field_name} # We copy only, it will be deleted later. # We can't rename the field, we need to copy it as the same # field might be used many times in the FMT tool. copy_fields(layer, to_rename) else: # Name is same, do nothing return else: # Creating expression # Put field name in a double quote. See #4248 input_fields = ['"%s"' % f for f in input_fields] string_expression = ' + '.join(input_fields) sum_expression = QgsExpression(string_expression) context = QgsExpressionContext() context.setFields(layer.fields()) sum_expression.prepare(context) # Get the output field index output_idx = layer.fields().lookupField(output_field_name) # Output index is not found layer.startEditing() if output_idx == -1: output_field = create_field_from_definition(field_definition) layer.addAttribute(output_field) output_idx = layer.fields().lookupField(output_field_name) # Iterate to all features for feature in layer.getFeatures(): context.setFeature(feature) result = sum_expression.evaluate(context) feature[output_idx] = result layer.updateFeature(feature) layer.commitChanges()
[ "def", "sum_fields", "(", "layer", ",", "output_field_key", ",", "input_fields", ")", ":", "field_definition", "=", "definition", "(", "output_field_key", ")", "output_field_name", "=", "field_definition", "[", "'field_name'", "]", "# If the fields only has one element", ...
Sum the value of input_fields and put it as output_field. :param layer: The vector layer. :type layer: QgsVectorLayer :param output_field_key: The output field definition key. :type output_field_key: basestring :param input_fields: List of input fields' name. :type input_fields: list
[ "Sum", "the", "value", "of", "input_fields", "and", "put", "it", "as", "output_field", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/prepare_vector_layer.py#L451-L503
train
26,582
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_profile.py
get_needs_provenance
def get_needs_provenance(parameters): """Get the provenance of minimum needs. :param parameters: A dictionary of impact function parameters. :type parameters: dict :returns: A parameter of provenance :rtype: TextParameter """ if 'minimum needs' not in parameters: return None needs = parameters['minimum needs'] provenance = [p for p in needs if p.name == tr('Provenance')] if provenance: return provenance[0] return None
python
def get_needs_provenance(parameters): """Get the provenance of minimum needs. :param parameters: A dictionary of impact function parameters. :type parameters: dict :returns: A parameter of provenance :rtype: TextParameter """ if 'minimum needs' not in parameters: return None needs = parameters['minimum needs'] provenance = [p for p in needs if p.name == tr('Provenance')] if provenance: return provenance[0] return None
[ "def", "get_needs_provenance", "(", "parameters", ")", ":", "if", "'minimum needs'", "not", "in", "parameters", ":", "return", "None", "needs", "=", "parameters", "[", "'minimum needs'", "]", "provenance", "=", "[", "p", "for", "p", "in", "needs", "if", "p",...
Get the provenance of minimum needs. :param parameters: A dictionary of impact function parameters. :type parameters: dict :returns: A parameter of provenance :rtype: TextParameter
[ "Get", "the", "provenance", "of", "minimum", "needs", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L40-L55
train
26,583
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_profile.py
NeedsProfile.load
def load(self): """Load the minimum needs. If the minimum needs defined in QSettings use it, if not, get the most relevant available minimum needs (based on QGIS locale). The last thing to do is to just use the default minimum needs. """ self.minimum_needs = self.settings.value('MinimumNeeds') if not self.minimum_needs or self.minimum_needs == '': # Load the most relevant minimum needs # If more than one profile exists, just use defaults so # the user doesn't get confused. profiles = self.get_profiles() if len(profiles) == 1: profile = self.get_profiles()[0] self.load_profile(profile) else: self.minimum_needs = self._defaults()
python
def load(self): """Load the minimum needs. If the minimum needs defined in QSettings use it, if not, get the most relevant available minimum needs (based on QGIS locale). The last thing to do is to just use the default minimum needs. """ self.minimum_needs = self.settings.value('MinimumNeeds') if not self.minimum_needs or self.minimum_needs == '': # Load the most relevant minimum needs # If more than one profile exists, just use defaults so # the user doesn't get confused. profiles = self.get_profiles() if len(profiles) == 1: profile = self.get_profiles()[0] self.load_profile(profile) else: self.minimum_needs = self._defaults()
[ "def", "load", "(", "self", ")", ":", "self", ".", "minimum_needs", "=", "self", ".", "settings", ".", "value", "(", "'MinimumNeeds'", ")", "if", "not", "self", ".", "minimum_needs", "or", "self", ".", "minimum_needs", "==", "''", ":", "# Load the most rel...
Load the minimum needs. If the minimum needs defined in QSettings use it, if not, get the most relevant available minimum needs (based on QGIS locale). The last thing to do is to just use the default minimum needs.
[ "Load", "the", "minimum", "needs", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L101-L119
train
26,584
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_profile.py
NeedsProfile.load_profile
def load_profile(self, profile): """Load a specific profile into the current minimum needs. :param profile: The profile's name :type profile: basestring, str """ profile_path = os.path.join( self.root_directory, 'minimum_needs', profile + '.json') self.read_from_file(profile_path)
python
def load_profile(self, profile): """Load a specific profile into the current minimum needs. :param profile: The profile's name :type profile: basestring, str """ profile_path = os.path.join( self.root_directory, 'minimum_needs', profile + '.json') self.read_from_file(profile_path)
[ "def", "load_profile", "(", "self", ",", "profile", ")", ":", "profile_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_directory", ",", "'minimum_needs'", ",", "profile", "+", "'.json'", ")", "self", ".", "read_from_file", "(", "profile...
Load a specific profile into the current minimum needs. :param profile: The profile's name :type profile: basestring, str
[ "Load", "a", "specific", "profile", "into", "the", "current", "minimum", "needs", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L121-L129
train
26,585
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_profile.py
NeedsProfile.save_profile
def save_profile(self, profile): """Save the current minimum needs into a new profile. :param profile: The profile's name :type profile: basestring, str """ profile = profile.replace('.json', '') profile_path = os.path.join( self.root_directory, 'minimum_needs', profile + '.json' ) self.write_to_file(profile_path)
python
def save_profile(self, profile): """Save the current minimum needs into a new profile. :param profile: The profile's name :type profile: basestring, str """ profile = profile.replace('.json', '') profile_path = os.path.join( self.root_directory, 'minimum_needs', profile + '.json' ) self.write_to_file(profile_path)
[ "def", "save_profile", "(", "self", ",", "profile", ")", ":", "profile", "=", "profile", ".", "replace", "(", "'.json'", ",", "''", ")", "profile_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root_directory", ",", "'minimum_needs'", ",",...
Save the current minimum needs into a new profile. :param profile: The profile's name :type profile: basestring, str
[ "Save", "the", "current", "minimum", "needs", "into", "a", "new", "profile", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L131-L143
train
26,586
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_profile.py
NeedsProfile.get_profiles
def get_profiles(self, overwrite=False): """Get all the minimum needs profiles. :returns: The minimum needs by name. :rtype: list """ def sort_by_locale(unsorted_profiles, locale): """Sort the profiles by language settings. The profiles that are in the same language as the QGIS' locale will be sorted out first. :param unsorted_profiles: The user profiles profiles :type unsorted_profiles: list :param locale: The language settings string :type locale: str :returns: Ordered profiles :rtype: list """ if locale is None: return unsorted_profiles locale = '_%s' % locale[:2] profiles_our_locale = [] profiles_remaining = [] for profile_name in unsorted_profiles: if locale in profile_name: profiles_our_locale.append(profile_name) else: profiles_remaining.append(profile_name) return profiles_our_locale + profiles_remaining # We ignore empty root_directory to avoid load min needs profile # to test directory when test is running. if not self.root_directory: profiles = [] return profiles else: locale_minimum_needs_dir = os.path.join( self.root_directory, 'minimum_needs') path_name = resources_path('minimum_needs') if not os.path.exists(locale_minimum_needs_dir): os.makedirs(locale_minimum_needs_dir) # load default min needs profile for file_name in os.listdir(path_name): source_file = os.path.join(path_name, file_name) destination_file = os.path.join( locale_minimum_needs_dir, file_name) if not os.path.exists(destination_file) or overwrite: copy(source_file, destination_file) # move old min needs profile under user profile to inasafe # subdirectory self.move_old_profile(locale_minimum_needs_dir) profiles = [ profile[:-5] for profile in os.listdir(locale_minimum_needs_dir) if profile[-5:] == '.json'] profiles = sort_by_locale(profiles, self.locale) return profiles
python
def get_profiles(self, overwrite=False): """Get all the minimum needs profiles. :returns: The minimum needs by name. :rtype: list """ def sort_by_locale(unsorted_profiles, locale): """Sort the profiles by language settings. The profiles that are in the same language as the QGIS' locale will be sorted out first. :param unsorted_profiles: The user profiles profiles :type unsorted_profiles: list :param locale: The language settings string :type locale: str :returns: Ordered profiles :rtype: list """ if locale is None: return unsorted_profiles locale = '_%s' % locale[:2] profiles_our_locale = [] profiles_remaining = [] for profile_name in unsorted_profiles: if locale in profile_name: profiles_our_locale.append(profile_name) else: profiles_remaining.append(profile_name) return profiles_our_locale + profiles_remaining # We ignore empty root_directory to avoid load min needs profile # to test directory when test is running. if not self.root_directory: profiles = [] return profiles else: locale_minimum_needs_dir = os.path.join( self.root_directory, 'minimum_needs') path_name = resources_path('minimum_needs') if not os.path.exists(locale_minimum_needs_dir): os.makedirs(locale_minimum_needs_dir) # load default min needs profile for file_name in os.listdir(path_name): source_file = os.path.join(path_name, file_name) destination_file = os.path.join( locale_minimum_needs_dir, file_name) if not os.path.exists(destination_file) or overwrite: copy(source_file, destination_file) # move old min needs profile under user profile to inasafe # subdirectory self.move_old_profile(locale_minimum_needs_dir) profiles = [ profile[:-5] for profile in os.listdir(locale_minimum_needs_dir) if profile[-5:] == '.json'] profiles = sort_by_locale(profiles, self.locale) return profiles
[ "def", "get_profiles", "(", "self", ",", "overwrite", "=", "False", ")", ":", "def", "sort_by_locale", "(", "unsorted_profiles", ",", "locale", ")", ":", "\"\"\"Sort the profiles by language settings.\n\n The profiles that are in the same language as the QGIS' locale\n...
Get all the minimum needs profiles. :returns: The minimum needs by name. :rtype: list
[ "Get", "all", "the", "minimum", "needs", "profiles", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L155-L217
train
26,587
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_profile.py
NeedsProfile.get_needs_parameters
def get_needs_parameters(self): """Get the minimum needs resources in parameter format :returns: The minimum needs resources wrapped in parameters. :rtype: list """ parameters = [] for resource in self.minimum_needs['resources']: parameter = ResourceParameter() parameter.name = resource['Resource name'] parameter.help_text = resource['Resource description'] # Adding in the frequency property. This is not in the # FloatParameter by default, so maybe we should subclass. parameter.frequency = resource['Frequency'] parameter.description = self.format_sentence( resource['Readable sentence'], resource) parameter.minimum_allowed_value = float( resource['Minimum allowed']) parameter.maximum_allowed_value = float( resource['Maximum allowed']) parameter.unit.name = resource['Unit'] parameter.unit.plural = resource['Units'] parameter.unit.abbreviation = resource['Unit abbreviation'] parameter.value = float(resource['Default']) # choose highest precision between resource's parameters # start with default of 1 precisions = [1] precision_influence = [ 'Maximum allowed', 'Minimum allowed', 'Default'] for element in precision_influence: resource_element = str(resource[element]) if resource[element] is not None and '.' in resource_element: precisions.append(self.precision_of(resource_element)) parameter.precision = max(precisions) parameters.append(parameter) prov_parameter = TextParameter() prov_parameter.name = tr('Provenance') prov_parameter.description = tr('The provenance of minimum needs') prov_parameter.help_text = tr('The provenance of minimum needs') try: prov_parameter.value = self.provenance except TypeError: prov_parameter.value = '' parameters.append(prov_parameter) return parameters
python
def get_needs_parameters(self): """Get the minimum needs resources in parameter format :returns: The minimum needs resources wrapped in parameters. :rtype: list """ parameters = [] for resource in self.minimum_needs['resources']: parameter = ResourceParameter() parameter.name = resource['Resource name'] parameter.help_text = resource['Resource description'] # Adding in the frequency property. This is not in the # FloatParameter by default, so maybe we should subclass. parameter.frequency = resource['Frequency'] parameter.description = self.format_sentence( resource['Readable sentence'], resource) parameter.minimum_allowed_value = float( resource['Minimum allowed']) parameter.maximum_allowed_value = float( resource['Maximum allowed']) parameter.unit.name = resource['Unit'] parameter.unit.plural = resource['Units'] parameter.unit.abbreviation = resource['Unit abbreviation'] parameter.value = float(resource['Default']) # choose highest precision between resource's parameters # start with default of 1 precisions = [1] precision_influence = [ 'Maximum allowed', 'Minimum allowed', 'Default'] for element in precision_influence: resource_element = str(resource[element]) if resource[element] is not None and '.' in resource_element: precisions.append(self.precision_of(resource_element)) parameter.precision = max(precisions) parameters.append(parameter) prov_parameter = TextParameter() prov_parameter.name = tr('Provenance') prov_parameter.description = tr('The provenance of minimum needs') prov_parameter.help_text = tr('The provenance of minimum needs') try: prov_parameter.value = self.provenance except TypeError: prov_parameter.value = '' parameters.append(prov_parameter) return parameters
[ "def", "get_needs_parameters", "(", "self", ")", ":", "parameters", "=", "[", "]", "for", "resource", "in", "self", ".", "minimum_needs", "[", "'resources'", "]", ":", "parameter", "=", "ResourceParameter", "(", ")", "parameter", ".", "name", "=", "resource"...
Get the minimum needs resources in parameter format :returns: The minimum needs resources wrapped in parameters. :rtype: list
[ "Get", "the", "minimum", "needs", "resources", "in", "parameter", "format" ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L234-L282
train
26,588
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_profile.py
NeedsProfile.format_sentence
def format_sentence(sentence, resource): """Populate the placeholders in the sentence. :param sentence: The sentence with placeholder keywords. :type sentence: basestring, str :param resource: The resource to be placed into the sentence. :type resource: dict :returns: The formatted sentence. :rtype: basestring """ sentence = sentence.split('{{') updated_sentence = sentence[0].rstrip() for part in sentence[1:]: replace, keep = part.split('}}') replace = replace.strip() updated_sentence = "%s %s%s" % ( updated_sentence, resource[replace], keep ) return updated_sentence
python
def format_sentence(sentence, resource): """Populate the placeholders in the sentence. :param sentence: The sentence with placeholder keywords. :type sentence: basestring, str :param resource: The resource to be placed into the sentence. :type resource: dict :returns: The formatted sentence. :rtype: basestring """ sentence = sentence.split('{{') updated_sentence = sentence[0].rstrip() for part in sentence[1:]: replace, keep = part.split('}}') replace = replace.strip() updated_sentence = "%s %s%s" % ( updated_sentence, resource[replace], keep ) return updated_sentence
[ "def", "format_sentence", "(", "sentence", ",", "resource", ")", ":", "sentence", "=", "sentence", ".", "split", "(", "'{{'", ")", "updated_sentence", "=", "sentence", "[", "0", "]", ".", "rstrip", "(", ")", "for", "part", "in", "sentence", "[", "1", "...
Populate the placeholders in the sentence. :param sentence: The sentence with placeholder keywords. :type sentence: basestring, str :param resource: The resource to be placed into the sentence. :type resource: dict :returns: The formatted sentence. :rtype: basestring
[ "Populate", "the", "placeholders", "in", "the", "sentence", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L314-L336
train
26,589
inasafe/inasafe
safe/gui/tools/minimum_needs/needs_profile.py
NeedsProfile.remove_profile
def remove_profile(self, profile): """Remove a profile. :param profile: The profile to be removed. :type profile: basestring, str """ self.remove_file( os.path.join( self.root_directory, 'minimum_needs', profile + '.json') )
python
def remove_profile(self, profile): """Remove a profile. :param profile: The profile to be removed. :type profile: basestring, str """ self.remove_file( os.path.join( self.root_directory, 'minimum_needs', profile + '.json') )
[ "def", "remove_profile", "(", "self", ",", "profile", ")", ":", "self", ".", "remove_file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "root_directory", ",", "'minimum_needs'", ",", "profile", "+", "'.json'", ")", ")" ]
Remove a profile. :param profile: The profile to be removed. :type profile: basestring, str
[ "Remove", "a", "profile", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/minimum_needs/needs_profile.py#L338-L347
train
26,590
inasafe/inasafe
safe/utilities/i18n.py
tr
def tr(text, context='@default'): """We define a tr function alias here since the utilities implementation below is not a class and does not inherit from QObject. .. note:: see http://tinyurl.com/pyqt-differences :param text: String to be translated :type text: str, unicode :param context: A context for the translation. Since a same can be translated to different text depends on the context. :type context: str :returns: Translated version of the given string if available, otherwise the original string. :rtype: str, unicode """ # noinspection PyCallByClass,PyTypeChecker,PyArgumentList if type(text) != str: text = str(text) translated_text = QCoreApplication.translate(context, text) # Check if there is missing container. If so, return the original text. # See #3164 if text.count('%') == translated_text.count('%'): return translated_text else: content = ( 'There is a problem in the translation text.\n' 'The original text: "%s".\n' 'The translation: "%s".\n' 'The number of %% character does not match (%s and %s).' 'Please check the translation in transifex for %s.' % ( text, translated_text, text.count('%'), translated_text.count('%s'), locale() )) LOGGER.warning(content) return text
python
def tr(text, context='@default'): """We define a tr function alias here since the utilities implementation below is not a class and does not inherit from QObject. .. note:: see http://tinyurl.com/pyqt-differences :param text: String to be translated :type text: str, unicode :param context: A context for the translation. Since a same can be translated to different text depends on the context. :type context: str :returns: Translated version of the given string if available, otherwise the original string. :rtype: str, unicode """ # noinspection PyCallByClass,PyTypeChecker,PyArgumentList if type(text) != str: text = str(text) translated_text = QCoreApplication.translate(context, text) # Check if there is missing container. If so, return the original text. # See #3164 if text.count('%') == translated_text.count('%'): return translated_text else: content = ( 'There is a problem in the translation text.\n' 'The original text: "%s".\n' 'The translation: "%s".\n' 'The number of %% character does not match (%s and %s).' 'Please check the translation in transifex for %s.' % ( text, translated_text, text.count('%'), translated_text.count('%s'), locale() )) LOGGER.warning(content) return text
[ "def", "tr", "(", "text", ",", "context", "=", "'@default'", ")", ":", "# noinspection PyCallByClass,PyTypeChecker,PyArgumentList", "if", "type", "(", "text", ")", "!=", "str", ":", "text", "=", "str", "(", "text", ")", "translated_text", "=", "QCoreApplication"...
We define a tr function alias here since the utilities implementation below is not a class and does not inherit from QObject. .. note:: see http://tinyurl.com/pyqt-differences :param text: String to be translated :type text: str, unicode :param context: A context for the translation. Since a same can be translated to different text depends on the context. :type context: str :returns: Translated version of the given string if available, otherwise the original string. :rtype: str, unicode
[ "We", "define", "a", "tr", "function", "alias", "here", "since", "the", "utilities", "implementation", "below", "is", "not", "a", "class", "and", "does", "not", "inherit", "from", "QObject", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/i18n.py#L24-L63
train
26,591
inasafe/inasafe
safe/utilities/i18n.py
locale
def locale(qsetting=''): """Get the name of the currently active locale. :param qsetting: String to specify the QSettings. By default, use empty string. :type qsetting: str :returns: Name of the locale e.g. 'id' :rtype: str """ override_flag = QSettings(qsetting).value( 'locale/overrideFlag', True, type=bool) default = 'en_US' if override_flag: locale_name = QSettings(qsetting).value( 'locale/userLocale', default, type=str) else: # noinspection PyArgumentList locale_name = QLocale.system().name() if locale_name == 'C': # On travis, locale/userLocale is equal to C. We want 'en'. locale_name = default # NOTES: we split the locale name because we need the first two # character i.e. 'id', 'af, etc locale_name = str(locale_name).split('_')[0] return locale_name
python
def locale(qsetting=''): """Get the name of the currently active locale. :param qsetting: String to specify the QSettings. By default, use empty string. :type qsetting: str :returns: Name of the locale e.g. 'id' :rtype: str """ override_flag = QSettings(qsetting).value( 'locale/overrideFlag', True, type=bool) default = 'en_US' if override_flag: locale_name = QSettings(qsetting).value( 'locale/userLocale', default, type=str) else: # noinspection PyArgumentList locale_name = QLocale.system().name() if locale_name == 'C': # On travis, locale/userLocale is equal to C. We want 'en'. locale_name = default # NOTES: we split the locale name because we need the first two # character i.e. 'id', 'af, etc locale_name = str(locale_name).split('_')[0] return locale_name
[ "def", "locale", "(", "qsetting", "=", "''", ")", ":", "override_flag", "=", "QSettings", "(", "qsetting", ")", ".", "value", "(", "'locale/overrideFlag'", ",", "True", ",", "type", "=", "bool", ")", "default", "=", "'en_US'", "if", "override_flag", ":", ...
Get the name of the currently active locale. :param qsetting: String to specify the QSettings. By default, use empty string. :type qsetting: str :returns: Name of the locale e.g. 'id' :rtype: str
[ "Get", "the", "name", "of", "the", "currently", "active", "locale", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/i18n.py#L66-L95
train
26,592
inasafe/inasafe
safe/gui/tools/wizard/step_kw13_band_selector.py
StepKwBandSelector.update_band_description
def update_band_description(self): """Helper to update band description.""" self.clear_further_steps() # Set widgets selected_band = self.selected_band() statistics = self.parent.layer.dataProvider().bandStatistics( selected_band, QgsRasterBandStats.All, self.parent.layer.extent(), 0) band_description = tr( 'This band contains data from {min_value} to {max_value}').format( min_value=statistics.minimumValue, max_value=statistics.maximumValue ) self.lblDescribeBandSelector.setText(band_description)
python
def update_band_description(self): """Helper to update band description.""" self.clear_further_steps() # Set widgets selected_band = self.selected_band() statistics = self.parent.layer.dataProvider().bandStatistics( selected_band, QgsRasterBandStats.All, self.parent.layer.extent(), 0) band_description = tr( 'This band contains data from {min_value} to {max_value}').format( min_value=statistics.minimumValue, max_value=statistics.maximumValue ) self.lblDescribeBandSelector.setText(band_description)
[ "def", "update_band_description", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "# Set widgets", "selected_band", "=", "self", ".", "selected_band", "(", ")", "statistics", "=", "self", ".", "parent", ".", "layer", ".", "dataProvider", "...
Helper to update band description.
[ "Helper", "to", "update", "band", "description", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw13_band_selector.py#L58-L73
train
26,593
inasafe/inasafe
safe/gui/tools/wizard/step_kw13_band_selector.py
StepKwBandSelector.selected_band
def selected_band(self): """Obtain the layer mode selected by user. :returns: selected layer mode. :rtype: string, None """ item = self.lstBands.currentItem() return item.data(QtCore.Qt.UserRole)
python
def selected_band(self): """Obtain the layer mode selected by user. :returns: selected layer mode. :rtype: string, None """ item = self.lstBands.currentItem() return item.data(QtCore.Qt.UserRole)
[ "def", "selected_band", "(", "self", ")", ":", "item", "=", "self", ".", "lstBands", ".", "currentItem", "(", ")", "return", "item", ".", "data", "(", "QtCore", ".", "Qt", ".", "UserRole", ")" ]
Obtain the layer mode selected by user. :returns: selected layer mode. :rtype: string, None
[ "Obtain", "the", "layer", "mode", "selected", "by", "user", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw13_band_selector.py#L75-L82
train
26,594
inasafe/inasafe
safe/metadata35/utils.py
merge_dictionaries
def merge_dictionaries(base_dict, extra_dict): """ merge two dictionaries. if both have a same key, the one from extra_dict is taken :param base_dict: first dictionary :type base_dict: dict :param extra_dict: second dictionary :type extra_dict: dict :return: a merge of the two dictionaries :rtype: dicts """ new_dict = base_dict.copy() new_dict.update(extra_dict) return new_dict
python
def merge_dictionaries(base_dict, extra_dict): """ merge two dictionaries. if both have a same key, the one from extra_dict is taken :param base_dict: first dictionary :type base_dict: dict :param extra_dict: second dictionary :type extra_dict: dict :return: a merge of the two dictionaries :rtype: dicts """ new_dict = base_dict.copy() new_dict.update(extra_dict) return new_dict
[ "def", "merge_dictionaries", "(", "base_dict", ",", "extra_dict", ")", ":", "new_dict", "=", "base_dict", ".", "copy", "(", ")", "new_dict", ".", "update", "(", "extra_dict", ")", "return", "new_dict" ]
merge two dictionaries. if both have a same key, the one from extra_dict is taken :param base_dict: first dictionary :type base_dict: dict :param extra_dict: second dictionary :type extra_dict: dict :return: a merge of the two dictionaries :rtype: dicts
[ "merge", "two", "dictionaries", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/utils.py#L112-L127
train
26,595
inasafe/inasafe
safe/metadata35/utils.py
read_property_from_xml
def read_property_from_xml(root, path): """ Get the text from an XML property. Whitespaces, tabs and new lines are trimmed :param root: container in which we search :type root: ElementTree.Element :param path: path to search in root :type path: str :return: the text of the element at the given path :rtype: str, None """ element = root.find(path, XML_NS) try: return element.text.strip(' \t\n\r') except AttributeError: return None
python
def read_property_from_xml(root, path): """ Get the text from an XML property. Whitespaces, tabs and new lines are trimmed :param root: container in which we search :type root: ElementTree.Element :param path: path to search in root :type path: str :return: the text of the element at the given path :rtype: str, None """ element = root.find(path, XML_NS) try: return element.text.strip(' \t\n\r') except AttributeError: return None
[ "def", "read_property_from_xml", "(", "root", ",", "path", ")", ":", "element", "=", "root", ".", "find", "(", "path", ",", "XML_NS", ")", "try", ":", "return", "element", ".", "text", ".", "strip", "(", "' \\t\\n\\r'", ")", "except", "AttributeError", "...
Get the text from an XML property. Whitespaces, tabs and new lines are trimmed :param root: container in which we search :type root: ElementTree.Element :param path: path to search in root :type path: str :return: the text of the element at the given path :rtype: str, None
[ "Get", "the", "text", "from", "an", "XML", "property", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata35/utils.py#L130-L147
train
26,596
inasafe/inasafe
safe/report/impact_report.py
InaSAFEReportContext.north_arrow
def north_arrow(self, north_arrow_path): """Set image that will be used as north arrow in reports. :param north_arrow_path: Path to the north arrow image. :type north_arrow_path: str """ if isinstance(north_arrow_path, str) and os.path.exists( north_arrow_path): self._north_arrow = north_arrow_path else: self._north_arrow = default_north_arrow_path()
python
def north_arrow(self, north_arrow_path): """Set image that will be used as north arrow in reports. :param north_arrow_path: Path to the north arrow image. :type north_arrow_path: str """ if isinstance(north_arrow_path, str) and os.path.exists( north_arrow_path): self._north_arrow = north_arrow_path else: self._north_arrow = default_north_arrow_path()
[ "def", "north_arrow", "(", "self", ",", "north_arrow_path", ")", ":", "if", "isinstance", "(", "north_arrow_path", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "north_arrow_path", ")", ":", "self", ".", "_north_arrow", "=", "north_arrow_pat...
Set image that will be used as north arrow in reports. :param north_arrow_path: Path to the north arrow image. :type north_arrow_path: str
[ "Set", "image", "that", "will", "be", "used", "as", "north", "arrow", "in", "reports", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L69-L79
train
26,597
inasafe/inasafe
safe/report/impact_report.py
InaSAFEReportContext.organisation_logo
def organisation_logo(self, logo): """Set image that will be used as organisation logo in reports. :param logo: Path to the organisation logo image. :type logo: str """ if isinstance(logo, str) and os.path.exists(logo): self._organisation_logo = logo else: self._organisation_logo = supporters_logo_path()
python
def organisation_logo(self, logo): """Set image that will be used as organisation logo in reports. :param logo: Path to the organisation logo image. :type logo: str """ if isinstance(logo, str) and os.path.exists(logo): self._organisation_logo = logo else: self._organisation_logo = supporters_logo_path()
[ "def", "organisation_logo", "(", "self", ",", "logo", ")", ":", "if", "isinstance", "(", "logo", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "logo", ")", ":", "self", ".", "_organisation_logo", "=", "logo", "else", ":", "self", "."...
Set image that will be used as organisation logo in reports. :param logo: Path to the organisation logo image. :type logo: str
[ "Set", "image", "that", "will", "be", "used", "as", "organisation", "logo", "in", "reports", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L116-L125
train
26,598
inasafe/inasafe
safe/report/impact_report.py
InaSAFEReportContext.disclaimer
def disclaimer(self, text): """Set text that will be used as disclaimer in reports. :param text: Disclaimer text :type text: str """ if not isinstance(text, str): self._disclaimer = disclaimer() else: self._disclaimer = text
python
def disclaimer(self, text): """Set text that will be used as disclaimer in reports. :param text: Disclaimer text :type text: str """ if not isinstance(text, str): self._disclaimer = disclaimer() else: self._disclaimer = text
[ "def", "disclaimer", "(", "self", ",", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "self", ".", "_disclaimer", "=", "disclaimer", "(", ")", "else", ":", "self", ".", "_disclaimer", "=", "text" ]
Set text that will be used as disclaimer in reports. :param text: Disclaimer text :type text: str
[ "Set", "text", "that", "will", "be", "used", "as", "disclaimer", "in", "reports", "." ]
831d60abba919f6d481dc94a8d988cc205130724
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L148-L157
train
26,599