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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
pr-omethe-us/PyKED
pyked/converters.py
get_reference
def get_reference(root): """Read reference info from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with reference information """ reference = {} elem = root.find('bibliographyLink') if elem is None: raise MissingElementError('bibliographyLink') # Try to get reference info via DOI, fall back on preferredKey if necessary. ref_doi = elem.get('doi', None) ref_key = elem.get('preferredKey', None) if ref_doi is not None: try: ref = crossref_api.works(ids=ref_doi)['message'] except (HTTPError, habanero.RequestError, ConnectionError): if ref_key is None: raise KeywordError('DOI not found and preferredKey attribute not set') else: warn('Missing doi attribute in bibliographyLink or lookup failed. ' 'Setting "detail" key as a fallback; please update to the appropriate fields.' ) reference['detail'] = ref_key if reference['detail'][-1] != '.': reference['detail'] += '.' else: if ref_key is not None: warn('Using DOI to obtain reference information, rather than preferredKey.') reference['doi'] = elem.attrib['doi'] # Now get elements of the reference data # Assume that the reference returned by the DOI lookup always has a container-title reference['journal'] = ref.get('container-title')[0] ref_year = ref.get('published-print') or ref.get('published-online') reference['year'] = int(ref_year['date-parts'][0][0]) reference['volume'] = int(ref.get('volume')) reference['pages'] = ref.get('page') reference['authors'] = [] for author in ref['author']: auth = {} auth['name'] = ' '.join([author['given'], author['family']]) # Add ORCID if available orcid = author.get('ORCID') if orcid: auth['ORCID'] = orcid.lstrip('http://orcid.org/') reference['authors'].append(auth) elif ref_key is not None: warn('Missing doi attribute in bibliographyLink. ' 'Setting "detail" key as a fallback; please update to the appropriate fields.' ) reference['detail'] = ref_key if reference['detail'][-1] != '.': reference['detail'] += '.' else: # Need one of DOI or preferredKey raise MissingAttributeError('preferredKey', 'bibliographyLink') return reference
python
def get_reference(root): """Read reference info from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with reference information """ reference = {} elem = root.find('bibliographyLink') if elem is None: raise MissingElementError('bibliographyLink') # Try to get reference info via DOI, fall back on preferredKey if necessary. ref_doi = elem.get('doi', None) ref_key = elem.get('preferredKey', None) if ref_doi is not None: try: ref = crossref_api.works(ids=ref_doi)['message'] except (HTTPError, habanero.RequestError, ConnectionError): if ref_key is None: raise KeywordError('DOI not found and preferredKey attribute not set') else: warn('Missing doi attribute in bibliographyLink or lookup failed. ' 'Setting "detail" key as a fallback; please update to the appropriate fields.' ) reference['detail'] = ref_key if reference['detail'][-1] != '.': reference['detail'] += '.' else: if ref_key is not None: warn('Using DOI to obtain reference information, rather than preferredKey.') reference['doi'] = elem.attrib['doi'] # Now get elements of the reference data # Assume that the reference returned by the DOI lookup always has a container-title reference['journal'] = ref.get('container-title')[0] ref_year = ref.get('published-print') or ref.get('published-online') reference['year'] = int(ref_year['date-parts'][0][0]) reference['volume'] = int(ref.get('volume')) reference['pages'] = ref.get('page') reference['authors'] = [] for author in ref['author']: auth = {} auth['name'] = ' '.join([author['given'], author['family']]) # Add ORCID if available orcid = author.get('ORCID') if orcid: auth['ORCID'] = orcid.lstrip('http://orcid.org/') reference['authors'].append(auth) elif ref_key is not None: warn('Missing doi attribute in bibliographyLink. ' 'Setting "detail" key as a fallback; please update to the appropriate fields.' ) reference['detail'] = ref_key if reference['detail'][-1] != '.': reference['detail'] += '.' else: # Need one of DOI or preferredKey raise MissingAttributeError('preferredKey', 'bibliographyLink') return reference
[ "def", "get_reference", "(", "root", ")", ":", "reference", "=", "{", "}", "elem", "=", "root", ".", "find", "(", "'bibliographyLink'", ")", "if", "elem", "is", "None", ":", "raise", "MissingElementError", "(", "'bibliographyLink'", ")", "ref_doi", "=", "elem", ".", "get", "(", "'doi'", ",", "None", ")", "ref_key", "=", "elem", ".", "get", "(", "'preferredKey'", ",", "None", ")", "if", "ref_doi", "is", "not", "None", ":", "try", ":", "ref", "=", "crossref_api", ".", "works", "(", "ids", "=", "ref_doi", ")", "[", "'message'", "]", "except", "(", "HTTPError", ",", "habanero", ".", "RequestError", ",", "ConnectionError", ")", ":", "if", "ref_key", "is", "None", ":", "raise", "KeywordError", "(", "'DOI not found and preferredKey attribute not set'", ")", "else", ":", "warn", "(", "'Missing doi attribute in bibliographyLink or lookup failed. '", "'Setting \"detail\" key as a fallback; please update to the appropriate fields.'", ")", "reference", "[", "'detail'", "]", "=", "ref_key", "if", "reference", "[", "'detail'", "]", "[", "-", "1", "]", "!=", "'.'", ":", "reference", "[", "'detail'", "]", "+=", "'.'", "else", ":", "if", "ref_key", "is", "not", "None", ":", "warn", "(", "'Using DOI to obtain reference information, rather than preferredKey.'", ")", "reference", "[", "'doi'", "]", "=", "elem", ".", "attrib", "[", "'doi'", "]", "reference", "[", "'journal'", "]", "=", "ref", ".", "get", "(", "'container-title'", ")", "[", "0", "]", "ref_year", "=", "ref", ".", "get", "(", "'published-print'", ")", "or", "ref", ".", "get", "(", "'published-online'", ")", "reference", "[", "'year'", "]", "=", "int", "(", "ref_year", "[", "'date-parts'", "]", "[", "0", "]", "[", "0", "]", ")", "reference", "[", "'volume'", "]", "=", "int", "(", "ref", ".", "get", "(", "'volume'", ")", ")", "reference", "[", "'pages'", "]", "=", "ref", ".", "get", "(", "'page'", ")", "reference", "[", "'authors'", "]", "=", "[", "]", "for", "author", "in", "ref", "[", "'author'", "]", ":", "auth", "=", "{", "}", "auth", "[", "'name'", "]", "=", "' '", ".", "join", "(", "[", "author", "[", "'given'", "]", ",", "author", "[", "'family'", "]", "]", ")", "orcid", "=", "author", ".", "get", "(", "'ORCID'", ")", "if", "orcid", ":", "auth", "[", "'ORCID'", "]", "=", "orcid", ".", "lstrip", "(", "'http://orcid.org/'", ")", "reference", "[", "'authors'", "]", ".", "append", "(", "auth", ")", "elif", "ref_key", "is", "not", "None", ":", "warn", "(", "'Missing doi attribute in bibliographyLink. '", "'Setting \"detail\" key as a fallback; please update to the appropriate fields.'", ")", "reference", "[", "'detail'", "]", "=", "ref_key", "if", "reference", "[", "'detail'", "]", "[", "-", "1", "]", "!=", "'.'", ":", "reference", "[", "'detail'", "]", "+=", "'.'", "else", ":", "raise", "MissingAttributeError", "(", "'preferredKey'", ",", "'bibliographyLink'", ")", "return", "reference" ]
Read reference info from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with reference information
[ "Read", "reference", "info", "from", "root", "of", "ReSpecTh", "XML", "file", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L86-L149
train
pr-omethe-us/PyKED
pyked/converters.py
get_ignition_type
def get_ignition_type(root): """Gets ignition type and target. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with ignition type/target information """ properties = {} elem = root.find('ignitionType') if elem is None: raise MissingElementError('ignitionType') elem = elem.attrib if 'target' in elem: ign_target = elem['target'].rstrip(';').upper() else: raise MissingAttributeError('target', 'ignitionType') if 'type' in elem: ign_type = elem['type'] if ign_type == 'baseline max intercept from d/dt': ign_type = 'd/dt max extrapolated' else: raise MissingAttributeError('type', 'ignitionType') # ReSpecTh allows multiple ignition targets if len(ign_target.split(';')) > 1: raise NotImplementedError('Multiple ignition targets not supported.') # Acceptable ignition targets include pressure, temperature, and species # concentrations if ign_target == 'OHEX': ign_target = 'OH*' elif ign_target == 'CHEX': ign_target = 'CH*' elif ign_target == 'P': ign_target = 'pressure' elif ign_target == 'T': ign_target = 'temperature' if ign_target not in ['pressure', 'temperature', 'OH', 'OH*', 'CH*', 'CH']: raise KeywordError(ign_target + ' not valid ignition target') if ign_type not in ['max', 'd/dt max', '1/2 max', 'min', 'd/dt max extrapolated']: raise KeywordError(ign_type + ' not valid ignition type') properties['type'] = ign_type properties['target'] = ign_target return properties
python
def get_ignition_type(root): """Gets ignition type and target. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with ignition type/target information """ properties = {} elem = root.find('ignitionType') if elem is None: raise MissingElementError('ignitionType') elem = elem.attrib if 'target' in elem: ign_target = elem['target'].rstrip(';').upper() else: raise MissingAttributeError('target', 'ignitionType') if 'type' in elem: ign_type = elem['type'] if ign_type == 'baseline max intercept from d/dt': ign_type = 'd/dt max extrapolated' else: raise MissingAttributeError('type', 'ignitionType') # ReSpecTh allows multiple ignition targets if len(ign_target.split(';')) > 1: raise NotImplementedError('Multiple ignition targets not supported.') # Acceptable ignition targets include pressure, temperature, and species # concentrations if ign_target == 'OHEX': ign_target = 'OH*' elif ign_target == 'CHEX': ign_target = 'CH*' elif ign_target == 'P': ign_target = 'pressure' elif ign_target == 'T': ign_target = 'temperature' if ign_target not in ['pressure', 'temperature', 'OH', 'OH*', 'CH*', 'CH']: raise KeywordError(ign_target + ' not valid ignition target') if ign_type not in ['max', 'd/dt max', '1/2 max', 'min', 'd/dt max extrapolated']: raise KeywordError(ign_type + ' not valid ignition type') properties['type'] = ign_type properties['target'] = ign_target return properties
[ "def", "get_ignition_type", "(", "root", ")", ":", "properties", "=", "{", "}", "elem", "=", "root", ".", "find", "(", "'ignitionType'", ")", "if", "elem", "is", "None", ":", "raise", "MissingElementError", "(", "'ignitionType'", ")", "elem", "=", "elem", ".", "attrib", "if", "'target'", "in", "elem", ":", "ign_target", "=", "elem", "[", "'target'", "]", ".", "rstrip", "(", "';'", ")", ".", "upper", "(", ")", "else", ":", "raise", "MissingAttributeError", "(", "'target'", ",", "'ignitionType'", ")", "if", "'type'", "in", "elem", ":", "ign_type", "=", "elem", "[", "'type'", "]", "if", "ign_type", "==", "'baseline max intercept from d/dt'", ":", "ign_type", "=", "'d/dt max extrapolated'", "else", ":", "raise", "MissingAttributeError", "(", "'type'", ",", "'ignitionType'", ")", "if", "len", "(", "ign_target", ".", "split", "(", "';'", ")", ")", ">", "1", ":", "raise", "NotImplementedError", "(", "'Multiple ignition targets not supported.'", ")", "if", "ign_target", "==", "'OHEX'", ":", "ign_target", "=", "'OH*'", "elif", "ign_target", "==", "'CHEX'", ":", "ign_target", "=", "'CH*'", "elif", "ign_target", "==", "'P'", ":", "ign_target", "=", "'pressure'", "elif", "ign_target", "==", "'T'", ":", "ign_target", "=", "'temperature'", "if", "ign_target", "not", "in", "[", "'pressure'", ",", "'temperature'", ",", "'OH'", ",", "'OH*'", ",", "'CH*'", ",", "'CH'", "]", ":", "raise", "KeywordError", "(", "ign_target", "+", "' not valid ignition target'", ")", "if", "ign_type", "not", "in", "[", "'max'", ",", "'d/dt max'", ",", "'1/2 max'", ",", "'min'", ",", "'d/dt max extrapolated'", "]", ":", "raise", "KeywordError", "(", "ign_type", "+", "' not valid ignition type'", ")", "properties", "[", "'type'", "]", "=", "ign_type", "properties", "[", "'target'", "]", "=", "ign_target", "return", "properties" ]
Gets ignition type and target. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with ignition type/target information
[ "Gets", "ignition", "type", "and", "target", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L263-L315
train
pr-omethe-us/PyKED
pyked/converters.py
ReSpecTh_to_ChemKED
def ReSpecTh_to_ChemKED(filename_xml, file_author='', file_author_orcid='', *, validate=False): """Convert ReSpecTh XML file to ChemKED-compliant dictionary. Args: filename_xml (`str`): Name of ReSpecTh XML file to be converted. file_author (`str`, optional): Name to override original file author file_author_orcid (`str`, optional): ORCID of file author validate (`bool`, optional, keyword-only): Set to `True` to validate the resulting property dictionary with `ChemKED`. Set to `False` if the file is being loaded and will be validated at some other point before use. """ # get all information from XML file tree = etree.parse(filename_xml) root = tree.getroot() # get file metadata properties = get_file_metadata(root) # get reference info properties['reference'] = get_reference(root) # Save name of original data filename properties['reference']['detail'] = (properties['reference'].get('detail', '') + 'Converted from ReSpecTh XML file ' + os.path.basename(filename_xml) ) # Ensure ignition delay, and get which kind of experiment properties.update(get_experiment_kind(root)) # Get properties shared across the file properties['common-properties'] = get_common_properties(root) # Determine definition of ignition delay properties['common-properties']['ignition-type'] = get_ignition_type(root) # Now parse ignition delay datapoints properties['datapoints'] = get_datapoints(root) # Ensure inclusion of pressure rise or volume history matches apparatus. has_pres_rise = ('pressure-rise' in properties['common-properties'] or any([True for dp in properties['datapoints'] if 'pressure-rise' in dp]) ) if has_pres_rise and properties['apparatus']['kind'] == 'rapid compression machine': raise KeywordError('Pressure rise cannot be defined for RCM.') has_vol_hist = any( [t.get('type') == 'volume' for dp in properties['datapoints'] for t in dp.get('time-histories', [{}])] ) if has_vol_hist and properties['apparatus']['kind'] == 'shock tube': raise KeywordError('Volume history cannot be defined for shock tube.') # add any additional file authors if file_author_orcid and not file_author: raise KeywordError('If file_author_orcid is specified, file_author must be as well') if file_author: temp_author = {'name': file_author} if file_author_orcid: temp_author['ORCID'] = file_author_orcid properties['file-authors'].append(temp_author) # Now go through datapoints and apply common properties for idx in range(len(properties['datapoints'])): for prop in properties['common-properties']: properties['datapoints'][idx][prop] = properties['common-properties'][prop] if validate: chemked.ChemKED(dict_input=properties) return properties
python
def ReSpecTh_to_ChemKED(filename_xml, file_author='', file_author_orcid='', *, validate=False): """Convert ReSpecTh XML file to ChemKED-compliant dictionary. Args: filename_xml (`str`): Name of ReSpecTh XML file to be converted. file_author (`str`, optional): Name to override original file author file_author_orcid (`str`, optional): ORCID of file author validate (`bool`, optional, keyword-only): Set to `True` to validate the resulting property dictionary with `ChemKED`. Set to `False` if the file is being loaded and will be validated at some other point before use. """ # get all information from XML file tree = etree.parse(filename_xml) root = tree.getroot() # get file metadata properties = get_file_metadata(root) # get reference info properties['reference'] = get_reference(root) # Save name of original data filename properties['reference']['detail'] = (properties['reference'].get('detail', '') + 'Converted from ReSpecTh XML file ' + os.path.basename(filename_xml) ) # Ensure ignition delay, and get which kind of experiment properties.update(get_experiment_kind(root)) # Get properties shared across the file properties['common-properties'] = get_common_properties(root) # Determine definition of ignition delay properties['common-properties']['ignition-type'] = get_ignition_type(root) # Now parse ignition delay datapoints properties['datapoints'] = get_datapoints(root) # Ensure inclusion of pressure rise or volume history matches apparatus. has_pres_rise = ('pressure-rise' in properties['common-properties'] or any([True for dp in properties['datapoints'] if 'pressure-rise' in dp]) ) if has_pres_rise and properties['apparatus']['kind'] == 'rapid compression machine': raise KeywordError('Pressure rise cannot be defined for RCM.') has_vol_hist = any( [t.get('type') == 'volume' for dp in properties['datapoints'] for t in dp.get('time-histories', [{}])] ) if has_vol_hist and properties['apparatus']['kind'] == 'shock tube': raise KeywordError('Volume history cannot be defined for shock tube.') # add any additional file authors if file_author_orcid and not file_author: raise KeywordError('If file_author_orcid is specified, file_author must be as well') if file_author: temp_author = {'name': file_author} if file_author_orcid: temp_author['ORCID'] = file_author_orcid properties['file-authors'].append(temp_author) # Now go through datapoints and apply common properties for idx in range(len(properties['datapoints'])): for prop in properties['common-properties']: properties['datapoints'][idx][prop] = properties['common-properties'][prop] if validate: chemked.ChemKED(dict_input=properties) return properties
[ "def", "ReSpecTh_to_ChemKED", "(", "filename_xml", ",", "file_author", "=", "''", ",", "file_author_orcid", "=", "''", ",", "*", ",", "validate", "=", "False", ")", ":", "tree", "=", "etree", ".", "parse", "(", "filename_xml", ")", "root", "=", "tree", ".", "getroot", "(", ")", "properties", "=", "get_file_metadata", "(", "root", ")", "properties", "[", "'reference'", "]", "=", "get_reference", "(", "root", ")", "properties", "[", "'reference'", "]", "[", "'detail'", "]", "=", "(", "properties", "[", "'reference'", "]", ".", "get", "(", "'detail'", ",", "''", ")", "+", "'Converted from ReSpecTh XML file '", "+", "os", ".", "path", ".", "basename", "(", "filename_xml", ")", ")", "properties", ".", "update", "(", "get_experiment_kind", "(", "root", ")", ")", "properties", "[", "'common-properties'", "]", "=", "get_common_properties", "(", "root", ")", "properties", "[", "'common-properties'", "]", "[", "'ignition-type'", "]", "=", "get_ignition_type", "(", "root", ")", "properties", "[", "'datapoints'", "]", "=", "get_datapoints", "(", "root", ")", "has_pres_rise", "=", "(", "'pressure-rise'", "in", "properties", "[", "'common-properties'", "]", "or", "any", "(", "[", "True", "for", "dp", "in", "properties", "[", "'datapoints'", "]", "if", "'pressure-rise'", "in", "dp", "]", ")", ")", "if", "has_pres_rise", "and", "properties", "[", "'apparatus'", "]", "[", "'kind'", "]", "==", "'rapid compression machine'", ":", "raise", "KeywordError", "(", "'Pressure rise cannot be defined for RCM.'", ")", "has_vol_hist", "=", "any", "(", "[", "t", ".", "get", "(", "'type'", ")", "==", "'volume'", "for", "dp", "in", "properties", "[", "'datapoints'", "]", "for", "t", "in", "dp", ".", "get", "(", "'time-histories'", ",", "[", "{", "}", "]", ")", "]", ")", "if", "has_vol_hist", "and", "properties", "[", "'apparatus'", "]", "[", "'kind'", "]", "==", "'shock tube'", ":", "raise", "KeywordError", "(", "'Volume history cannot be defined for shock tube.'", ")", "if", "file_author_orcid", "and", "not", "file_author", ":", "raise", "KeywordError", "(", "'If file_author_orcid is specified, file_author must be as well'", ")", "if", "file_author", ":", "temp_author", "=", "{", "'name'", ":", "file_author", "}", "if", "file_author_orcid", ":", "temp_author", "[", "'ORCID'", "]", "=", "file_author_orcid", "properties", "[", "'file-authors'", "]", ".", "append", "(", "temp_author", ")", "for", "idx", "in", "range", "(", "len", "(", "properties", "[", "'datapoints'", "]", ")", ")", ":", "for", "prop", "in", "properties", "[", "'common-properties'", "]", ":", "properties", "[", "'datapoints'", "]", "[", "idx", "]", "[", "prop", "]", "=", "properties", "[", "'common-properties'", "]", "[", "prop", "]", "if", "validate", ":", "chemked", ".", "ChemKED", "(", "dict_input", "=", "properties", ")", "return", "properties" ]
Convert ReSpecTh XML file to ChemKED-compliant dictionary. Args: filename_xml (`str`): Name of ReSpecTh XML file to be converted. file_author (`str`, optional): Name to override original file author file_author_orcid (`str`, optional): ORCID of file author validate (`bool`, optional, keyword-only): Set to `True` to validate the resulting property dictionary with `ChemKED`. Set to `False` if the file is being loaded and will be validated at some other point before use.
[ "Convert", "ReSpecTh", "XML", "file", "to", "ChemKED", "-", "compliant", "dictionary", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L474-L544
train
pr-omethe-us/PyKED
pyked/converters.py
respth2ck
def respth2ck(argv=None): """Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file. """ parser = ArgumentParser( description='Convert a ReSpecTh XML file to a ChemKED YAML file.' ) parser.add_argument('-i', '--input', type=str, required=True, help='Input filename (e.g., "file1.yaml")' ) parser.add_argument('-o', '--output', type=str, required=False, default='', help='Output filename (e.g., "file1.xml")' ) parser.add_argument('-fa', '--file-author', dest='file_author', type=str, required=False, default='', help='File author name to override original' ) parser.add_argument('-fo', '--file-author-orcid', dest='file_author_orcid', type=str, required=False, default='', help='File author ORCID' ) args = parser.parse_args(argv) filename_ck = args.output filename_xml = args.input properties = ReSpecTh_to_ChemKED(filename_xml, args.file_author, args.file_author_orcid, validate=True) # set output filename and path if not filename_ck: filename_ck = os.path.join(os.path.dirname(filename_xml), os.path.splitext(os.path.basename(filename_xml))[0] + '.yaml' ) with open(filename_ck, 'w') as outfile: yaml.dump(properties, outfile, default_flow_style=False) print('Converted to ' + filename_ck)
python
def respth2ck(argv=None): """Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file. """ parser = ArgumentParser( description='Convert a ReSpecTh XML file to a ChemKED YAML file.' ) parser.add_argument('-i', '--input', type=str, required=True, help='Input filename (e.g., "file1.yaml")' ) parser.add_argument('-o', '--output', type=str, required=False, default='', help='Output filename (e.g., "file1.xml")' ) parser.add_argument('-fa', '--file-author', dest='file_author', type=str, required=False, default='', help='File author name to override original' ) parser.add_argument('-fo', '--file-author-orcid', dest='file_author_orcid', type=str, required=False, default='', help='File author ORCID' ) args = parser.parse_args(argv) filename_ck = args.output filename_xml = args.input properties = ReSpecTh_to_ChemKED(filename_xml, args.file_author, args.file_author_orcid, validate=True) # set output filename and path if not filename_ck: filename_ck = os.path.join(os.path.dirname(filename_xml), os.path.splitext(os.path.basename(filename_xml))[0] + '.yaml' ) with open(filename_ck, 'w') as outfile: yaml.dump(properties, outfile, default_flow_style=False) print('Converted to ' + filename_ck)
[ "def", "respth2ck", "(", "argv", "=", "None", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "'Convert a ReSpecTh XML file to a ChemKED YAML file.'", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--input'", ",", "type", "=", "str", ",", "required", "=", "True", ",", "help", "=", "'Input filename (e.g., \"file1.yaml\")'", ")", "parser", ".", "add_argument", "(", "'-o'", ",", "'--output'", ",", "type", "=", "str", ",", "required", "=", "False", ",", "default", "=", "''", ",", "help", "=", "'Output filename (e.g., \"file1.xml\")'", ")", "parser", ".", "add_argument", "(", "'-fa'", ",", "'--file-author'", ",", "dest", "=", "'file_author'", ",", "type", "=", "str", ",", "required", "=", "False", ",", "default", "=", "''", ",", "help", "=", "'File author name to override original'", ")", "parser", ".", "add_argument", "(", "'-fo'", ",", "'--file-author-orcid'", ",", "dest", "=", "'file_author_orcid'", ",", "type", "=", "str", ",", "required", "=", "False", ",", "default", "=", "''", ",", "help", "=", "'File author ORCID'", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "filename_ck", "=", "args", ".", "output", "filename_xml", "=", "args", ".", "input", "properties", "=", "ReSpecTh_to_ChemKED", "(", "filename_xml", ",", "args", ".", "file_author", ",", "args", ".", "file_author_orcid", ",", "validate", "=", "True", ")", "if", "not", "filename_ck", ":", "filename_ck", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "filename_xml", ")", ",", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "filename_xml", ")", ")", "[", "0", "]", "+", "'.yaml'", ")", "with", "open", "(", "filename_ck", ",", "'w'", ")", "as", "outfile", ":", "yaml", ".", "dump", "(", "properties", ",", "outfile", ",", "default_flow_style", "=", "False", ")", "print", "(", "'Converted to '", "+", "filename_ck", ")" ]
Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file.
[ "Command", "-", "line", "entry", "point", "for", "converting", "a", "ReSpecTh", "XML", "file", "to", "a", "ChemKED", "YAML", "file", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L547-L595
train
pr-omethe-us/PyKED
pyked/converters.py
ck2respth
def ck2respth(argv=None): """Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file. """ parser = ArgumentParser( description='Convert a ChemKED YAML file to a ReSpecTh XML file.' ) parser.add_argument('-i', '--input', type=str, required=True, help='Input filename (e.g., "file1.xml")' ) parser.add_argument('-o', '--output', type=str, required=False, default='', help='Output filename (e.g., "file1.yaml")' ) args = parser.parse_args(argv) c = chemked.ChemKED(yaml_file=args.input) c.convert_to_ReSpecTh(args.output)
python
def ck2respth(argv=None): """Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file. """ parser = ArgumentParser( description='Convert a ChemKED YAML file to a ReSpecTh XML file.' ) parser.add_argument('-i', '--input', type=str, required=True, help='Input filename (e.g., "file1.xml")' ) parser.add_argument('-o', '--output', type=str, required=False, default='', help='Output filename (e.g., "file1.yaml")' ) args = parser.parse_args(argv) c = chemked.ChemKED(yaml_file=args.input) c.convert_to_ReSpecTh(args.output)
[ "def", "ck2respth", "(", "argv", "=", "None", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "'Convert a ChemKED YAML file to a ReSpecTh XML file.'", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--input'", ",", "type", "=", "str", ",", "required", "=", "True", ",", "help", "=", "'Input filename (e.g., \"file1.xml\")'", ")", "parser", ".", "add_argument", "(", "'-o'", ",", "'--output'", ",", "type", "=", "str", ",", "required", "=", "False", ",", "default", "=", "''", ",", "help", "=", "'Output filename (e.g., \"file1.yaml\")'", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "c", "=", "chemked", ".", "ChemKED", "(", "yaml_file", "=", "args", ".", "input", ")", "c", ".", "convert_to_ReSpecTh", "(", "args", ".", "output", ")" ]
Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file.
[ "Command", "-", "line", "entry", "point", "for", "converting", "a", "ChemKED", "YAML", "file", "to", "a", "ReSpecTh", "XML", "file", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L598-L619
train
pr-omethe-us/PyKED
pyked/converters.py
main
def main(argv=None): """General function for converting between ReSpecTh and ChemKED files based on extension. """ parser = ArgumentParser( description='Convert between ReSpecTh XML file and ChemKED YAML file ' 'automatically based on file extension.' ) parser.add_argument('-i', '--input', type=str, required=True, help='Input filename (e.g., "file1.yaml" or "file2.xml")' ) parser.add_argument('-o', '--output', type=str, required=False, default='', help='Output filename (e.g., "file1.xml" or "file2.yaml")' ) parser.add_argument('-fa', '--file-author', dest='file_author', type=str, required=False, default='', help='File author name to override original' ) parser.add_argument('-fo', '--file-author-orcid', dest='file_author_orcid', type=str, required=False, default='', help='File author ORCID' ) args = parser.parse_args(argv) if os.path.splitext(args.input)[1] == '.xml' and os.path.splitext(args.output)[1] == '.yaml': respth2ck(['-i', args.input, '-o', args.output, '-fa', args.file_author, '-fo', args.file_author_orcid]) elif os.path.splitext(args.input)[1] == '.yaml' and os.path.splitext(args.output)[1] == '.xml': c = chemked.ChemKED(yaml_file=args.input) c.convert_to_ReSpecTh(args.output) elif os.path.splitext(args.input)[1] == '.xml' and os.path.splitext(args.output)[1] == '.xml': raise KeywordError('Cannot convert .xml to .xml') elif os.path.splitext(args.input)[1] == '.yaml' and os.path.splitext(args.output)[1] == '.yaml': raise KeywordError('Cannot convert .yaml to .yaml') else: raise KeywordError('Input/output args need to be .xml/.yaml')
python
def main(argv=None): """General function for converting between ReSpecTh and ChemKED files based on extension. """ parser = ArgumentParser( description='Convert between ReSpecTh XML file and ChemKED YAML file ' 'automatically based on file extension.' ) parser.add_argument('-i', '--input', type=str, required=True, help='Input filename (e.g., "file1.yaml" or "file2.xml")' ) parser.add_argument('-o', '--output', type=str, required=False, default='', help='Output filename (e.g., "file1.xml" or "file2.yaml")' ) parser.add_argument('-fa', '--file-author', dest='file_author', type=str, required=False, default='', help='File author name to override original' ) parser.add_argument('-fo', '--file-author-orcid', dest='file_author_orcid', type=str, required=False, default='', help='File author ORCID' ) args = parser.parse_args(argv) if os.path.splitext(args.input)[1] == '.xml' and os.path.splitext(args.output)[1] == '.yaml': respth2ck(['-i', args.input, '-o', args.output, '-fa', args.file_author, '-fo', args.file_author_orcid]) elif os.path.splitext(args.input)[1] == '.yaml' and os.path.splitext(args.output)[1] == '.xml': c = chemked.ChemKED(yaml_file=args.input) c.convert_to_ReSpecTh(args.output) elif os.path.splitext(args.input)[1] == '.xml' and os.path.splitext(args.output)[1] == '.xml': raise KeywordError('Cannot convert .xml to .xml') elif os.path.splitext(args.input)[1] == '.yaml' and os.path.splitext(args.output)[1] == '.yaml': raise KeywordError('Cannot convert .yaml to .yaml') else: raise KeywordError('Input/output args need to be .xml/.yaml')
[ "def", "main", "(", "argv", "=", "None", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "'Convert between ReSpecTh XML file and ChemKED YAML file '", "'automatically based on file extension.'", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--input'", ",", "type", "=", "str", ",", "required", "=", "True", ",", "help", "=", "'Input filename (e.g., \"file1.yaml\" or \"file2.xml\")'", ")", "parser", ".", "add_argument", "(", "'-o'", ",", "'--output'", ",", "type", "=", "str", ",", "required", "=", "False", ",", "default", "=", "''", ",", "help", "=", "'Output filename (e.g., \"file1.xml\" or \"file2.yaml\")'", ")", "parser", ".", "add_argument", "(", "'-fa'", ",", "'--file-author'", ",", "dest", "=", "'file_author'", ",", "type", "=", "str", ",", "required", "=", "False", ",", "default", "=", "''", ",", "help", "=", "'File author name to override original'", ")", "parser", ".", "add_argument", "(", "'-fo'", ",", "'--file-author-orcid'", ",", "dest", "=", "'file_author_orcid'", ",", "type", "=", "str", ",", "required", "=", "False", ",", "default", "=", "''", ",", "help", "=", "'File author ORCID'", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "if", "os", ".", "path", ".", "splitext", "(", "args", ".", "input", ")", "[", "1", "]", "==", "'.xml'", "and", "os", ".", "path", ".", "splitext", "(", "args", ".", "output", ")", "[", "1", "]", "==", "'.yaml'", ":", "respth2ck", "(", "[", "'-i'", ",", "args", ".", "input", ",", "'-o'", ",", "args", ".", "output", ",", "'-fa'", ",", "args", ".", "file_author", ",", "'-fo'", ",", "args", ".", "file_author_orcid", "]", ")", "elif", "os", ".", "path", ".", "splitext", "(", "args", ".", "input", ")", "[", "1", "]", "==", "'.yaml'", "and", "os", ".", "path", ".", "splitext", "(", "args", ".", "output", ")", "[", "1", "]", "==", "'.xml'", ":", "c", "=", "chemked", ".", "ChemKED", "(", "yaml_file", "=", "args", ".", "input", ")", "c", ".", "convert_to_ReSpecTh", "(", "args", ".", "output", ")", "elif", "os", ".", "path", ".", "splitext", "(", "args", ".", "input", ")", "[", "1", "]", "==", "'.xml'", "and", "os", ".", "path", ".", "splitext", "(", "args", ".", "output", ")", "[", "1", "]", "==", "'.xml'", ":", "raise", "KeywordError", "(", "'Cannot convert .xml to .xml'", ")", "elif", "os", ".", "path", ".", "splitext", "(", "args", ".", "input", ")", "[", "1", "]", "==", "'.yaml'", "and", "os", ".", "path", ".", "splitext", "(", "args", ".", "output", ")", "[", "1", "]", "==", "'.yaml'", ":", "raise", "KeywordError", "(", "'Cannot convert .yaml to .yaml'", ")", "else", ":", "raise", "KeywordError", "(", "'Input/output args need to be .xml/.yaml'", ")" ]
General function for converting between ReSpecTh and ChemKED files based on extension.
[ "General", "function", "for", "converting", "between", "ReSpecTh", "and", "ChemKED", "files", "based", "on", "extension", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L622-L672
train
bitlabstudio/django-libs
django_libs/middleware.py
ErrorMiddleware.process_exception
def process_exception(self, request, exception): """ Add user details. """ if request.user and hasattr(request.user, 'email'): request.META['USER'] = request.user.email
python
def process_exception(self, request, exception): """ Add user details. """ if request.user and hasattr(request.user, 'email'): request.META['USER'] = request.user.email
[ "def", "process_exception", "(", "self", ",", "request", ",", "exception", ")", ":", "if", "request", ".", "user", "and", "hasattr", "(", "request", ".", "user", ",", "'email'", ")", ":", "request", ".", "META", "[", "'USER'", "]", "=", "request", ".", "user", ".", "email" ]
Add user details.
[ "Add", "user", "details", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/middleware.py#L36-L41
train
bitlabstudio/django-libs
django_libs/middleware.py
CustomBrokenLinkEmailsMiddleware.process_response
def process_response(self, request, response): """ Send broken link emails for relevant 404 NOT FOUND responses. """ if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = force_text( request.META.get('HTTP_REFERER', ''), errors='replace') if not self.is_ignorable_request(request, path, domain, referer): ua = request.META.get('HTTP_USER_AGENT', '<none>') ip = request.META.get('REMOTE_ADDR', '<none>') user = None if request.user and hasattr(request.user, 'email'): user = request.user.email content = ( "Referrer: %s\n" "Requested URL: %s\n" "User agent: %s\n" "IP address: %s\n" "User: %s\n" ) % (referer, path, ua, ip, user) if self.is_internal_request(domain, referer): internal = 'INTERNAL ' else: internal = '' mail_managers( "Broken %slink on %s" % ( internal, domain ), content, fail_silently=True) return response
python
def process_response(self, request, response): """ Send broken link emails for relevant 404 NOT FOUND responses. """ if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = force_text( request.META.get('HTTP_REFERER', ''), errors='replace') if not self.is_ignorable_request(request, path, domain, referer): ua = request.META.get('HTTP_USER_AGENT', '<none>') ip = request.META.get('REMOTE_ADDR', '<none>') user = None if request.user and hasattr(request.user, 'email'): user = request.user.email content = ( "Referrer: %s\n" "Requested URL: %s\n" "User agent: %s\n" "IP address: %s\n" "User: %s\n" ) % (referer, path, ua, ip, user) if self.is_internal_request(domain, referer): internal = 'INTERNAL ' else: internal = '' mail_managers( "Broken %slink on %s" % ( internal, domain ), content, fail_silently=True) return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "response", ".", "status_code", "==", "404", "and", "not", "settings", ".", "DEBUG", ":", "domain", "=", "request", ".", "get_host", "(", ")", "path", "=", "request", ".", "get_full_path", "(", ")", "referer", "=", "force_text", "(", "request", ".", "META", ".", "get", "(", "'HTTP_REFERER'", ",", "''", ")", ",", "errors", "=", "'replace'", ")", "if", "not", "self", ".", "is_ignorable_request", "(", "request", ",", "path", ",", "domain", ",", "referer", ")", ":", "ua", "=", "request", ".", "META", ".", "get", "(", "'HTTP_USER_AGENT'", ",", "'<none>'", ")", "ip", "=", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ",", "'<none>'", ")", "user", "=", "None", "if", "request", ".", "user", "and", "hasattr", "(", "request", ".", "user", ",", "'email'", ")", ":", "user", "=", "request", ".", "user", ".", "email", "content", "=", "(", "\"Referrer: %s\\n\"", "\"Requested URL: %s\\n\"", "\"User agent: %s\\n\"", "\"IP address: %s\\n\"", "\"User: %s\\n\"", ")", "%", "(", "referer", ",", "path", ",", "ua", ",", "ip", ",", "user", ")", "if", "self", ".", "is_internal_request", "(", "domain", ",", "referer", ")", ":", "internal", "=", "'INTERNAL '", "else", ":", "internal", "=", "''", "mail_managers", "(", "\"Broken %slink on %s\"", "%", "(", "internal", ",", "domain", ")", ",", "content", ",", "fail_silently", "=", "True", ")", "return", "response" ]
Send broken link emails for relevant 404 NOT FOUND responses.
[ "Send", "broken", "link", "emails", "for", "relevant", "404", "NOT", "FOUND", "responses", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/middleware.py#L94-L129
train
bitlabstudio/django-libs
django_libs/middleware.py
CustomBrokenLinkEmailsMiddleware.is_internal_request
def is_internal_request(self, domain, referer): """ Returns True if referring URL is the same domain as current request. """ # Different subdomains are treated as different domains. return bool(re.match("^https?://%s/" % re.escape(domain), referer))
python
def is_internal_request(self, domain, referer): """ Returns True if referring URL is the same domain as current request. """ # Different subdomains are treated as different domains. return bool(re.match("^https?://%s/" % re.escape(domain), referer))
[ "def", "is_internal_request", "(", "self", ",", "domain", ",", "referer", ")", ":", "return", "bool", "(", "re", ".", "match", "(", "\"^https?://%s/\"", "%", "re", ".", "escape", "(", "domain", ")", ",", "referer", ")", ")" ]
Returns True if referring URL is the same domain as current request.
[ "Returns", "True", "if", "referring", "URL", "is", "the", "same", "domain", "as", "current", "request", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/middleware.py#L131-L137
train
oleiade/durations
durations/duration.py
Duration.parse
def parse(self, representation): """Parses a duration string representation :param representation: duration as a string, example: '1d' (day), '34minutes' (minutes), '485s' (seconds)... :type representation: string :returns: the parsed duration representation :rtype: DurationRepresentation """ elements = extract_tokens(representation) try: scales = [DurationRepresentation(float(p[0]), Scale(p[1])) for p in elements] except ValueError: raise ScaleFormatError("Malformed duration representation: {0}".format(representation)) return scales
python
def parse(self, representation): """Parses a duration string representation :param representation: duration as a string, example: '1d' (day), '34minutes' (minutes), '485s' (seconds)... :type representation: string :returns: the parsed duration representation :rtype: DurationRepresentation """ elements = extract_tokens(representation) try: scales = [DurationRepresentation(float(p[0]), Scale(p[1])) for p in elements] except ValueError: raise ScaleFormatError("Malformed duration representation: {0}".format(representation)) return scales
[ "def", "parse", "(", "self", ",", "representation", ")", ":", "elements", "=", "extract_tokens", "(", "representation", ")", "try", ":", "scales", "=", "[", "DurationRepresentation", "(", "float", "(", "p", "[", "0", "]", ")", ",", "Scale", "(", "p", "[", "1", "]", ")", ")", "for", "p", "in", "elements", "]", "except", "ValueError", ":", "raise", "ScaleFormatError", "(", "\"Malformed duration representation: {0}\"", ".", "format", "(", "representation", ")", ")", "return", "scales" ]
Parses a duration string representation :param representation: duration as a string, example: '1d' (day), '34minutes' (minutes), '485s' (seconds)... :type representation: string :returns: the parsed duration representation :rtype: DurationRepresentation
[ "Parses", "a", "duration", "string", "representation" ]
62c176dfa7d36d5c59bf93bdebfdc80ab53757bd
https://github.com/oleiade/durations/blob/62c176dfa7d36d5c59bf93bdebfdc80ab53757bd/durations/duration.py#L53-L71
train
Genida/django-meerkat
src/meerkat/logs/models.py
IPInfo.get_or_create_from_ip
def get_or_create_from_ip(ip): """ Get or create an entry using obtained information from an IP. Args: ip (str): IP address xxx.xxx.xxx.xxx. Returns: ip_info: an instance of IPInfo. """ data = ip_api_handler.get(ip) if data and any(v for v in data.values()): if data.get('ip_address', None) is None or not data['ip_address']: data['ip_address'] = ip return IPInfo.objects.get_or_create(**data) return None, False
python
def get_or_create_from_ip(ip): """ Get or create an entry using obtained information from an IP. Args: ip (str): IP address xxx.xxx.xxx.xxx. Returns: ip_info: an instance of IPInfo. """ data = ip_api_handler.get(ip) if data and any(v for v in data.values()): if data.get('ip_address', None) is None or not data['ip_address']: data['ip_address'] = ip return IPInfo.objects.get_or_create(**data) return None, False
[ "def", "get_or_create_from_ip", "(", "ip", ")", ":", "data", "=", "ip_api_handler", ".", "get", "(", "ip", ")", "if", "data", "and", "any", "(", "v", "for", "v", "in", "data", ".", "values", "(", ")", ")", ":", "if", "data", ".", "get", "(", "'ip_address'", ",", "None", ")", "is", "None", "or", "not", "data", "[", "'ip_address'", "]", ":", "data", "[", "'ip_address'", "]", "=", "ip", "return", "IPInfo", ".", "objects", ".", "get_or_create", "(", "**", "data", ")", "return", "None", ",", "False" ]
Get or create an entry using obtained information from an IP. Args: ip (str): IP address xxx.xxx.xxx.xxx. Returns: ip_info: an instance of IPInfo.
[ "Get", "or", "create", "an", "entry", "using", "obtained", "information", "from", "an", "IP", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L128-L143
train
Genida/django-meerkat
src/meerkat/logs/models.py
RequestLog.update_ip_info
def update_ip_info(self, since_days=10, save=False, force=False): """ Update the IP info. Args: since_days (int): if checked less than this number of days ago, don't check again (default to 10 days). save (bool): whether to save anyway or not. force (bool): whether to update ip_info to last checked one. Returns: bool: check was run. IPInfo might not have been updated. """ # If ip already checked try: last_check = IPInfoCheck.objects.get( ip_address=self.client_ip_address) # If checked less than since_days ago, don't check again since_last = datetime.date.today() - last_check.date if since_last <= datetime.timedelta(days=since_days): if not self.ip_info or ( self.ip_info != last_check.ip_info and force): self.ip_info = last_check.ip_info self.save() return True elif save: self.save() return False # Get or create ip_info object ip_info, created = IPInfo.get_or_create_from_ip( self.client_ip_address) # Update check time last_check.date = datetime.date.today() last_check.save() # Maybe data changed if created: last_check.ip_info = ip_info self.ip_info = ip_info self.save() return True elif save: self.save() return False except IPInfoCheck.DoesNotExist: # Else if ip never checked, check it and set ip_info self.ip_info = IPInfoCheck.check_ip(self.client_ip_address) self.save() return True
python
def update_ip_info(self, since_days=10, save=False, force=False): """ Update the IP info. Args: since_days (int): if checked less than this number of days ago, don't check again (default to 10 days). save (bool): whether to save anyway or not. force (bool): whether to update ip_info to last checked one. Returns: bool: check was run. IPInfo might not have been updated. """ # If ip already checked try: last_check = IPInfoCheck.objects.get( ip_address=self.client_ip_address) # If checked less than since_days ago, don't check again since_last = datetime.date.today() - last_check.date if since_last <= datetime.timedelta(days=since_days): if not self.ip_info or ( self.ip_info != last_check.ip_info and force): self.ip_info = last_check.ip_info self.save() return True elif save: self.save() return False # Get or create ip_info object ip_info, created = IPInfo.get_or_create_from_ip( self.client_ip_address) # Update check time last_check.date = datetime.date.today() last_check.save() # Maybe data changed if created: last_check.ip_info = ip_info self.ip_info = ip_info self.save() return True elif save: self.save() return False except IPInfoCheck.DoesNotExist: # Else if ip never checked, check it and set ip_info self.ip_info = IPInfoCheck.check_ip(self.client_ip_address) self.save() return True
[ "def", "update_ip_info", "(", "self", ",", "since_days", "=", "10", ",", "save", "=", "False", ",", "force", "=", "False", ")", ":", "try", ":", "last_check", "=", "IPInfoCheck", ".", "objects", ".", "get", "(", "ip_address", "=", "self", ".", "client_ip_address", ")", "since_last", "=", "datetime", ".", "date", ".", "today", "(", ")", "-", "last_check", ".", "date", "if", "since_last", "<=", "datetime", ".", "timedelta", "(", "days", "=", "since_days", ")", ":", "if", "not", "self", ".", "ip_info", "or", "(", "self", ".", "ip_info", "!=", "last_check", ".", "ip_info", "and", "force", ")", ":", "self", ".", "ip_info", "=", "last_check", ".", "ip_info", "self", ".", "save", "(", ")", "return", "True", "elif", "save", ":", "self", ".", "save", "(", ")", "return", "False", "ip_info", ",", "created", "=", "IPInfo", ".", "get_or_create_from_ip", "(", "self", ".", "client_ip_address", ")", "last_check", ".", "date", "=", "datetime", ".", "date", ".", "today", "(", ")", "last_check", ".", "save", "(", ")", "if", "created", ":", "last_check", ".", "ip_info", "=", "ip_info", "self", ".", "ip_info", "=", "ip_info", "self", ".", "save", "(", ")", "return", "True", "elif", "save", ":", "self", ".", "save", "(", ")", "return", "False", "except", "IPInfoCheck", ".", "DoesNotExist", ":", "self", ".", "ip_info", "=", "IPInfoCheck", ".", "check_ip", "(", "self", ".", "client_ip_address", ")", "self", ".", "save", "(", ")", "return", "True" ]
Update the IP info. Args: since_days (int): if checked less than this number of days ago, don't check again (default to 10 days). save (bool): whether to save anyway or not. force (bool): whether to update ip_info to last checked one. Returns: bool: check was run. IPInfo might not have been updated.
[ "Update", "the", "IP", "info", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L333-L387
train
Genida/django-meerkat
src/meerkat/logs/models.py
RequestLog.start_daemon
def start_daemon(): """ Start a thread to continuously read log files and append lines in DB. Work in progress. Currently the thread doesn't append anything, it only print the information parsed from each line read. Returns: thread: the started thread. """ if RequestLog.daemon is None: parser = get_nginx_parser() RequestLog.daemon = RequestLog.ParseToDBThread(parser, daemon=True) RequestLog.daemon.start() return RequestLog.daemon
python
def start_daemon(): """ Start a thread to continuously read log files and append lines in DB. Work in progress. Currently the thread doesn't append anything, it only print the information parsed from each line read. Returns: thread: the started thread. """ if RequestLog.daemon is None: parser = get_nginx_parser() RequestLog.daemon = RequestLog.ParseToDBThread(parser, daemon=True) RequestLog.daemon.start() return RequestLog.daemon
[ "def", "start_daemon", "(", ")", ":", "if", "RequestLog", ".", "daemon", "is", "None", ":", "parser", "=", "get_nginx_parser", "(", ")", "RequestLog", ".", "daemon", "=", "RequestLog", ".", "ParseToDBThread", "(", "parser", ",", "daemon", "=", "True", ")", "RequestLog", ".", "daemon", ".", "start", "(", ")", "return", "RequestLog", ".", "daemon" ]
Start a thread to continuously read log files and append lines in DB. Work in progress. Currently the thread doesn't append anything, it only print the information parsed from each line read. Returns: thread: the started thread.
[ "Start", "a", "thread", "to", "continuously", "read", "log", "files", "and", "append", "lines", "in", "DB", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L648-L662
train
pr-omethe-us/PyKED
pyked/chemked.py
ChemKED.from_respecth
def from_respecth(cls, filename_xml, file_author='', file_author_orcid=''): """Construct a ChemKED instance directly from a ReSpecTh file. Arguments: filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported file_author (`str`, optional): File author to be added to the list generated from the XML file file_author_orcid (`str`, optional): ORCID for the file author being added to the list of file authors Returns: `ChemKED`: Instance of the `ChemKED` class containing the data in ``filename_xml``. Examples: >>> ck = ChemKED.from_respecth('respecth_file.xml') >>> ck = ChemKED.from_respecth('respecth_file.xml', file_author='Bryan W. Weber') >>> ck = ChemKED.from_respecth('respecth_file.xml', file_author='Bryan W. Weber', file_author_orcid='0000-0000-0000-0000') """ properties = ReSpecTh_to_ChemKED(filename_xml, file_author, file_author_orcid, validate=False) return cls(dict_input=properties)
python
def from_respecth(cls, filename_xml, file_author='', file_author_orcid=''): """Construct a ChemKED instance directly from a ReSpecTh file. Arguments: filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported file_author (`str`, optional): File author to be added to the list generated from the XML file file_author_orcid (`str`, optional): ORCID for the file author being added to the list of file authors Returns: `ChemKED`: Instance of the `ChemKED` class containing the data in ``filename_xml``. Examples: >>> ck = ChemKED.from_respecth('respecth_file.xml') >>> ck = ChemKED.from_respecth('respecth_file.xml', file_author='Bryan W. Weber') >>> ck = ChemKED.from_respecth('respecth_file.xml', file_author='Bryan W. Weber', file_author_orcid='0000-0000-0000-0000') """ properties = ReSpecTh_to_ChemKED(filename_xml, file_author, file_author_orcid, validate=False) return cls(dict_input=properties)
[ "def", "from_respecth", "(", "cls", ",", "filename_xml", ",", "file_author", "=", "''", ",", "file_author_orcid", "=", "''", ")", ":", "properties", "=", "ReSpecTh_to_ChemKED", "(", "filename_xml", ",", "file_author", ",", "file_author_orcid", ",", "validate", "=", "False", ")", "return", "cls", "(", "dict_input", "=", "properties", ")" ]
Construct a ChemKED instance directly from a ReSpecTh file. Arguments: filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported file_author (`str`, optional): File author to be added to the list generated from the XML file file_author_orcid (`str`, optional): ORCID for the file author being added to the list of file authors Returns: `ChemKED`: Instance of the `ChemKED` class containing the data in ``filename_xml``. Examples: >>> ck = ChemKED.from_respecth('respecth_file.xml') >>> ck = ChemKED.from_respecth('respecth_file.xml', file_author='Bryan W. Weber') >>> ck = ChemKED.from_respecth('respecth_file.xml', file_author='Bryan W. Weber', file_author_orcid='0000-0000-0000-0000')
[ "Construct", "a", "ChemKED", "instance", "directly", "from", "a", "ReSpecTh", "file", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L146-L167
train
pr-omethe-us/PyKED
pyked/chemked.py
ChemKED.validate_yaml
def validate_yaml(self, properties): """Validate the parsed YAML file for adherance to the ChemKED format. Arguments: properties (`dict`): Dictionary created from the parsed YAML file Raises: `ValueError`: If the YAML file cannot be validated, a `ValueError` is raised whose string contains the errors that are present. """ validator = OurValidator(schema) if not validator.validate(properties): for key, value in validator.errors.items(): if any(['unallowed value' in v for v in value]): print(('{key} has an illegal value. Allowed values are {values} and are case ' 'sensitive.').format(key=key, values=schema[key]['allowed'])) raise ValueError(validator.errors)
python
def validate_yaml(self, properties): """Validate the parsed YAML file for adherance to the ChemKED format. Arguments: properties (`dict`): Dictionary created from the parsed YAML file Raises: `ValueError`: If the YAML file cannot be validated, a `ValueError` is raised whose string contains the errors that are present. """ validator = OurValidator(schema) if not validator.validate(properties): for key, value in validator.errors.items(): if any(['unallowed value' in v for v in value]): print(('{key} has an illegal value. Allowed values are {values} and are case ' 'sensitive.').format(key=key, values=schema[key]['allowed'])) raise ValueError(validator.errors)
[ "def", "validate_yaml", "(", "self", ",", "properties", ")", ":", "validator", "=", "OurValidator", "(", "schema", ")", "if", "not", "validator", ".", "validate", "(", "properties", ")", ":", "for", "key", ",", "value", "in", "validator", ".", "errors", ".", "items", "(", ")", ":", "if", "any", "(", "[", "'unallowed value'", "in", "v", "for", "v", "in", "value", "]", ")", ":", "print", "(", "(", "'{key} has an illegal value. Allowed values are {values} and are case '", "'sensitive.'", ")", ".", "format", "(", "key", "=", "key", ",", "values", "=", "schema", "[", "key", "]", "[", "'allowed'", "]", ")", ")", "raise", "ValueError", "(", "validator", ".", "errors", ")" ]
Validate the parsed YAML file for adherance to the ChemKED format. Arguments: properties (`dict`): Dictionary created from the parsed YAML file Raises: `ValueError`: If the YAML file cannot be validated, a `ValueError` is raised whose string contains the errors that are present.
[ "Validate", "the", "parsed", "YAML", "file", "for", "adherance", "to", "the", "ChemKED", "format", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L169-L186
train
pr-omethe-us/PyKED
pyked/chemked.py
ChemKED.write_file
def write_file(self, filename, *, overwrite=False): """Write new ChemKED YAML file based on object. Arguments: filename (`str`): Filename for target YAML file overwrite (`bool`, optional): Whether to overwrite file with given name if present. Must be supplied as a keyword-argument. Raises: `NameError`: If ``filename`` is already present, and ``overwrite`` is not ``True``. Example: >>> dataset = ChemKED(yaml_file) >>> dataset.write_file(new_yaml_file) """ # Ensure file isn't already present if exists(filename) and not overwrite: raise OSError(filename + ' already present. Specify "overwrite=True" ' 'to overwrite, or rename.' ) with open(filename, 'w') as yaml_file: yaml.dump(self._properties, yaml_file)
python
def write_file(self, filename, *, overwrite=False): """Write new ChemKED YAML file based on object. Arguments: filename (`str`): Filename for target YAML file overwrite (`bool`, optional): Whether to overwrite file with given name if present. Must be supplied as a keyword-argument. Raises: `NameError`: If ``filename`` is already present, and ``overwrite`` is not ``True``. Example: >>> dataset = ChemKED(yaml_file) >>> dataset.write_file(new_yaml_file) """ # Ensure file isn't already present if exists(filename) and not overwrite: raise OSError(filename + ' already present. Specify "overwrite=True" ' 'to overwrite, or rename.' ) with open(filename, 'w') as yaml_file: yaml.dump(self._properties, yaml_file)
[ "def", "write_file", "(", "self", ",", "filename", ",", "*", ",", "overwrite", "=", "False", ")", ":", "if", "exists", "(", "filename", ")", "and", "not", "overwrite", ":", "raise", "OSError", "(", "filename", "+", "' already present. Specify \"overwrite=True\" '", "'to overwrite, or rename.'", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "yaml_file", ":", "yaml", ".", "dump", "(", "self", ".", "_properties", ",", "yaml_file", ")" ]
Write new ChemKED YAML file based on object. Arguments: filename (`str`): Filename for target YAML file overwrite (`bool`, optional): Whether to overwrite file with given name if present. Must be supplied as a keyword-argument. Raises: `NameError`: If ``filename`` is already present, and ``overwrite`` is not ``True``. Example: >>> dataset = ChemKED(yaml_file) >>> dataset.write_file(new_yaml_file)
[ "Write", "new", "ChemKED", "YAML", "file", "based", "on", "object", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L310-L332
train
pr-omethe-us/PyKED
pyked/chemked.py
DataPoint.process_quantity
def process_quantity(self, properties): """Process the uncertainty information from a given quantity and return it """ quant = Q_(properties[0]) if len(properties) > 1: unc = properties[1] uncertainty = unc.get('uncertainty', False) upper_uncertainty = unc.get('upper-uncertainty', False) lower_uncertainty = unc.get('lower-uncertainty', False) uncertainty_type = unc.get('uncertainty-type') if uncertainty_type == 'relative': if uncertainty: quant = quant.plus_minus(float(uncertainty), relative=True) elif upper_uncertainty and lower_uncertainty: warn('Asymmetric uncertainties are not supported. The ' 'maximum of lower-uncertainty and upper-uncertainty ' 'has been used as the symmetric uncertainty.') uncertainty = max(float(upper_uncertainty), float(lower_uncertainty)) quant = quant.plus_minus(uncertainty, relative=True) else: raise ValueError('Either "uncertainty" or "upper-uncertainty" and ' '"lower-uncertainty" need to be specified.') elif uncertainty_type == 'absolute': if uncertainty: uncertainty = Q_(uncertainty) quant = quant.plus_minus(uncertainty.to(quant.units).magnitude) elif upper_uncertainty and lower_uncertainty: warn('Asymmetric uncertainties are not supported. The ' 'maximum of lower-uncertainty and upper-uncertainty ' 'has been used as the symmetric uncertainty.') uncertainty = max(Q_(upper_uncertainty), Q_(lower_uncertainty)) quant = quant.plus_minus(uncertainty.to(quant.units).magnitude) else: raise ValueError('Either "uncertainty" or "upper-uncertainty" and ' '"lower-uncertainty" need to be specified.') else: raise ValueError('uncertainty-type must be one of "absolute" or "relative"') return quant
python
def process_quantity(self, properties): """Process the uncertainty information from a given quantity and return it """ quant = Q_(properties[0]) if len(properties) > 1: unc = properties[1] uncertainty = unc.get('uncertainty', False) upper_uncertainty = unc.get('upper-uncertainty', False) lower_uncertainty = unc.get('lower-uncertainty', False) uncertainty_type = unc.get('uncertainty-type') if uncertainty_type == 'relative': if uncertainty: quant = quant.plus_minus(float(uncertainty), relative=True) elif upper_uncertainty and lower_uncertainty: warn('Asymmetric uncertainties are not supported. The ' 'maximum of lower-uncertainty and upper-uncertainty ' 'has been used as the symmetric uncertainty.') uncertainty = max(float(upper_uncertainty), float(lower_uncertainty)) quant = quant.plus_minus(uncertainty, relative=True) else: raise ValueError('Either "uncertainty" or "upper-uncertainty" and ' '"lower-uncertainty" need to be specified.') elif uncertainty_type == 'absolute': if uncertainty: uncertainty = Q_(uncertainty) quant = quant.plus_minus(uncertainty.to(quant.units).magnitude) elif upper_uncertainty and lower_uncertainty: warn('Asymmetric uncertainties are not supported. The ' 'maximum of lower-uncertainty and upper-uncertainty ' 'has been used as the symmetric uncertainty.') uncertainty = max(Q_(upper_uncertainty), Q_(lower_uncertainty)) quant = quant.plus_minus(uncertainty.to(quant.units).magnitude) else: raise ValueError('Either "uncertainty" or "upper-uncertainty" and ' '"lower-uncertainty" need to be specified.') else: raise ValueError('uncertainty-type must be one of "absolute" or "relative"') return quant
[ "def", "process_quantity", "(", "self", ",", "properties", ")", ":", "quant", "=", "Q_", "(", "properties", "[", "0", "]", ")", "if", "len", "(", "properties", ")", ">", "1", ":", "unc", "=", "properties", "[", "1", "]", "uncertainty", "=", "unc", ".", "get", "(", "'uncertainty'", ",", "False", ")", "upper_uncertainty", "=", "unc", ".", "get", "(", "'upper-uncertainty'", ",", "False", ")", "lower_uncertainty", "=", "unc", ".", "get", "(", "'lower-uncertainty'", ",", "False", ")", "uncertainty_type", "=", "unc", ".", "get", "(", "'uncertainty-type'", ")", "if", "uncertainty_type", "==", "'relative'", ":", "if", "uncertainty", ":", "quant", "=", "quant", ".", "plus_minus", "(", "float", "(", "uncertainty", ")", ",", "relative", "=", "True", ")", "elif", "upper_uncertainty", "and", "lower_uncertainty", ":", "warn", "(", "'Asymmetric uncertainties are not supported. The '", "'maximum of lower-uncertainty and upper-uncertainty '", "'has been used as the symmetric uncertainty.'", ")", "uncertainty", "=", "max", "(", "float", "(", "upper_uncertainty", ")", ",", "float", "(", "lower_uncertainty", ")", ")", "quant", "=", "quant", ".", "plus_minus", "(", "uncertainty", ",", "relative", "=", "True", ")", "else", ":", "raise", "ValueError", "(", "'Either \"uncertainty\" or \"upper-uncertainty\" and '", "'\"lower-uncertainty\" need to be specified.'", ")", "elif", "uncertainty_type", "==", "'absolute'", ":", "if", "uncertainty", ":", "uncertainty", "=", "Q_", "(", "uncertainty", ")", "quant", "=", "quant", ".", "plus_minus", "(", "uncertainty", ".", "to", "(", "quant", ".", "units", ")", ".", "magnitude", ")", "elif", "upper_uncertainty", "and", "lower_uncertainty", ":", "warn", "(", "'Asymmetric uncertainties are not supported. The '", "'maximum of lower-uncertainty and upper-uncertainty '", "'has been used as the symmetric uncertainty.'", ")", "uncertainty", "=", "max", "(", "Q_", "(", "upper_uncertainty", ")", ",", "Q_", "(", "lower_uncertainty", ")", ")", "quant", "=", "quant", ".", "plus_minus", "(", "uncertainty", ".", "to", "(", "quant", ".", "units", ")", ".", "magnitude", ")", "else", ":", "raise", "ValueError", "(", "'Either \"uncertainty\" or \"upper-uncertainty\" and '", "'\"lower-uncertainty\" need to be specified.'", ")", "else", ":", "raise", "ValueError", "(", "'uncertainty-type must be one of \"absolute\" or \"relative\"'", ")", "return", "quant" ]
Process the uncertainty information from a given quantity and return it
[ "Process", "the", "uncertainty", "information", "from", "a", "given", "quantity", "and", "return", "it" ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L722-L760
train
pr-omethe-us/PyKED
pyked/chemked.py
DataPoint.get_cantera_composition_string
def get_cantera_composition_string(self, species_conversion=None): """Get the composition in a string format suitable for input to Cantera. Returns a formatted string no matter the type of composition. As such, this method is not recommended for end users; instead, prefer the `get_cantera_mole_fraction` or `get_cantera_mass_fraction` methods. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type of the `DataPoint` is not one of ``'mass fraction'``, ``'mole fraction'``, or ``'mole percent'`` """ if self.composition_type in ['mole fraction', 'mass fraction']: factor = 1.0 elif self.composition_type == 'mole percent': factor = 100.0 else: raise ValueError('Unknown composition type: {}'.format(self.composition_type)) if species_conversion is None: comps = ['{!s}:{:.4e}'.format(c.species_name, c.amount.magnitude/factor) for c in self.composition.values()] else: comps = [] for c in self.composition.values(): amount = c.amount.magnitude/factor idents = [getattr(c, s, False) for s in ['species_name', 'InChI', 'SMILES']] present = [i in species_conversion for i in idents] if not any(present): comps.append('{!s}:{:.4e}'.format(c.species_name, amount)) else: if len([i for i in present if i]) > 1: raise ValueError('More than one conversion present for species {}'.format( c.species_name)) ident = idents[present.index(True)] species_replacement_name = species_conversion.pop(ident) comps.append('{!s}:{:.4e}'.format(species_replacement_name, amount)) if len(species_conversion) > 0: raise ValueError('Unknown species in conversion: {}'.format(species_conversion)) return ', '.join(comps)
python
def get_cantera_composition_string(self, species_conversion=None): """Get the composition in a string format suitable for input to Cantera. Returns a formatted string no matter the type of composition. As such, this method is not recommended for end users; instead, prefer the `get_cantera_mole_fraction` or `get_cantera_mass_fraction` methods. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type of the `DataPoint` is not one of ``'mass fraction'``, ``'mole fraction'``, or ``'mole percent'`` """ if self.composition_type in ['mole fraction', 'mass fraction']: factor = 1.0 elif self.composition_type == 'mole percent': factor = 100.0 else: raise ValueError('Unknown composition type: {}'.format(self.composition_type)) if species_conversion is None: comps = ['{!s}:{:.4e}'.format(c.species_name, c.amount.magnitude/factor) for c in self.composition.values()] else: comps = [] for c in self.composition.values(): amount = c.amount.magnitude/factor idents = [getattr(c, s, False) for s in ['species_name', 'InChI', 'SMILES']] present = [i in species_conversion for i in idents] if not any(present): comps.append('{!s}:{:.4e}'.format(c.species_name, amount)) else: if len([i for i in present if i]) > 1: raise ValueError('More than one conversion present for species {}'.format( c.species_name)) ident = idents[present.index(True)] species_replacement_name = species_conversion.pop(ident) comps.append('{!s}:{:.4e}'.format(species_replacement_name, amount)) if len(species_conversion) > 0: raise ValueError('Unknown species in conversion: {}'.format(species_conversion)) return ', '.join(comps)
[ "def", "get_cantera_composition_string", "(", "self", ",", "species_conversion", "=", "None", ")", ":", "if", "self", ".", "composition_type", "in", "[", "'mole fraction'", ",", "'mass fraction'", "]", ":", "factor", "=", "1.0", "elif", "self", ".", "composition_type", "==", "'mole percent'", ":", "factor", "=", "100.0", "else", ":", "raise", "ValueError", "(", "'Unknown composition type: {}'", ".", "format", "(", "self", ".", "composition_type", ")", ")", "if", "species_conversion", "is", "None", ":", "comps", "=", "[", "'{!s}:{:.4e}'", ".", "format", "(", "c", ".", "species_name", ",", "c", ".", "amount", ".", "magnitude", "/", "factor", ")", "for", "c", "in", "self", ".", "composition", ".", "values", "(", ")", "]", "else", ":", "comps", "=", "[", "]", "for", "c", "in", "self", ".", "composition", ".", "values", "(", ")", ":", "amount", "=", "c", ".", "amount", ".", "magnitude", "/", "factor", "idents", "=", "[", "getattr", "(", "c", ",", "s", ",", "False", ")", "for", "s", "in", "[", "'species_name'", ",", "'InChI'", ",", "'SMILES'", "]", "]", "present", "=", "[", "i", "in", "species_conversion", "for", "i", "in", "idents", "]", "if", "not", "any", "(", "present", ")", ":", "comps", ".", "append", "(", "'{!s}:{:.4e}'", ".", "format", "(", "c", ".", "species_name", ",", "amount", ")", ")", "else", ":", "if", "len", "(", "[", "i", "for", "i", "in", "present", "if", "i", "]", ")", ">", "1", ":", "raise", "ValueError", "(", "'More than one conversion present for species {}'", ".", "format", "(", "c", ".", "species_name", ")", ")", "ident", "=", "idents", "[", "present", ".", "index", "(", "True", ")", "]", "species_replacement_name", "=", "species_conversion", ".", "pop", "(", "ident", ")", "comps", ".", "append", "(", "'{!s}:{:.4e}'", ".", "format", "(", "species_replacement_name", ",", "amount", ")", ")", "if", "len", "(", "species_conversion", ")", ">", "0", ":", "raise", "ValueError", "(", "'Unknown species in conversion: {}'", ".", "format", "(", "species_conversion", ")", ")", "return", "', '", ".", "join", "(", "comps", ")" ]
Get the composition in a string format suitable for input to Cantera. Returns a formatted string no matter the type of composition. As such, this method is not recommended for end users; instead, prefer the `get_cantera_mole_fraction` or `get_cantera_mass_fraction` methods. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type of the `DataPoint` is not one of ``'mass fraction'``, ``'mole fraction'``, or ``'mole percent'``
[ "Get", "the", "composition", "in", "a", "string", "format", "suitable", "for", "input", "to", "Cantera", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L762-L815
train
pr-omethe-us/PyKED
pyked/chemked.py
DataPoint.get_cantera_mole_fraction
def get_cantera_mole_fraction(self, species_conversion=None): """Get the mole fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mole fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mass fraction'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mole_fraction() 'H2:4.4400e-03, O2:5.5600e-03, Ar:9.9000e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mole_fraction(species_conversion) 'h2:4.4400e-03, o2:5.5600e-03, Ar:9.9000e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mole_fraction(species_conversion) 'h2:4.4400e-03, o2:5.5600e-03, Ar:9.9000e-01' """ if self.composition_type == 'mass fraction': raise ValueError('Cannot get mole fractions from the given composition.\n' '{}'.format(self.composition)) else: return self.get_cantera_composition_string(species_conversion)
python
def get_cantera_mole_fraction(self, species_conversion=None): """Get the mole fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mole fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mass fraction'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mole_fraction() 'H2:4.4400e-03, O2:5.5600e-03, Ar:9.9000e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mole_fraction(species_conversion) 'h2:4.4400e-03, o2:5.5600e-03, Ar:9.9000e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mole_fraction(species_conversion) 'h2:4.4400e-03, o2:5.5600e-03, Ar:9.9000e-01' """ if self.composition_type == 'mass fraction': raise ValueError('Cannot get mole fractions from the given composition.\n' '{}'.format(self.composition)) else: return self.get_cantera_composition_string(species_conversion)
[ "def", "get_cantera_mole_fraction", "(", "self", ",", "species_conversion", "=", "None", ")", ":", "if", "self", ".", "composition_type", "==", "'mass fraction'", ":", "raise", "ValueError", "(", "'Cannot get mole fractions from the given composition.\\n'", "'{}'", ".", "format", "(", "self", ".", "composition", ")", ")", "else", ":", "return", "self", ".", "get_cantera_composition_string", "(", "species_conversion", ")" ]
Get the mole fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mole fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mass fraction'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mole_fraction() 'H2:4.4400e-03, O2:5.5600e-03, Ar:9.9000e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mole_fraction(species_conversion) 'h2:4.4400e-03, o2:5.5600e-03, Ar:9.9000e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mole_fraction(species_conversion) 'h2:4.4400e-03, o2:5.5600e-03, Ar:9.9000e-01'
[ "Get", "the", "mole", "fractions", "in", "a", "string", "format", "suitable", "for", "input", "to", "Cantera", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L817-L851
train
pr-omethe-us/PyKED
pyked/chemked.py
DataPoint.get_cantera_mass_fraction
def get_cantera_mass_fraction(self, species_conversion=None): """Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mass fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mole fraction'`` or ``'mole percent'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mass_fraction() 'H2:2.2525e-04, O2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' """ if self.composition_type in ['mole fraction', 'mole percent']: raise ValueError('Cannot get mass fractions from the given composition.\n' '{}'.format(self.composition) ) else: return self.get_cantera_composition_string(species_conversion)
python
def get_cantera_mass_fraction(self, species_conversion=None): """Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mass fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mole fraction'`` or ``'mole percent'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mass_fraction() 'H2:2.2525e-04, O2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' """ if self.composition_type in ['mole fraction', 'mole percent']: raise ValueError('Cannot get mass fractions from the given composition.\n' '{}'.format(self.composition) ) else: return self.get_cantera_composition_string(species_conversion)
[ "def", "get_cantera_mass_fraction", "(", "self", ",", "species_conversion", "=", "None", ")", ":", "if", "self", ".", "composition_type", "in", "[", "'mole fraction'", ",", "'mole percent'", "]", ":", "raise", "ValueError", "(", "'Cannot get mass fractions from the given composition.\\n'", "'{}'", ".", "format", "(", "self", ".", "composition", ")", ")", "else", ":", "return", "self", ".", "get_cantera_composition_string", "(", "species_conversion", ")" ]
Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mass fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mole fraction'`` or ``'mole percent'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mass_fraction() 'H2:2.2525e-04, O2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01'
[ "Get", "the", "mass", "fractions", "in", "a", "string", "format", "suitable", "for", "input", "to", "Cantera", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/chemked.py#L853-L889
train
bitlabstudio/django-libs
django_libs/decorators.py
lockfile
def lockfile(lockfile_name, lock_wait_timeout=-1): """ Only runs the method if the lockfile is not acquired. You should create a setting ``LOCKFILE_PATH`` which points to ``/home/username/tmp/``. In your management command, use it like so:: LOCKFILE = os.path.join( settings.LOCKFILE_FOLDER, 'command_name') class Command(NoArgsCommand): @lockfile(LOCKFILE) def handle_noargs(self, **options): # your command here :lockfile_name: A unique name for a lockfile that belongs to the wrapped method. :lock_wait_timeout: Seconds to wait if lockfile is acquired. If ``-1`` we will not wait and just quit. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): lock = FileLock(lockfile_name) try: lock.acquire(lock_wait_timeout) except AlreadyLocked: return except LockTimeout: return try: result = func(*args, **kwargs) finally: lock.release() return result return wrapper return decorator
python
def lockfile(lockfile_name, lock_wait_timeout=-1): """ Only runs the method if the lockfile is not acquired. You should create a setting ``LOCKFILE_PATH`` which points to ``/home/username/tmp/``. In your management command, use it like so:: LOCKFILE = os.path.join( settings.LOCKFILE_FOLDER, 'command_name') class Command(NoArgsCommand): @lockfile(LOCKFILE) def handle_noargs(self, **options): # your command here :lockfile_name: A unique name for a lockfile that belongs to the wrapped method. :lock_wait_timeout: Seconds to wait if lockfile is acquired. If ``-1`` we will not wait and just quit. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): lock = FileLock(lockfile_name) try: lock.acquire(lock_wait_timeout) except AlreadyLocked: return except LockTimeout: return try: result = func(*args, **kwargs) finally: lock.release() return result return wrapper return decorator
[ "def", "lockfile", "(", "lockfile_name", ",", "lock_wait_timeout", "=", "-", "1", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "lock", "=", "FileLock", "(", "lockfile_name", ")", "try", ":", "lock", ".", "acquire", "(", "lock_wait_timeout", ")", "except", "AlreadyLocked", ":", "return", "except", "LockTimeout", ":", "return", "try", ":", "result", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "finally", ":", "lock", ".", "release", "(", ")", "return", "result", "return", "wrapper", "return", "decorator" ]
Only runs the method if the lockfile is not acquired. You should create a setting ``LOCKFILE_PATH`` which points to ``/home/username/tmp/``. In your management command, use it like so:: LOCKFILE = os.path.join( settings.LOCKFILE_FOLDER, 'command_name') class Command(NoArgsCommand): @lockfile(LOCKFILE) def handle_noargs(self, **options): # your command here :lockfile_name: A unique name for a lockfile that belongs to the wrapped method. :lock_wait_timeout: Seconds to wait if lockfile is acquired. If ``-1`` we will not wait and just quit.
[ "Only", "runs", "the", "method", "if", "the", "lockfile", "is", "not", "acquired", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/decorators.py#L11-L51
train
bitlabstudio/django-libs
django_libs/decorators.py
get_username
def get_username(identifier): """Checks if a string is a email adress or not.""" pattern = re.compile('.+@\w+\..+') if pattern.match(identifier): try: user = User.objects.get(email=identifier) except: raise Http404 else: return user.username else: return identifier
python
def get_username(identifier): """Checks if a string is a email adress or not.""" pattern = re.compile('.+@\w+\..+') if pattern.match(identifier): try: user = User.objects.get(email=identifier) except: raise Http404 else: return user.username else: return identifier
[ "def", "get_username", "(", "identifier", ")", ":", "pattern", "=", "re", ".", "compile", "(", "'.+@\\w+\\..+'", ")", "if", "pattern", ".", "match", "(", "identifier", ")", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "email", "=", "identifier", ")", "except", ":", "raise", "Http404", "else", ":", "return", "user", ".", "username", "else", ":", "return", "identifier" ]
Checks if a string is a email adress or not.
[ "Checks", "if", "a", "string", "is", "a", "email", "adress", "or", "not", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/decorators.py#L54-L65
train
amatellanes/fixerio
fixerio/client.py
Fixerio._create_payload
def _create_payload(self, symbols): """ Creates a payload with no none values. :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: a payload. :rtype: dict """ payload = {'access_key': self.access_key} if symbols is not None: payload['symbols'] = ','.join(symbols) return payload
python
def _create_payload(self, symbols): """ Creates a payload with no none values. :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: a payload. :rtype: dict """ payload = {'access_key': self.access_key} if symbols is not None: payload['symbols'] = ','.join(symbols) return payload
[ "def", "_create_payload", "(", "self", ",", "symbols", ")", ":", "payload", "=", "{", "'access_key'", ":", "self", ".", "access_key", "}", "if", "symbols", "is", "not", "None", ":", "payload", "[", "'symbols'", "]", "=", "','", ".", "join", "(", "symbols", ")", "return", "payload" ]
Creates a payload with no none values. :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: a payload. :rtype: dict
[ "Creates", "a", "payload", "with", "no", "none", "values", "." ]
0890e0ee3d39a2a3a2396d934c32bc9ed5f4c974
https://github.com/amatellanes/fixerio/blob/0890e0ee3d39a2a3a2396d934c32bc9ed5f4c974/fixerio/client.py#L32-L44
train
amatellanes/fixerio
fixerio/client.py
Fixerio.historical_rates
def historical_rates(self, date, symbols=None): """ Get historical rates for any day since `date`. :param date: a date :type date: date or str :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: the historical rates for any day since `date`. :rtype: dict :raises FixerioException: if any error making a request. """ try: if isinstance(date, datetime.date): # Convert date to ISO 8601 format. date = date.isoformat() symbols = symbols or self.symbols payload = self._create_payload(symbols) url = BASE_URL + date response = requests.get(url, params=payload) response.raise_for_status() return response.json() except requests.exceptions.RequestException as ex: raise FixerioException(str(ex))
python
def historical_rates(self, date, symbols=None): """ Get historical rates for any day since `date`. :param date: a date :type date: date or str :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: the historical rates for any day since `date`. :rtype: dict :raises FixerioException: if any error making a request. """ try: if isinstance(date, datetime.date): # Convert date to ISO 8601 format. date = date.isoformat() symbols = symbols or self.symbols payload = self._create_payload(symbols) url = BASE_URL + date response = requests.get(url, params=payload) response.raise_for_status() return response.json() except requests.exceptions.RequestException as ex: raise FixerioException(str(ex))
[ "def", "historical_rates", "(", "self", ",", "date", ",", "symbols", "=", "None", ")", ":", "try", ":", "if", "isinstance", "(", "date", ",", "datetime", ".", "date", ")", ":", "date", "=", "date", ".", "isoformat", "(", ")", "symbols", "=", "symbols", "or", "self", ".", "symbols", "payload", "=", "self", ".", "_create_payload", "(", "symbols", ")", "url", "=", "BASE_URL", "+", "date", "response", "=", "requests", ".", "get", "(", "url", ",", "params", "=", "payload", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "ex", ":", "raise", "FixerioException", "(", "str", "(", "ex", ")", ")" ]
Get historical rates for any day since `date`. :param date: a date :type date: date or str :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: the historical rates for any day since `date`. :rtype: dict :raises FixerioException: if any error making a request.
[ "Get", "historical", "rates", "for", "any", "day", "since", "date", "." ]
0890e0ee3d39a2a3a2396d934c32bc9ed5f4c974
https://github.com/amatellanes/fixerio/blob/0890e0ee3d39a2a3a2396d934c32bc9ed5f4c974/fixerio/client.py#L69-L97
train
Genida/django-meerkat
src/meerkat/utils/list.py
distinct
def distinct(l): """ Return a list where the duplicates have been removed. Args: l (list): the list to filter. Returns: list: the same list without duplicates. """ seen = set() seen_add = seen.add return (_ for _ in l if not (_ in seen or seen_add(_)))
python
def distinct(l): """ Return a list where the duplicates have been removed. Args: l (list): the list to filter. Returns: list: the same list without duplicates. """ seen = set() seen_add = seen.add return (_ for _ in l if not (_ in seen or seen_add(_)))
[ "def", "distinct", "(", "l", ")", ":", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "return", "(", "_", "for", "_", "in", "l", "if", "not", "(", "_", "in", "seen", "or", "seen_add", "(", "_", ")", ")", ")" ]
Return a list where the duplicates have been removed. Args: l (list): the list to filter. Returns: list: the same list without duplicates.
[ "Return", "a", "list", "where", "the", "duplicates", "have", "been", "removed", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/list.py#L6-L18
train
bitlabstudio/django-libs
django_libs/format_utils.py
iter_format_modules
def iter_format_modules(lang): """ Does the heavy lifting of finding format modules. """ if check_for_language(lang): format_locations = [] for path in CUSTOM_FORMAT_MODULE_PATHS: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_module('.formats', location % loc) except ImportError: pass
python
def iter_format_modules(lang): """ Does the heavy lifting of finding format modules. """ if check_for_language(lang): format_locations = [] for path in CUSTOM_FORMAT_MODULE_PATHS: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_module('.formats', location % loc) except ImportError: pass
[ "def", "iter_format_modules", "(", "lang", ")", ":", "if", "check_for_language", "(", "lang", ")", ":", "format_locations", "=", "[", "]", "for", "path", "in", "CUSTOM_FORMAT_MODULE_PATHS", ":", "format_locations", ".", "append", "(", "path", "+", "'.%s'", ")", "format_locations", ".", "append", "(", "'django.conf.locale.%s'", ")", "locale", "=", "to_locale", "(", "lang", ")", "locales", "=", "[", "locale", "]", "if", "'_'", "in", "locale", ":", "locales", ".", "append", "(", "locale", ".", "split", "(", "'_'", ")", "[", "0", "]", ")", "for", "location", "in", "format_locations", ":", "for", "loc", "in", "locales", ":", "try", ":", "yield", "import_module", "(", "'.formats'", ",", "location", "%", "loc", ")", "except", "ImportError", ":", "pass" ]
Does the heavy lifting of finding format modules.
[ "Does", "the", "heavy", "lifting", "of", "finding", "format", "modules", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/format_utils.py#L50-L69
train
bitlabstudio/django-libs
django_libs/format_utils.py
get_format_modules
def get_format_modules(lang=None, reverse=False): """ Returns a list of the format modules found """ if lang is None: lang = get_language() modules = _format_modules_cache.setdefault(lang, list( iter_format_modules(lang))) if reverse: return list(reversed(modules)) return modules
python
def get_format_modules(lang=None, reverse=False): """ Returns a list of the format modules found """ if lang is None: lang = get_language() modules = _format_modules_cache.setdefault(lang, list( iter_format_modules(lang))) if reverse: return list(reversed(modules)) return modules
[ "def", "get_format_modules", "(", "lang", "=", "None", ",", "reverse", "=", "False", ")", ":", "if", "lang", "is", "None", ":", "lang", "=", "get_language", "(", ")", "modules", "=", "_format_modules_cache", ".", "setdefault", "(", "lang", ",", "list", "(", "iter_format_modules", "(", "lang", ")", ")", ")", "if", "reverse", ":", "return", "list", "(", "reversed", "(", "modules", ")", ")", "return", "modules" ]
Returns a list of the format modules found
[ "Returns", "a", "list", "of", "the", "format", "modules", "found" ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/format_utils.py#L72-L83
train
bitlabstudio/django-libs
django_libs/views.py
HybridView.as_view
def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % ( cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs self.authed_view = initkwargs.get('authed_view') self.authed_view_kwargs = initkwargs.get('authed_view_kwargs') self.anonymous_view = initkwargs.get('anonymous_view') self.anonymous_view_kwargs = initkwargs.get( 'anonymous_view_kwargs') return self.dispatch(request, *args, **kwargs) # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view
python
def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % ( cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs self.authed_view = initkwargs.get('authed_view') self.authed_view_kwargs = initkwargs.get('authed_view_kwargs') self.anonymous_view = initkwargs.get('anonymous_view') self.anonymous_view_kwargs = initkwargs.get( 'anonymous_view_kwargs') return self.dispatch(request, *args, **kwargs) # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view
[ "def", "as_view", "(", "cls", ",", "**", "initkwargs", ")", ":", "for", "key", "in", "initkwargs", ":", "if", "key", "in", "cls", ".", "http_method_names", ":", "raise", "TypeError", "(", "\"You tried to pass in the %s method name as a \"", "\"keyword argument to %s(). Don't do that.\"", "%", "(", "key", ",", "cls", ".", "__name__", ")", ")", "if", "not", "hasattr", "(", "cls", ",", "key", ")", ":", "raise", "TypeError", "(", "\"%s() received an invalid keyword %r. as_view \"", "\"only accepts arguments that are already \"", "\"attributes of the class.\"", "%", "(", "cls", ".", "__name__", ",", "key", ")", ")", "def", "view", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", "=", "cls", "(", "**", "initkwargs", ")", "if", "hasattr", "(", "self", ",", "'get'", ")", "and", "not", "hasattr", "(", "self", ",", "'head'", ")", ":", "self", ".", "head", "=", "self", ".", "get", "self", ".", "request", "=", "request", "self", ".", "args", "=", "args", "self", ".", "kwargs", "=", "kwargs", "self", ".", "authed_view", "=", "initkwargs", ".", "get", "(", "'authed_view'", ")", "self", ".", "authed_view_kwargs", "=", "initkwargs", ".", "get", "(", "'authed_view_kwargs'", ")", "self", ".", "anonymous_view", "=", "initkwargs", ".", "get", "(", "'anonymous_view'", ")", "self", ".", "anonymous_view_kwargs", "=", "initkwargs", ".", "get", "(", "'anonymous_view_kwargs'", ")", "return", "self", ".", "dispatch", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", "update_wrapper", "(", "view", ",", "cls", ",", "updated", "=", "(", ")", ")", "update_wrapper", "(", "view", ",", "cls", ".", "dispatch", ",", "assigned", "=", "(", ")", ")", "return", "view" ]
Main entry point for a request-response process.
[ "Main", "entry", "point", "for", "a", "request", "-", "response", "process", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/views.py#L54-L88
train
Genida/django-meerkat
src/meerkat/logs/boxes.py
BoxLogsStatusCodesByDate.context
def context(self): """Get the context.""" stats = status_codes_by_date_stats() attacks_data = [{ 'type': 'line', 'zIndex': 9, 'name': _('Attacks'), 'data': [(v[0], v[1]['attacks']) for v in stats] }] codes_data = [{ 'zIndex': 4, 'name': '2xx', 'data': [(v[0], v[1][200]) for v in stats] }, { 'zIndex': 5, 'name': '3xx', 'data': [(v[0], v[1][300]) for v in stats] }, { 'zIndex': 6, 'name': '4xx', 'data': [(v[0], v[1][400]) for v in stats] }, { 'zIndex': 8, 'name': '5xx', 'data': [(v[0], v[1][500]) for v in stats] }] return {'generic_chart': json.dumps(status_codes_by_date_chart()), 'attacks_data': json.dumps(attacks_data), 'codes_data': json.dumps(codes_data)}
python
def context(self): """Get the context.""" stats = status_codes_by_date_stats() attacks_data = [{ 'type': 'line', 'zIndex': 9, 'name': _('Attacks'), 'data': [(v[0], v[1]['attacks']) for v in stats] }] codes_data = [{ 'zIndex': 4, 'name': '2xx', 'data': [(v[0], v[1][200]) for v in stats] }, { 'zIndex': 5, 'name': '3xx', 'data': [(v[0], v[1][300]) for v in stats] }, { 'zIndex': 6, 'name': '4xx', 'data': [(v[0], v[1][400]) for v in stats] }, { 'zIndex': 8, 'name': '5xx', 'data': [(v[0], v[1][500]) for v in stats] }] return {'generic_chart': json.dumps(status_codes_by_date_chart()), 'attacks_data': json.dumps(attacks_data), 'codes_data': json.dumps(codes_data)}
[ "def", "context", "(", "self", ")", ":", "stats", "=", "status_codes_by_date_stats", "(", ")", "attacks_data", "=", "[", "{", "'type'", ":", "'line'", ",", "'zIndex'", ":", "9", ",", "'name'", ":", "_", "(", "'Attacks'", ")", ",", "'data'", ":", "[", "(", "v", "[", "0", "]", ",", "v", "[", "1", "]", "[", "'attacks'", "]", ")", "for", "v", "in", "stats", "]", "}", "]", "codes_data", "=", "[", "{", "'zIndex'", ":", "4", ",", "'name'", ":", "'2xx'", ",", "'data'", ":", "[", "(", "v", "[", "0", "]", ",", "v", "[", "1", "]", "[", "200", "]", ")", "for", "v", "in", "stats", "]", "}", ",", "{", "'zIndex'", ":", "5", ",", "'name'", ":", "'3xx'", ",", "'data'", ":", "[", "(", "v", "[", "0", "]", ",", "v", "[", "1", "]", "[", "300", "]", ")", "for", "v", "in", "stats", "]", "}", ",", "{", "'zIndex'", ":", "6", ",", "'name'", ":", "'4xx'", ",", "'data'", ":", "[", "(", "v", "[", "0", "]", ",", "v", "[", "1", "]", "[", "400", "]", ")", "for", "v", "in", "stats", "]", "}", ",", "{", "'zIndex'", ":", "8", ",", "'name'", ":", "'5xx'", ",", "'data'", ":", "[", "(", "v", "[", "0", "]", ",", "v", "[", "1", "]", "[", "500", "]", ")", "for", "v", "in", "stats", "]", "}", "]", "return", "{", "'generic_chart'", ":", "json", ".", "dumps", "(", "status_codes_by_date_chart", "(", ")", ")", ",", "'attacks_data'", ":", "json", ".", "dumps", "(", "attacks_data", ")", ",", "'codes_data'", ":", "json", ".", "dumps", "(", "codes_data", ")", "}" ]
Get the context.
[ "Get", "the", "context", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/boxes.py#L68-L100
train
Genida/django-meerkat
src/meerkat/logs/boxes.py
BoxLogsMostVisitedPages.widgets
def widgets(self): """Get the items.""" widgets = [] for i, chart in enumerate(most_visited_pages_charts()): widgets.append(Widget(html_id='most_visited_chart_%d' % i, content=json.dumps(chart), template='meerkat/widgets/highcharts.html', js_code=['plotOptions.tooltip.pointFormatter'])) return widgets
python
def widgets(self): """Get the items.""" widgets = [] for i, chart in enumerate(most_visited_pages_charts()): widgets.append(Widget(html_id='most_visited_chart_%d' % i, content=json.dumps(chart), template='meerkat/widgets/highcharts.html', js_code=['plotOptions.tooltip.pointFormatter'])) return widgets
[ "def", "widgets", "(", "self", ")", ":", "widgets", "=", "[", "]", "for", "i", ",", "chart", "in", "enumerate", "(", "most_visited_pages_charts", "(", ")", ")", ":", "widgets", ".", "append", "(", "Widget", "(", "html_id", "=", "'most_visited_chart_%d'", "%", "i", ",", "content", "=", "json", ".", "dumps", "(", "chart", ")", ",", "template", "=", "'meerkat/widgets/highcharts.html'", ",", "js_code", "=", "[", "'plotOptions.tooltip.pointFormatter'", "]", ")", ")", "return", "widgets" ]
Get the items.
[ "Get", "the", "items", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/boxes.py#L118-L127
train
oleiade/durations
durations/scales.py
Scale.get
def get(self, str_representation): """Retrieves a scale representation from it's string representation :param str_representation: scale string representation to be retrieved :type str_representation: string :raises: ScaleFormatError :returns: scale representation :rtype: ScaleRepresentation """ for scale in self.SCALES: if str_representation in scale: return scale raise ScaleFormatError("Unsupported scale format: {0}".format(str_representation))
python
def get(self, str_representation): """Retrieves a scale representation from it's string representation :param str_representation: scale string representation to be retrieved :type str_representation: string :raises: ScaleFormatError :returns: scale representation :rtype: ScaleRepresentation """ for scale in self.SCALES: if str_representation in scale: return scale raise ScaleFormatError("Unsupported scale format: {0}".format(str_representation))
[ "def", "get", "(", "self", ",", "str_representation", ")", ":", "for", "scale", "in", "self", ".", "SCALES", ":", "if", "str_representation", "in", "scale", ":", "return", "scale", "raise", "ScaleFormatError", "(", "\"Unsupported scale format: {0}\"", ".", "format", "(", "str_representation", ")", ")" ]
Retrieves a scale representation from it's string representation :param str_representation: scale string representation to be retrieved :type str_representation: string :raises: ScaleFormatError :returns: scale representation :rtype: ScaleRepresentation
[ "Retrieves", "a", "scale", "representation", "from", "it", "s", "string", "representation" ]
62c176dfa7d36d5c59bf93bdebfdc80ab53757bd
https://github.com/oleiade/durations/blob/62c176dfa7d36d5c59bf93bdebfdc80ab53757bd/durations/scales.py#L52-L65
train
oleiade/durations
durations/parser.py
valid_token
def valid_token(token): """Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string """ is_scale = False # Check if the token represents a scale # If it doesn't set a flag accordingly try: Scale(token) is_scale = True except ScaleFormatError: pass # If token either represents a numerical value, a # separator token, or a scale, it is considered valid if any([token.isdigit(), token in SEPARATOR_TOKENS, is_scale]): return True return False
python
def valid_token(token): """Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string """ is_scale = False # Check if the token represents a scale # If it doesn't set a flag accordingly try: Scale(token) is_scale = True except ScaleFormatError: pass # If token either represents a numerical value, a # separator token, or a scale, it is considered valid if any([token.isdigit(), token in SEPARATOR_TOKENS, is_scale]): return True return False
[ "def", "valid_token", "(", "token", ")", ":", "is_scale", "=", "False", "try", ":", "Scale", "(", "token", ")", "is_scale", "=", "True", "except", "ScaleFormatError", ":", "pass", "if", "any", "(", "[", "token", ".", "isdigit", "(", ")", ",", "token", "in", "SEPARATOR_TOKENS", ",", "is_scale", "]", ")", ":", "return", "True", "return", "False" ]
Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string
[ "Asserts", "a", "provided", "string", "is", "a", "valid", "duration", "token", "representation" ]
62c176dfa7d36d5c59bf93bdebfdc80ab53757bd
https://github.com/oleiade/durations/blob/62c176dfa7d36d5c59bf93bdebfdc80ab53757bd/durations/parser.py#L10-L31
train
oleiade/durations
durations/parser.py
extract_tokens
def extract_tokens(representation, separators=SEPARATOR_CHARACTERS): """Extracts durations tokens from a duration representation. Parses the string representation incrementaly and raises on first error met. :param representation: duration representation :type representation: string """ buff = "" elements = [] last_index = 0 last_token = None for index, c in enumerate(representation): # if separator character is found, push # the content of the buffer in the elements list if c in separators: if buff: # If the last found token is invalid, # raise and InvalidTokenError if not valid_token(buff): raise InvalidTokenError( "Duration representation {0} contains " "an invalid token: {1}".format(representation, buff) ) # If buffer content is a separator word, for example # "and", just ignore it if not buff.strip() in SEPARATOR_TOKENS: elements.append(buff) # Anyway, reset buffer and last token marker # to their zero value buff = "" last_token = None else: token = compute_char_token(c) if (token is not None and last_token is not None and token != last_token): elements.append(buff) buff = c else: buff += c last_token = token # push the content left in representation # in the elements list elements.append(buff) return list(zip(elements[::2], elements[1::2]))
python
def extract_tokens(representation, separators=SEPARATOR_CHARACTERS): """Extracts durations tokens from a duration representation. Parses the string representation incrementaly and raises on first error met. :param representation: duration representation :type representation: string """ buff = "" elements = [] last_index = 0 last_token = None for index, c in enumerate(representation): # if separator character is found, push # the content of the buffer in the elements list if c in separators: if buff: # If the last found token is invalid, # raise and InvalidTokenError if not valid_token(buff): raise InvalidTokenError( "Duration representation {0} contains " "an invalid token: {1}".format(representation, buff) ) # If buffer content is a separator word, for example # "and", just ignore it if not buff.strip() in SEPARATOR_TOKENS: elements.append(buff) # Anyway, reset buffer and last token marker # to their zero value buff = "" last_token = None else: token = compute_char_token(c) if (token is not None and last_token is not None and token != last_token): elements.append(buff) buff = c else: buff += c last_token = token # push the content left in representation # in the elements list elements.append(buff) return list(zip(elements[::2], elements[1::2]))
[ "def", "extract_tokens", "(", "representation", ",", "separators", "=", "SEPARATOR_CHARACTERS", ")", ":", "buff", "=", "\"\"", "elements", "=", "[", "]", "last_index", "=", "0", "last_token", "=", "None", "for", "index", ",", "c", "in", "enumerate", "(", "representation", ")", ":", "if", "c", "in", "separators", ":", "if", "buff", ":", "if", "not", "valid_token", "(", "buff", ")", ":", "raise", "InvalidTokenError", "(", "\"Duration representation {0} contains \"", "\"an invalid token: {1}\"", ".", "format", "(", "representation", ",", "buff", ")", ")", "if", "not", "buff", ".", "strip", "(", ")", "in", "SEPARATOR_TOKENS", ":", "elements", ".", "append", "(", "buff", ")", "buff", "=", "\"\"", "last_token", "=", "None", "else", ":", "token", "=", "compute_char_token", "(", "c", ")", "if", "(", "token", "is", "not", "None", "and", "last_token", "is", "not", "None", "and", "token", "!=", "last_token", ")", ":", "elements", ".", "append", "(", "buff", ")", "buff", "=", "c", "else", ":", "buff", "+=", "c", "last_token", "=", "token", "elements", ".", "append", "(", "buff", ")", "return", "list", "(", "zip", "(", "elements", "[", ":", ":", "2", "]", ",", "elements", "[", "1", ":", ":", "2", "]", ")", ")" ]
Extracts durations tokens from a duration representation. Parses the string representation incrementaly and raises on first error met. :param representation: duration representation :type representation: string
[ "Extracts", "durations", "tokens", "from", "a", "duration", "representation", "." ]
62c176dfa7d36d5c59bf93bdebfdc80ab53757bd
https://github.com/oleiade/durations/blob/62c176dfa7d36d5c59bf93bdebfdc80ab53757bd/durations/parser.py#L43-L93
train
bitlabstudio/django-libs
django_libs/utils/text.py
create_random_string
def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789', repetitions=False): """ Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided. """ if repetitions: return ''.join(random.choice(chars) for _ in range(length)) return ''.join(random.sample(chars, length))
python
def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789', repetitions=False): """ Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided. """ if repetitions: return ''.join(random.choice(chars) for _ in range(length)) return ''.join(random.sample(chars, length))
[ "def", "create_random_string", "(", "length", "=", "7", ",", "chars", "=", "'ABCDEFGHJKMNPQRSTUVWXYZ23456789'", ",", "repetitions", "=", "False", ")", ":", "if", "repetitions", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "_", "in", "range", "(", "length", ")", ")", "return", "''", ".", "join", "(", "random", ".", "sample", "(", "chars", ",", "length", ")", ")" ]
Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided.
[ "Returns", "a", "random", "string", "based", "on", "the", "provided", "arguments", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/text.py#L5-L16
train
bitlabstudio/django-libs
django_libs/loaders.py
load_member
def load_member(fqn): """Loads and returns a class for a given fully qualified name.""" modulename, member_name = split_fqn(fqn) module = __import__(modulename, globals(), locals(), member_name) return getattr(module, member_name)
python
def load_member(fqn): """Loads and returns a class for a given fully qualified name.""" modulename, member_name = split_fqn(fqn) module = __import__(modulename, globals(), locals(), member_name) return getattr(module, member_name)
[ "def", "load_member", "(", "fqn", ")", ":", "modulename", ",", "member_name", "=", "split_fqn", "(", "fqn", ")", "module", "=", "__import__", "(", "modulename", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "member_name", ")", "return", "getattr", "(", "module", ",", "member_name", ")" ]
Loads and returns a class for a given fully qualified name.
[ "Loads", "and", "returns", "a", "class", "for", "a", "given", "fully", "qualified", "name", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/loaders.py#L5-L9
train
bitlabstudio/django-libs
django_libs/loaders.py
split_fqn
def split_fqn(fqn): """ Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string. """ if hasattr(fqn, '__call__'): fqn_string = fqn() else: fqn_string = fqn return fqn_string.rsplit('.', 1)
python
def split_fqn(fqn): """ Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string. """ if hasattr(fqn, '__call__'): fqn_string = fqn() else: fqn_string = fqn return fqn_string.rsplit('.', 1)
[ "def", "split_fqn", "(", "fqn", ")", ":", "if", "hasattr", "(", "fqn", ",", "'__call__'", ")", ":", "fqn_string", "=", "fqn", "(", ")", "else", ":", "fqn_string", "=", "fqn", "return", "fqn_string", ".", "rsplit", "(", "'.'", ",", "1", ")" ]
Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string.
[ "Returns", "the", "left", "and", "right", "part", "of", "the", "import", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/loaders.py#L18-L30
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection.send
def send(self, data): """ Sends data to the server. """ self.logger.debug('Send data: {}'.format(data)) if not self.connected: self.logger.warning('Connection not established. Return...') return self.websocket.send(json.dumps(data))
python
def send(self, data): """ Sends data to the server. """ self.logger.debug('Send data: {}'.format(data)) if not self.connected: self.logger.warning('Connection not established. Return...') return self.websocket.send(json.dumps(data))
[ "def", "send", "(", "self", ",", "data", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Send data: {}'", ".", "format", "(", "data", ")", ")", "if", "not", "self", ".", "connected", ":", "self", ".", "logger", ".", "warning", "(", "'Connection not established. Return...'", ")", "return", "self", ".", "websocket", ".", "send", "(", "json", ".", "dumps", "(", "data", ")", ")" ]
Sends data to the server.
[ "Sends", "data", "to", "the", "server", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L97-L107
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection._on_message
def _on_message(self, socket, message): """ Called aways when a message arrives. """ data = json.loads(message) message_type = None identifier = None subscription = None if 'type' in data: message_type = data['type'] if 'identifier' in data: identifier = json.loads(data['identifier']) if identifier is not None: subscription = self.find_subscription(identifier) if subscription is not None: subscription.received(data) elif message_type == 'welcome': self.logger.debug('Welcome message received.') for subscription in self.subscriptions.values(): if subscription.state == 'connection_pending': subscription.create() elif message_type == 'ping': if self.log_ping: self.logger.debug('Ping received.') else: self.logger.warning('Message not supported. (Message: {})'.format(message))
python
def _on_message(self, socket, message): """ Called aways when a message arrives. """ data = json.loads(message) message_type = None identifier = None subscription = None if 'type' in data: message_type = data['type'] if 'identifier' in data: identifier = json.loads(data['identifier']) if identifier is not None: subscription = self.find_subscription(identifier) if subscription is not None: subscription.received(data) elif message_type == 'welcome': self.logger.debug('Welcome message received.') for subscription in self.subscriptions.values(): if subscription.state == 'connection_pending': subscription.create() elif message_type == 'ping': if self.log_ping: self.logger.debug('Ping received.') else: self.logger.warning('Message not supported. (Message: {})'.format(message))
[ "def", "_on_message", "(", "self", ",", "socket", ",", "message", ")", ":", "data", "=", "json", ".", "loads", "(", "message", ")", "message_type", "=", "None", "identifier", "=", "None", "subscription", "=", "None", "if", "'type'", "in", "data", ":", "message_type", "=", "data", "[", "'type'", "]", "if", "'identifier'", "in", "data", ":", "identifier", "=", "json", ".", "loads", "(", "data", "[", "'identifier'", "]", ")", "if", "identifier", "is", "not", "None", ":", "subscription", "=", "self", ".", "find_subscription", "(", "identifier", ")", "if", "subscription", "is", "not", "None", ":", "subscription", ".", "received", "(", "data", ")", "elif", "message_type", "==", "'welcome'", ":", "self", ".", "logger", ".", "debug", "(", "'Welcome message received.'", ")", "for", "subscription", "in", "self", ".", "subscriptions", ".", "values", "(", ")", ":", "if", "subscription", ".", "state", "==", "'connection_pending'", ":", "subscription", ".", "create", "(", ")", "elif", "message_type", "==", "'ping'", ":", "if", "self", ".", "log_ping", ":", "self", ".", "logger", ".", "debug", "(", "'Ping received.'", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "'Message not supported. (Message: {})'", ".", "format", "(", "message", ")", ")" ]
Called aways when a message arrives.
[ "Called", "aways", "when", "a", "message", "arrives", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L116-L147
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection._on_close
def _on_close(self, socket): """ Called when the connection was closed. """ self.logger.debug('Connection closed.') for subscription in self.subscriptions.values(): if subscription.state == 'subscribed': subscription.state = 'connection_pending'
python
def _on_close(self, socket): """ Called when the connection was closed. """ self.logger.debug('Connection closed.') for subscription in self.subscriptions.values(): if subscription.state == 'subscribed': subscription.state = 'connection_pending'
[ "def", "_on_close", "(", "self", ",", "socket", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Connection closed.'", ")", "for", "subscription", "in", "self", ".", "subscriptions", ".", "values", "(", ")", ":", "if", "subscription", ".", "state", "==", "'subscribed'", ":", "subscription", ".", "state", "=", "'connection_pending'" ]
Called when the connection was closed.
[ "Called", "when", "the", "connection", "was", "closed", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L149-L157
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection.connected
def connected(self): """ If connected to server. """ return self.websocket is not None and \ self.websocket.sock is not None and \ self.websocket.sock.connected
python
def connected(self): """ If connected to server. """ return self.websocket is not None and \ self.websocket.sock is not None and \ self.websocket.sock.connected
[ "def", "connected", "(", "self", ")", ":", "return", "self", ".", "websocket", "is", "not", "None", "and", "self", ".", "websocket", ".", "sock", "is", "not", "None", "and", "self", ".", "websocket", ".", "sock", ".", "connected" ]
If connected to server.
[ "If", "connected", "to", "server", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L167-L173
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/connection.py
Connection.find_subscription
def find_subscription(self, identifier): """ Finds a subscription by it's identifier. """ for subscription in self.subscriptions.values(): if subscription.identifier == identifier: return subscription
python
def find_subscription(self, identifier): """ Finds a subscription by it's identifier. """ for subscription in self.subscriptions.values(): if subscription.identifier == identifier: return subscription
[ "def", "find_subscription", "(", "self", ",", "identifier", ")", ":", "for", "subscription", "in", "self", ".", "subscriptions", ".", "values", "(", ")", ":", "if", "subscription", ".", "identifier", "==", "identifier", ":", "return", "subscription" ]
Finds a subscription by it's identifier.
[ "Finds", "a", "subscription", "by", "it", "s", "identifier", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/connection.py#L175-L182
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription.create
def create(self): """ Subscribes at the server. """ self.logger.debug('Create subscription on server...') if not self.connection.connected: self.state = 'connection_pending' return data = { 'command': 'subscribe', 'identifier': self._identifier_string() } self.connection.send(data) self.state = 'pending'
python
def create(self): """ Subscribes at the server. """ self.logger.debug('Create subscription on server...') if not self.connection.connected: self.state = 'connection_pending' return data = { 'command': 'subscribe', 'identifier': self._identifier_string() } self.connection.send(data) self.state = 'pending'
[ "def", "create", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Create subscription on server...'", ")", "if", "not", "self", ".", "connection", ".", "connected", ":", "self", ".", "state", "=", "'connection_pending'", "return", "data", "=", "{", "'command'", ":", "'subscribe'", ",", "'identifier'", ":", "self", ".", "_identifier_string", "(", ")", "}", "self", ".", "connection", ".", "send", "(", "data", ")", "self", ".", "state", "=", "'pending'" ]
Subscribes at the server.
[ "Subscribes", "at", "the", "server", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L33-L49
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription.remove
def remove(self): """ Removes the subscription. """ self.logger.debug('Remove subscription from server...') data = { 'command': 'unsubscribe', 'identifier': self._identifier_string() } self.connection.send(data) self.state = 'unsubscribed'
python
def remove(self): """ Removes the subscription. """ self.logger.debug('Remove subscription from server...') data = { 'command': 'unsubscribe', 'identifier': self._identifier_string() } self.connection.send(data) self.state = 'unsubscribed'
[ "def", "remove", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Remove subscription from server...'", ")", "data", "=", "{", "'command'", ":", "'unsubscribe'", ",", "'identifier'", ":", "self", ".", "_identifier_string", "(", ")", "}", "self", ".", "connection", ".", "send", "(", "data", ")", "self", ".", "state", "=", "'unsubscribed'" ]
Removes the subscription.
[ "Removes", "the", "subscription", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L51-L63
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription.send
def send(self, message): """ Sends data to the server on the subscription channel. :param data: The JSON data to send. """ self.logger.debug('Send message: {}'.format(message)) if self.state == 'pending' or self.state == 'connection_pending': self.logger.info('Connection not established. Add message to queue.') self.message_queue.append(message) return elif self.state == 'unsubscribed' or self.state == 'rejected': self.logger.warning('Not subscribed! Message discarded.') return data = { 'command': 'message', 'identifier': self._identifier_string(), 'data': message.raw_message() } self.connection.send(data)
python
def send(self, message): """ Sends data to the server on the subscription channel. :param data: The JSON data to send. """ self.logger.debug('Send message: {}'.format(message)) if self.state == 'pending' or self.state == 'connection_pending': self.logger.info('Connection not established. Add message to queue.') self.message_queue.append(message) return elif self.state == 'unsubscribed' or self.state == 'rejected': self.logger.warning('Not subscribed! Message discarded.') return data = { 'command': 'message', 'identifier': self._identifier_string(), 'data': message.raw_message() } self.connection.send(data)
[ "def", "send", "(", "self", ",", "message", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Send message: {}'", ".", "format", "(", "message", ")", ")", "if", "self", ".", "state", "==", "'pending'", "or", "self", ".", "state", "==", "'connection_pending'", ":", "self", ".", "logger", ".", "info", "(", "'Connection not established. Add message to queue.'", ")", "self", ".", "message_queue", ".", "append", "(", "message", ")", "return", "elif", "self", ".", "state", "==", "'unsubscribed'", "or", "self", ".", "state", "==", "'rejected'", ":", "self", ".", "logger", ".", "warning", "(", "'Not subscribed! Message discarded.'", ")", "return", "data", "=", "{", "'command'", ":", "'message'", ",", "'identifier'", ":", "self", ".", "_identifier_string", "(", ")", ",", "'data'", ":", "message", ".", "raw_message", "(", ")", "}", "self", ".", "connection", ".", "send", "(", "data", ")" ]
Sends data to the server on the subscription channel. :param data: The JSON data to send.
[ "Sends", "data", "to", "the", "server", "on", "the", "subscription", "channel", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L65-L88
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription.received
def received(self, data): """ API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message """ self.logger.debug('Data received: {}'.format(data)) message_type = None if 'type' in data: message_type = data['type'] if message_type == 'confirm_subscription': self._subscribed() elif message_type == 'reject_subscription': self._rejected() elif self.receive_callback is not None and 'message' in data: self.receive_callback(data['message']) else: self.logger.warning('Message type unknown. ({})'.format(message_type))
python
def received(self, data): """ API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message """ self.logger.debug('Data received: {}'.format(data)) message_type = None if 'type' in data: message_type = data['type'] if message_type == 'confirm_subscription': self._subscribed() elif message_type == 'reject_subscription': self._rejected() elif self.receive_callback is not None and 'message' in data: self.receive_callback(data['message']) else: self.logger.warning('Message type unknown. ({})'.format(message_type))
[ "def", "received", "(", "self", ",", "data", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Data received: {}'", ".", "format", "(", "data", ")", ")", "message_type", "=", "None", "if", "'type'", "in", "data", ":", "message_type", "=", "data", "[", "'type'", "]", "if", "message_type", "==", "'confirm_subscription'", ":", "self", ".", "_subscribed", "(", ")", "elif", "message_type", "==", "'reject_subscription'", ":", "self", ".", "_rejected", "(", ")", "elif", "self", ".", "receive_callback", "is", "not", "None", "and", "'message'", "in", "data", ":", "self", ".", "receive_callback", "(", "data", "[", "'message'", "]", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "'Message type unknown. ({})'", ".", "format", "(", "message_type", ")", ")" ]
API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message
[ "API", "for", "the", "connection", "to", "forward", "information", "to", "this", "subscription", "instance", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L101-L123
train
tobiasfeistmantl/python-actioncable-zwei
actioncable/subscription.py
Subscription._subscribed
def _subscribed(self): """ Called when the subscription was accepted successfully. """ self.logger.debug('Subscription confirmed.') self.state = 'subscribed' for message in self.message_queue: self.send(message)
python
def _subscribed(self): """ Called when the subscription was accepted successfully. """ self.logger.debug('Subscription confirmed.') self.state = 'subscribed' for message in self.message_queue: self.send(message)
[ "def", "_subscribed", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Subscription confirmed.'", ")", "self", ".", "state", "=", "'subscribed'", "for", "message", "in", "self", ".", "message_queue", ":", "self", ".", "send", "(", "message", ")" ]
Called when the subscription was accepted successfully.
[ "Called", "when", "the", "subscription", "was", "accepted", "successfully", "." ]
04876b4425a295485af8976acceb0b46d2ef1c8d
https://github.com/tobiasfeistmantl/python-actioncable-zwei/blob/04876b4425a295485af8976acceb0b46d2ef1c8d/actioncable/subscription.py#L125-L133
train
flavio/scsgate
scsgate/monitor/__init__.py
cli_opts
def cli_opts(): """ Handle the command line options """ parser = argparse.ArgumentParser() parser.add_argument( "--homeassistant-config", type=str, required=False, dest="config", help="Create configuration section for home assistant",) parser.add_argument( "-f", "--filter", type=str, required=False, dest="filter", help="Ignore events related with these devices",) parser.add_argument( "-o", "--output", type=str, required=False, dest="output", help="Send output to file",) parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", help="Verbose output",) parser.add_argument('device') return parser.parse_args()
python
def cli_opts(): """ Handle the command line options """ parser = argparse.ArgumentParser() parser.add_argument( "--homeassistant-config", type=str, required=False, dest="config", help="Create configuration section for home assistant",) parser.add_argument( "-f", "--filter", type=str, required=False, dest="filter", help="Ignore events related with these devices",) parser.add_argument( "-o", "--output", type=str, required=False, dest="output", help="Send output to file",) parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", help="Verbose output",) parser.add_argument('device') return parser.parse_args()
[ "def", "cli_opts", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--homeassistant-config\"", ",", "type", "=", "str", ",", "required", "=", "False", ",", "dest", "=", "\"config\"", ",", "help", "=", "\"Create configuration section for home assistant\"", ",", ")", "parser", ".", "add_argument", "(", "\"-f\"", ",", "\"--filter\"", ",", "type", "=", "str", ",", "required", "=", "False", ",", "dest", "=", "\"filter\"", ",", "help", "=", "\"Ignore events related with these devices\"", ",", ")", "parser", ".", "add_argument", "(", "\"-o\"", ",", "\"--output\"", ",", "type", "=", "str", ",", "required", "=", "False", ",", "dest", "=", "\"output\"", ",", "help", "=", "\"Send output to file\"", ",", ")", "parser", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"verbose\"", ",", "help", "=", "\"Verbose output\"", ",", ")", "parser", ".", "add_argument", "(", "'device'", ")", "return", "parser", ".", "parse_args", "(", ")" ]
Handle the command line options
[ "Handle", "the", "command", "line", "options" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L13-L44
train
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._setup_signal_handler
def _setup_signal_handler(self): """ Register signal handlers """ signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGQUIT, self._signal_handler)
python
def _setup_signal_handler(self): """ Register signal handlers """ signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGQUIT, self._signal_handler)
[ "def", "_setup_signal_handler", "(", "self", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "self", ".", "_signal_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "self", ".", "_signal_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGQUIT", ",", "self", ".", "_signal_handler", ")" ]
Register signal handlers
[ "Register", "signal", "handlers" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L83-L87
train
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._signal_handler
def _signal_handler(self, signum, frame): """ Method called when handling signals """ if self._options.config: with open(self._options.config, "w") as cfg: yaml.dump(self._home_assistant_config(), cfg) print( "Dumped home assistant configuration at", self._options.config) self._connection.close() sys.exit(0)
python
def _signal_handler(self, signum, frame): """ Method called when handling signals """ if self._options.config: with open(self._options.config, "w") as cfg: yaml.dump(self._home_assistant_config(), cfg) print( "Dumped home assistant configuration at", self._options.config) self._connection.close() sys.exit(0)
[ "def", "_signal_handler", "(", "self", ",", "signum", ",", "frame", ")", ":", "if", "self", ".", "_options", ".", "config", ":", "with", "open", "(", "self", ".", "_options", ".", "config", ",", "\"w\"", ")", "as", "cfg", ":", "yaml", ".", "dump", "(", "self", ".", "_home_assistant_config", "(", ")", ",", "cfg", ")", "print", "(", "\"Dumped home assistant configuration at\"", ",", "self", ".", "_options", ".", "config", ")", "self", ".", "_connection", ".", "close", "(", ")", "sys", ".", "exit", "(", "0", ")" ]
Method called when handling signals
[ "Method", "called", "when", "handling", "signals" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L89-L98
train
flavio/scsgate
scsgate/monitor/__init__.py
Monitor.start
def start(self): """ Monitor the bus for events and handle them """ print("Entering monitoring mode, press CTRL-C to quit") serial = self._connection.serial while True: serial.write(b"@R") length = int(serial.read(), 16) data = serial.read(length * 2) message = messages.parse(data) if not (self._options.filter and message.entity and message.entity in self._devices): logging.debug(" ".join(message.bytes)) if not self._options.config or \ message.entity is None or \ message.entity in self._devices: continue print("New device found") ha_id = input("Enter home assistant unique ID: ") name = input("Enter name: ") self._add_device(scs_id=message.entity, ha_id=ha_id, name=name)
python
def start(self): """ Monitor the bus for events and handle them """ print("Entering monitoring mode, press CTRL-C to quit") serial = self._connection.serial while True: serial.write(b"@R") length = int(serial.read(), 16) data = serial.read(length * 2) message = messages.parse(data) if not (self._options.filter and message.entity and message.entity in self._devices): logging.debug(" ".join(message.bytes)) if not self._options.config or \ message.entity is None or \ message.entity in self._devices: continue print("New device found") ha_id = input("Enter home assistant unique ID: ") name = input("Enter name: ") self._add_device(scs_id=message.entity, ha_id=ha_id, name=name)
[ "def", "start", "(", "self", ")", ":", "print", "(", "\"Entering monitoring mode, press CTRL-C to quit\"", ")", "serial", "=", "self", ".", "_connection", ".", "serial", "while", "True", ":", "serial", ".", "write", "(", "b\"@R\"", ")", "length", "=", "int", "(", "serial", ".", "read", "(", ")", ",", "16", ")", "data", "=", "serial", ".", "read", "(", "length", "*", "2", ")", "message", "=", "messages", ".", "parse", "(", "data", ")", "if", "not", "(", "self", ".", "_options", ".", "filter", "and", "message", ".", "entity", "and", "message", ".", "entity", "in", "self", ".", "_devices", ")", ":", "logging", ".", "debug", "(", "\" \"", ".", "join", "(", "message", ".", "bytes", ")", ")", "if", "not", "self", ".", "_options", ".", "config", "or", "message", ".", "entity", "is", "None", "or", "message", ".", "entity", "in", "self", ".", "_devices", ":", "continue", "print", "(", "\"New device found\"", ")", "ha_id", "=", "input", "(", "\"Enter home assistant unique ID: \"", ")", "name", "=", "input", "(", "\"Enter name: \"", ")", "self", ".", "_add_device", "(", "scs_id", "=", "message", ".", "entity", ",", "ha_id", "=", "ha_id", ",", "name", "=", "name", ")" ]
Monitor the bus for events and handle them
[ "Monitor", "the", "bus", "for", "events", "and", "handle", "them" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L100-L122
train
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._add_device
def _add_device(self, scs_id, ha_id, name): """ Add device to the list of known ones """ if scs_id in self._devices: return self._devices[scs_id] = { 'name': name, 'ha_id': ha_id }
python
def _add_device(self, scs_id, ha_id, name): """ Add device to the list of known ones """ if scs_id in self._devices: return self._devices[scs_id] = { 'name': name, 'ha_id': ha_id }
[ "def", "_add_device", "(", "self", ",", "scs_id", ",", "ha_id", ",", "name", ")", ":", "if", "scs_id", "in", "self", ".", "_devices", ":", "return", "self", ".", "_devices", "[", "scs_id", "]", "=", "{", "'name'", ":", "name", ",", "'ha_id'", ":", "ha_id", "}" ]
Add device to the list of known ones
[ "Add", "device", "to", "the", "list", "of", "known", "ones" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L124-L132
train
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._home_assistant_config
def _home_assistant_config(self): """ Creates home assistant configuration for the known devices """ devices = {} for scs_id, dev in self._devices.items(): devices[dev['ha_id']] = { 'name': dev['name'], 'scs_id': scs_id} return {'devices': devices}
python
def _home_assistant_config(self): """ Creates home assistant configuration for the known devices """ devices = {} for scs_id, dev in self._devices.items(): devices[dev['ha_id']] = { 'name': dev['name'], 'scs_id': scs_id} return {'devices': devices}
[ "def", "_home_assistant_config", "(", "self", ")", ":", "devices", "=", "{", "}", "for", "scs_id", ",", "dev", "in", "self", ".", "_devices", ".", "items", "(", ")", ":", "devices", "[", "dev", "[", "'ha_id'", "]", "]", "=", "{", "'name'", ":", "dev", "[", "'name'", "]", ",", "'scs_id'", ":", "scs_id", "}", "return", "{", "'devices'", ":", "devices", "}" ]
Creates home assistant configuration for the known devices
[ "Creates", "home", "assistant", "configuration", "for", "the", "known", "devices" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L134-L142
train
flavio/scsgate
scsgate/monitor/__init__.py
Monitor._load_filter
def _load_filter(self, config): """ Load the filter file and populates self._devices accordingly """ path = pathlib.Path(config) if not path.is_file(): return with open(config, 'r') as conf: devices = yaml.load(conf)['devices'] for ha_id, dev in devices.items(): self._devices[dev['scs_id']] = { ha_id: dev, 'name': dev['name']}
python
def _load_filter(self, config): """ Load the filter file and populates self._devices accordingly """ path = pathlib.Path(config) if not path.is_file(): return with open(config, 'r') as conf: devices = yaml.load(conf)['devices'] for ha_id, dev in devices.items(): self._devices[dev['scs_id']] = { ha_id: dev, 'name': dev['name']}
[ "def", "_load_filter", "(", "self", ",", "config", ")", ":", "path", "=", "pathlib", ".", "Path", "(", "config", ")", "if", "not", "path", ".", "is_file", "(", ")", ":", "return", "with", "open", "(", "config", ",", "'r'", ")", "as", "conf", ":", "devices", "=", "yaml", ".", "load", "(", "conf", ")", "[", "'devices'", "]", "for", "ha_id", ",", "dev", "in", "devices", ".", "items", "(", ")", ":", "self", ".", "_devices", "[", "dev", "[", "'scs_id'", "]", "]", "=", "{", "ha_id", ":", "dev", ",", "'name'", ":", "dev", "[", "'name'", "]", "}" ]
Load the filter file and populates self._devices accordingly
[ "Load", "the", "filter", "file", "and", "populates", "self", ".", "_devices", "accordingly" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L144-L155
train
flavio/scsgate
scsgate/connection.py
Connection.close
def close(self): """ Closes the connection to the serial port and ensure no pending operatoin are left """ self._serial.write(b"@c") self._serial.read() self._serial.close()
python
def close(self): """ Closes the connection to the serial port and ensure no pending operatoin are left """ self._serial.write(b"@c") self._serial.read() self._serial.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "_serial", ".", "write", "(", "b\"@c\"", ")", "self", ".", "_serial", ".", "read", "(", ")", "self", ".", "_serial", ".", "close", "(", ")" ]
Closes the connection to the serial port and ensure no pending operatoin are left
[ "Closes", "the", "connection", "to", "the", "serial", "port", "and", "ensure", "no", "pending", "operatoin", "are", "left" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/connection.py#L48-L53
train
kensho-technologies/grift
grift/config.py
ConfigProperty.load
def load(self, value): """Load a value, converting it to the proper type if validation_type exists.""" if self.property_type is None: return value elif not isinstance(self.property_type, BaseType): raise TypeError('property_type must be schematics BaseType') else: native_value = self.property_type.to_native(value) self.property_type.validate(native_value) return native_value
python
def load(self, value): """Load a value, converting it to the proper type if validation_type exists.""" if self.property_type is None: return value elif not isinstance(self.property_type, BaseType): raise TypeError('property_type must be schematics BaseType') else: native_value = self.property_type.to_native(value) self.property_type.validate(native_value) return native_value
[ "def", "load", "(", "self", ",", "value", ")", ":", "if", "self", ".", "property_type", "is", "None", ":", "return", "value", "elif", "not", "isinstance", "(", "self", ".", "property_type", ",", "BaseType", ")", ":", "raise", "TypeError", "(", "'property_type must be schematics BaseType'", ")", "else", ":", "native_value", "=", "self", ".", "property_type", ".", "to_native", "(", "value", ")", "self", ".", "property_type", ".", "validate", "(", "native_value", ")", "return", "native_value" ]
Load a value, converting it to the proper type if validation_type exists.
[ "Load", "a", "value", "converting", "it", "to", "the", "proper", "type", "if", "validation_type", "exists", "." ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L35-L44
train
kensho-technologies/grift
grift/config.py
BaseConfig._update_property_keys
def _update_property_keys(cls): """Set unspecified property_keys for each ConfigProperty to the name of the class attr""" for attr_name, config_prop in cls._iter_config_props(): if config_prop.property_key is None: config_prop.property_key = attr_name
python
def _update_property_keys(cls): """Set unspecified property_keys for each ConfigProperty to the name of the class attr""" for attr_name, config_prop in cls._iter_config_props(): if config_prop.property_key is None: config_prop.property_key = attr_name
[ "def", "_update_property_keys", "(", "cls", ")", ":", "for", "attr_name", ",", "config_prop", "in", "cls", ".", "_iter_config_props", "(", ")", ":", "if", "config_prop", ".", "property_key", "is", "None", ":", "config_prop", ".", "property_key", "=", "attr_name" ]
Set unspecified property_keys for each ConfigProperty to the name of the class attr
[ "Set", "unspecified", "property_keys", "for", "each", "ConfigProperty", "to", "the", "name", "of", "the", "class", "attr" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L77-L81
train
kensho-technologies/grift
grift/config.py
BaseConfig._set_instance_prop
def _set_instance_prop(self, attr_name, config_prop, value): """Set instance property to a value and add it varz if needed""" setattr(self, attr_name, value) # add to varz if it is not private if not config_prop.exclude_from_varz: self.varz[attr_name] = value
python
def _set_instance_prop(self, attr_name, config_prop, value): """Set instance property to a value and add it varz if needed""" setattr(self, attr_name, value) # add to varz if it is not private if not config_prop.exclude_from_varz: self.varz[attr_name] = value
[ "def", "_set_instance_prop", "(", "self", ",", "attr_name", ",", "config_prop", ",", "value", ")", ":", "setattr", "(", "self", ",", "attr_name", ",", "value", ")", "if", "not", "config_prop", ".", "exclude_from_varz", ":", "self", ".", "varz", "[", "attr_name", "]", "=", "value" ]
Set instance property to a value and add it varz if needed
[ "Set", "instance", "property", "to", "a", "value", "and", "add", "it", "varz", "if", "needed" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L83-L89
train
kensho-technologies/grift
grift/config.py
BaseConfig._load
def _load(self): """Load values for all ConfigProperty attributes""" for attr_name, config_prop in self._iter_config_props(): found = False for loader in self._loaders: if loader.exists(config_prop.property_key): raw_value = loader.get(config_prop.property_key) converted_value = config_prop.load(raw_value) self._set_instance_prop(attr_name, config_prop, converted_value) found = True break if not found: if not config_prop.required or config_prop.default is not None: self._set_instance_prop(attr_name, config_prop, config_prop.default) else: raise ValueError('Missing required ConfigProperty {}'.format(attr_name))
python
def _load(self): """Load values for all ConfigProperty attributes""" for attr_name, config_prop in self._iter_config_props(): found = False for loader in self._loaders: if loader.exists(config_prop.property_key): raw_value = loader.get(config_prop.property_key) converted_value = config_prop.load(raw_value) self._set_instance_prop(attr_name, config_prop, converted_value) found = True break if not found: if not config_prop.required or config_prop.default is not None: self._set_instance_prop(attr_name, config_prop, config_prop.default) else: raise ValueError('Missing required ConfigProperty {}'.format(attr_name))
[ "def", "_load", "(", "self", ")", ":", "for", "attr_name", ",", "config_prop", "in", "self", ".", "_iter_config_props", "(", ")", ":", "found", "=", "False", "for", "loader", "in", "self", ".", "_loaders", ":", "if", "loader", ".", "exists", "(", "config_prop", ".", "property_key", ")", ":", "raw_value", "=", "loader", ".", "get", "(", "config_prop", ".", "property_key", ")", "converted_value", "=", "config_prop", ".", "load", "(", "raw_value", ")", "self", ".", "_set_instance_prop", "(", "attr_name", ",", "config_prop", ",", "converted_value", ")", "found", "=", "True", "break", "if", "not", "found", ":", "if", "not", "config_prop", ".", "required", "or", "config_prop", ".", "default", "is", "not", "None", ":", "self", ".", "_set_instance_prop", "(", "attr_name", ",", "config_prop", ",", "config_prop", ".", "default", ")", "else", ":", "raise", "ValueError", "(", "'Missing required ConfigProperty {}'", ".", "format", "(", "attr_name", ")", ")" ]
Load values for all ConfigProperty attributes
[ "Load", "values", "for", "all", "ConfigProperty", "attributes" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/config.py#L91-L108
train
kensho-technologies/grift
grift/utils.py
in_same_dir
def in_same_dir(as_file, target_file): """Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file """ return os.path.abspath(os.path.join(os.path.dirname(as_file), target_file))
python
def in_same_dir(as_file, target_file): """Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file """ return os.path.abspath(os.path.join(os.path.dirname(as_file), target_file))
[ "def", "in_same_dir", "(", "as_file", ",", "target_file", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "as_file", ")", ",", "target_file", ")", ")" ]
Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file
[ "Return", "an", "absolute", "path", "to", "a", "target", "file", "that", "is", "located", "in", "the", "same", "directory", "as", "as_file" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/utils.py#L5-L13
train
pr-omethe-us/PyKED
pyked/validation.py
compare_name
def compare_name(given_name, family_name, question_name): """Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer". Other possibilities include names with hyphens such as "Chih-Jen Sung", "C. J. Sung", "C-J Sung". Examples: >>> compare_name('Kyle', 'Niemeyer', 'Kyle E Niemeyer') True >>> compare_name('Chih-Jen', 'Sung', 'C-J Sung') True Args: given_name (`str`): Given (or first) name to be checked against. family_name (`str`): Family (or last) name to be checked against. question_name (`str`): The whole name in question. Returns: `bool`: The return value. True for successful comparison, False otherwise. """ # lowercase everything given_name = given_name.lower() family_name = family_name.lower() question_name = question_name.lower() # rearrange names given as "last, first middle" if ',' in question_name: name_split = question_name.split(',') name_split.reverse() question_name = ' '.join(name_split).strip() # remove periods question_name = question_name.replace('.', '') given_name = given_name.replace('.', '') family_name = family_name.replace('.', '') # split names by , <space> - . given_name = list(filter(None, re.split(r"[, \-.]+", given_name))) num_family_names = len(list(filter(None, re.split("[, .]+", family_name)))) # split name in question by , <space> - . name_split = list(filter(None, re.split(r"[, \-.]+", question_name))) first_name = [name_split[0]] if len(name_split) > 2: first_name += [n for n in name_split[1:-num_family_names]] if len(first_name) > 1 and len(given_name) == len(first_name): # both have same number of first and middle names/initials for i in range(1, len(first_name)): first_name[i] = first_name[i][0] given_name[i] = given_name[i][0] elif len(given_name) != len(first_name): min_names = min(len(given_name), len(first_name)) first_name = first_name[:min_names] given_name = given_name[:min_names] # first initial if len(first_name[0]) == 1 or len(given_name[0]) == 1: given_name[0] = given_name[0][0] first_name[0] = first_name[0][0] # first and middle initials combined if len(first_name[0]) > 1 or len(given_name[0]) > 1: given_name[0] = given_name[0][0] first_name[0] = name_split[0][0] # Hyphenated last name may need to be reconnected if num_family_names == 1 and '-' in family_name: num_hyphen = family_name.count('-') family_name_compare = '-'.join(name_split[-(num_hyphen + 1):]) else: family_name_compare = ' '.join(name_split[-num_family_names:]) return given_name == first_name and family_name == family_name_compare
python
def compare_name(given_name, family_name, question_name): """Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer". Other possibilities include names with hyphens such as "Chih-Jen Sung", "C. J. Sung", "C-J Sung". Examples: >>> compare_name('Kyle', 'Niemeyer', 'Kyle E Niemeyer') True >>> compare_name('Chih-Jen', 'Sung', 'C-J Sung') True Args: given_name (`str`): Given (or first) name to be checked against. family_name (`str`): Family (or last) name to be checked against. question_name (`str`): The whole name in question. Returns: `bool`: The return value. True for successful comparison, False otherwise. """ # lowercase everything given_name = given_name.lower() family_name = family_name.lower() question_name = question_name.lower() # rearrange names given as "last, first middle" if ',' in question_name: name_split = question_name.split(',') name_split.reverse() question_name = ' '.join(name_split).strip() # remove periods question_name = question_name.replace('.', '') given_name = given_name.replace('.', '') family_name = family_name.replace('.', '') # split names by , <space> - . given_name = list(filter(None, re.split(r"[, \-.]+", given_name))) num_family_names = len(list(filter(None, re.split("[, .]+", family_name)))) # split name in question by , <space> - . name_split = list(filter(None, re.split(r"[, \-.]+", question_name))) first_name = [name_split[0]] if len(name_split) > 2: first_name += [n for n in name_split[1:-num_family_names]] if len(first_name) > 1 and len(given_name) == len(first_name): # both have same number of first and middle names/initials for i in range(1, len(first_name)): first_name[i] = first_name[i][0] given_name[i] = given_name[i][0] elif len(given_name) != len(first_name): min_names = min(len(given_name), len(first_name)) first_name = first_name[:min_names] given_name = given_name[:min_names] # first initial if len(first_name[0]) == 1 or len(given_name[0]) == 1: given_name[0] = given_name[0][0] first_name[0] = first_name[0][0] # first and middle initials combined if len(first_name[0]) > 1 or len(given_name[0]) > 1: given_name[0] = given_name[0][0] first_name[0] = name_split[0][0] # Hyphenated last name may need to be reconnected if num_family_names == 1 and '-' in family_name: num_hyphen = family_name.count('-') family_name_compare = '-'.join(name_split[-(num_hyphen + 1):]) else: family_name_compare = ' '.join(name_split[-num_family_names:]) return given_name == first_name and family_name == family_name_compare
[ "def", "compare_name", "(", "given_name", ",", "family_name", ",", "question_name", ")", ":", "given_name", "=", "given_name", ".", "lower", "(", ")", "family_name", "=", "family_name", ".", "lower", "(", ")", "question_name", "=", "question_name", ".", "lower", "(", ")", "if", "','", "in", "question_name", ":", "name_split", "=", "question_name", ".", "split", "(", "','", ")", "name_split", ".", "reverse", "(", ")", "question_name", "=", "' '", ".", "join", "(", "name_split", ")", ".", "strip", "(", ")", "question_name", "=", "question_name", ".", "replace", "(", "'.'", ",", "''", ")", "given_name", "=", "given_name", ".", "replace", "(", "'.'", ",", "''", ")", "family_name", "=", "family_name", ".", "replace", "(", "'.'", ",", "''", ")", "given_name", "=", "list", "(", "filter", "(", "None", ",", "re", ".", "split", "(", "r\"[, \\-.]+\"", ",", "given_name", ")", ")", ")", "num_family_names", "=", "len", "(", "list", "(", "filter", "(", "None", ",", "re", ".", "split", "(", "\"[, .]+\"", ",", "family_name", ")", ")", ")", ")", "name_split", "=", "list", "(", "filter", "(", "None", ",", "re", ".", "split", "(", "r\"[, \\-.]+\"", ",", "question_name", ")", ")", ")", "first_name", "=", "[", "name_split", "[", "0", "]", "]", "if", "len", "(", "name_split", ")", ">", "2", ":", "first_name", "+=", "[", "n", "for", "n", "in", "name_split", "[", "1", ":", "-", "num_family_names", "]", "]", "if", "len", "(", "first_name", ")", ">", "1", "and", "len", "(", "given_name", ")", "==", "len", "(", "first_name", ")", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "first_name", ")", ")", ":", "first_name", "[", "i", "]", "=", "first_name", "[", "i", "]", "[", "0", "]", "given_name", "[", "i", "]", "=", "given_name", "[", "i", "]", "[", "0", "]", "elif", "len", "(", "given_name", ")", "!=", "len", "(", "first_name", ")", ":", "min_names", "=", "min", "(", "len", "(", "given_name", ")", ",", "len", "(", "first_name", ")", ")", "first_name", "=", "first_name", "[", ":", "min_names", "]", "given_name", "=", "given_name", "[", ":", "min_names", "]", "if", "len", "(", "first_name", "[", "0", "]", ")", "==", "1", "or", "len", "(", "given_name", "[", "0", "]", ")", "==", "1", ":", "given_name", "[", "0", "]", "=", "given_name", "[", "0", "]", "[", "0", "]", "first_name", "[", "0", "]", "=", "first_name", "[", "0", "]", "[", "0", "]", "if", "len", "(", "first_name", "[", "0", "]", ")", ">", "1", "or", "len", "(", "given_name", "[", "0", "]", ")", ">", "1", ":", "given_name", "[", "0", "]", "=", "given_name", "[", "0", "]", "[", "0", "]", "first_name", "[", "0", "]", "=", "name_split", "[", "0", "]", "[", "0", "]", "if", "num_family_names", "==", "1", "and", "'-'", "in", "family_name", ":", "num_hyphen", "=", "family_name", ".", "count", "(", "'-'", ")", "family_name_compare", "=", "'-'", ".", "join", "(", "name_split", "[", "-", "(", "num_hyphen", "+", "1", ")", ":", "]", ")", "else", ":", "family_name_compare", "=", "' '", ".", "join", "(", "name_split", "[", "-", "num_family_names", ":", "]", ")", "return", "given_name", "==", "first_name", "and", "family_name", "==", "family_name_compare" ]
Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer". Other possibilities include names with hyphens such as "Chih-Jen Sung", "C. J. Sung", "C-J Sung". Examples: >>> compare_name('Kyle', 'Niemeyer', 'Kyle E Niemeyer') True >>> compare_name('Chih-Jen', 'Sung', 'C-J Sung') True Args: given_name (`str`): Given (or first) name to be checked against. family_name (`str`): Family (or last) name to be checked against. question_name (`str`): The whole name in question. Returns: `bool`: The return value. True for successful comparison, False otherwise.
[ "Compares", "a", "name", "in", "question", "to", "a", "specified", "name", "separated", "into", "given", "and", "family", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L91-L166
train
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_history
def _validate_isvalid_history(self, isvalid_history, field, value): """Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. value (`dict`): dictionary of values from file associated with this property. The rule's arguments are validated against this schema: {'isvalid_history': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}} """ # Check the type has appropriate units history_type = value['type'] if history_type.endswith('emission'): history_type = 'emission' elif history_type.endswith('absorption'): history_type = 'absorption' quantity = 1.0*(units(value['quantity']['units'])) try: quantity.to(property_units[history_type]) except pint.DimensionalityError: self._error(field, 'incompatible units; should be consistent ' 'with ' + property_units[history_type]) # Check that time has appropriate units time = 1.0*(units(value['time']['units'])) try: time.to(property_units['time']) except pint.DimensionalityError: self._error(field, 'incompatible units; should be consistent ' 'with ' + property_units['time']) # Check that the values have the right number of columns n_cols = len(value['values'][0]) max_cols = max(value['time']['column'], value['quantity']['column'], value.get('uncertainty', {}).get('column', 0)) + 1 if n_cols > max_cols: self._error(field, 'too many columns in the values') elif n_cols < max_cols: self._error(field, 'not enough columns in the values')
python
def _validate_isvalid_history(self, isvalid_history, field, value): """Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. value (`dict`): dictionary of values from file associated with this property. The rule's arguments are validated against this schema: {'isvalid_history': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}} """ # Check the type has appropriate units history_type = value['type'] if history_type.endswith('emission'): history_type = 'emission' elif history_type.endswith('absorption'): history_type = 'absorption' quantity = 1.0*(units(value['quantity']['units'])) try: quantity.to(property_units[history_type]) except pint.DimensionalityError: self._error(field, 'incompatible units; should be consistent ' 'with ' + property_units[history_type]) # Check that time has appropriate units time = 1.0*(units(value['time']['units'])) try: time.to(property_units['time']) except pint.DimensionalityError: self._error(field, 'incompatible units; should be consistent ' 'with ' + property_units['time']) # Check that the values have the right number of columns n_cols = len(value['values'][0]) max_cols = max(value['time']['column'], value['quantity']['column'], value.get('uncertainty', {}).get('column', 0)) + 1 if n_cols > max_cols: self._error(field, 'too many columns in the values') elif n_cols < max_cols: self._error(field, 'not enough columns in the values')
[ "def", "_validate_isvalid_history", "(", "self", ",", "isvalid_history", ",", "field", ",", "value", ")", ":", "history_type", "=", "value", "[", "'type'", "]", "if", "history_type", ".", "endswith", "(", "'emission'", ")", ":", "history_type", "=", "'emission'", "elif", "history_type", ".", "endswith", "(", "'absorption'", ")", ":", "history_type", "=", "'absorption'", "quantity", "=", "1.0", "*", "(", "units", "(", "value", "[", "'quantity'", "]", "[", "'units'", "]", ")", ")", "try", ":", "quantity", ".", "to", "(", "property_units", "[", "history_type", "]", ")", "except", "pint", ".", "DimensionalityError", ":", "self", ".", "_error", "(", "field", ",", "'incompatible units; should be consistent '", "'with '", "+", "property_units", "[", "history_type", "]", ")", "time", "=", "1.0", "*", "(", "units", "(", "value", "[", "'time'", "]", "[", "'units'", "]", ")", ")", "try", ":", "time", ".", "to", "(", "property_units", "[", "'time'", "]", ")", "except", "pint", ".", "DimensionalityError", ":", "self", ".", "_error", "(", "field", ",", "'incompatible units; should be consistent '", "'with '", "+", "property_units", "[", "'time'", "]", ")", "n_cols", "=", "len", "(", "value", "[", "'values'", "]", "[", "0", "]", ")", "max_cols", "=", "max", "(", "value", "[", "'time'", "]", "[", "'column'", "]", ",", "value", "[", "'quantity'", "]", "[", "'column'", "]", ",", "value", ".", "get", "(", "'uncertainty'", ",", "{", "}", ")", ".", "get", "(", "'column'", ",", "0", ")", ")", "+", "1", "if", "n_cols", ">", "max_cols", ":", "self", ".", "_error", "(", "field", ",", "'too many columns in the values'", ")", "elif", "n_cols", "<", "max_cols", ":", "self", ".", "_error", "(", "field", ",", "'not enough columns in the values'", ")" ]
Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. value (`dict`): dictionary of values from file associated with this property. The rule's arguments are validated against this schema: {'isvalid_history': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}}
[ "Checks", "that", "the", "given", "time", "history", "is", "properly", "formatted", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L221-L262
train
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_quantity
def _validate_isvalid_quantity(self, isvalid_quantity, field, value): """Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. value (`list`): list whose first element is a string representing a value with units The rule's arguments are validated against this schema: {'isvalid_quantity': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'list'}} """ quantity = Q_(value[0]) low_lim = 0.0 * units(property_units[field]) try: if quantity <= low_lim: self._error( field, 'value must be greater than 0.0 {}'.format(property_units[field]), ) except pint.DimensionalityError: self._error(field, 'incompatible units; should be consistent ' 'with ' + property_units[field] )
python
def _validate_isvalid_quantity(self, isvalid_quantity, field, value): """Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. value (`list`): list whose first element is a string representing a value with units The rule's arguments are validated against this schema: {'isvalid_quantity': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'list'}} """ quantity = Q_(value[0]) low_lim = 0.0 * units(property_units[field]) try: if quantity <= low_lim: self._error( field, 'value must be greater than 0.0 {}'.format(property_units[field]), ) except pint.DimensionalityError: self._error(field, 'incompatible units; should be consistent ' 'with ' + property_units[field] )
[ "def", "_validate_isvalid_quantity", "(", "self", ",", "isvalid_quantity", ",", "field", ",", "value", ")", ":", "quantity", "=", "Q_", "(", "value", "[", "0", "]", ")", "low_lim", "=", "0.0", "*", "units", "(", "property_units", "[", "field", "]", ")", "try", ":", "if", "quantity", "<=", "low_lim", ":", "self", ".", "_error", "(", "field", ",", "'value must be greater than 0.0 {}'", ".", "format", "(", "property_units", "[", "field", "]", ")", ",", ")", "except", "pint", ".", "DimensionalityError", ":", "self", ".", "_error", "(", "field", ",", "'incompatible units; should be consistent '", "'with '", "+", "property_units", "[", "field", "]", ")" ]
Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. value (`list`): list whose first element is a string representing a value with units The rule's arguments are validated against this schema: {'isvalid_quantity': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'list'}}
[ "Checks", "for", "valid", "given", "value", "and", "appropriate", "units", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L264-L287
train
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_uncertainty
def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value): """Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with the quantity in question. value (`list`): list with the string of the value of the quantity and a dictionary of the uncertainty The rule's arguments are validated against this schema: {'isvalid_uncertainty': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'list'}} """ self._validate_isvalid_quantity(True, field, value) # This len check is necessary for reasons that aren't quite clear to me # Cerberus calls this validation method even when lists have only one element # and should therefore be validated only by isvalid_quantity if len(value) > 1 and value[1]['uncertainty-type'] != 'relative': if value[1].get('uncertainty') is not None: self._validate_isvalid_quantity(True, field, [value[1]['uncertainty']]) if value[1].get('upper-uncertainty') is not None: self._validate_isvalid_quantity(True, field, [value[1]['upper-uncertainty']]) if value[1].get('lower-uncertainty') is not None: self._validate_isvalid_quantity(True, field, [value[1]['lower-uncertainty']])
python
def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value): """Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with the quantity in question. value (`list`): list with the string of the value of the quantity and a dictionary of the uncertainty The rule's arguments are validated against this schema: {'isvalid_uncertainty': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'list'}} """ self._validate_isvalid_quantity(True, field, value) # This len check is necessary for reasons that aren't quite clear to me # Cerberus calls this validation method even when lists have only one element # and should therefore be validated only by isvalid_quantity if len(value) > 1 and value[1]['uncertainty-type'] != 'relative': if value[1].get('uncertainty') is not None: self._validate_isvalid_quantity(True, field, [value[1]['uncertainty']]) if value[1].get('upper-uncertainty') is not None: self._validate_isvalid_quantity(True, field, [value[1]['upper-uncertainty']]) if value[1].get('lower-uncertainty') is not None: self._validate_isvalid_quantity(True, field, [value[1]['lower-uncertainty']])
[ "def", "_validate_isvalid_uncertainty", "(", "self", ",", "isvalid_uncertainty", ",", "field", ",", "value", ")", ":", "self", ".", "_validate_isvalid_quantity", "(", "True", ",", "field", ",", "value", ")", "if", "len", "(", "value", ")", ">", "1", "and", "value", "[", "1", "]", "[", "'uncertainty-type'", "]", "!=", "'relative'", ":", "if", "value", "[", "1", "]", ".", "get", "(", "'uncertainty'", ")", "is", "not", "None", ":", "self", ".", "_validate_isvalid_quantity", "(", "True", ",", "field", ",", "[", "value", "[", "1", "]", "[", "'uncertainty'", "]", "]", ")", "if", "value", "[", "1", "]", ".", "get", "(", "'upper-uncertainty'", ")", "is", "not", "None", ":", "self", ".", "_validate_isvalid_quantity", "(", "True", ",", "field", ",", "[", "value", "[", "1", "]", "[", "'upper-uncertainty'", "]", "]", ")", "if", "value", "[", "1", "]", ".", "get", "(", "'lower-uncertainty'", ")", "is", "not", "None", ":", "self", ".", "_validate_isvalid_quantity", "(", "True", ",", "field", ",", "[", "value", "[", "1", "]", "[", "'lower-uncertainty'", "]", "]", ")" ]
Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with the quantity in question. value (`list`): list with the string of the value of the quantity and a dictionary of the uncertainty The rule's arguments are validated against this schema: {'isvalid_uncertainty': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'list'}}
[ "Checks", "for", "valid", "given", "value", "and", "appropriate", "units", "with", "uncertainty", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L289-L315
train
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_orcid
def _validate_isvalid_orcid(self, isvalid_orcid, field, value): """Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule's arguments are validated against this schema: {'isvalid_orcid': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}} """ if isvalid_orcid and 'ORCID' in value: try: res = search_orcid(value['ORCID']) except ConnectionError: warn('network not available, ORCID not validated.') return except HTTPError: self._error(field, 'ORCID incorrect or invalid for ' + value['name'] ) return family_name = res['name']['family-name']['value'] given_name = res['name']['given-names']['value'] if not compare_name(given_name, family_name, value['name']): self._error(field, 'Name and ORCID do not match. Name supplied: ' + value['name'] + '. Name associated with ORCID: ' + ' '.join([given_name, family_name]) )
python
def _validate_isvalid_orcid(self, isvalid_orcid, field, value): """Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule's arguments are validated against this schema: {'isvalid_orcid': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}} """ if isvalid_orcid and 'ORCID' in value: try: res = search_orcid(value['ORCID']) except ConnectionError: warn('network not available, ORCID not validated.') return except HTTPError: self._error(field, 'ORCID incorrect or invalid for ' + value['name'] ) return family_name = res['name']['family-name']['value'] given_name = res['name']['given-names']['value'] if not compare_name(given_name, family_name, value['name']): self._error(field, 'Name and ORCID do not match. Name supplied: ' + value['name'] + '. Name associated with ORCID: ' + ' '.join([given_name, family_name]) )
[ "def", "_validate_isvalid_orcid", "(", "self", ",", "isvalid_orcid", ",", "field", ",", "value", ")", ":", "if", "isvalid_orcid", "and", "'ORCID'", "in", "value", ":", "try", ":", "res", "=", "search_orcid", "(", "value", "[", "'ORCID'", "]", ")", "except", "ConnectionError", ":", "warn", "(", "'network not available, ORCID not validated.'", ")", "return", "except", "HTTPError", ":", "self", ".", "_error", "(", "field", ",", "'ORCID incorrect or invalid for '", "+", "value", "[", "'name'", "]", ")", "return", "family_name", "=", "res", "[", "'name'", "]", "[", "'family-name'", "]", "[", "'value'", "]", "given_name", "=", "res", "[", "'name'", "]", "[", "'given-names'", "]", "[", "'value'", "]", "if", "not", "compare_name", "(", "given_name", ",", "family_name", ",", "value", "[", "'name'", "]", ")", ":", "self", ".", "_error", "(", "field", ",", "'Name and ORCID do not match. Name supplied: '", "+", "value", "[", "'name'", "]", "+", "'. Name associated with ORCID: '", "+", "' '", ".", "join", "(", "[", "given_name", ",", "family_name", "]", ")", ")" ]
Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule's arguments are validated against this schema: {'isvalid_orcid': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}}
[ "Checks", "for", "valid", "ORCID", "if", "given", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L420-L451
train
pr-omethe-us/PyKED
pyked/validation.py
OurValidator._validate_isvalid_composition
def _validate_isvalid_composition(self, isvalid_composition, field, value): """Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (dict): dictionary of composition The rule's arguments are validated against this schema: {'isvalid_composition': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}} """ sum_amount = 0.0 if value['kind'] in ['mass fraction', 'mole fraction']: low_lim = 0.0 up_lim = 1.0 total_amount = 1.0 elif value['kind'] in ['mole percent']: low_lim = 0.0 up_lim = 100.0 total_amount = 100.0 else: self._error(field, 'composition kind must be "mole percent", "mass fraction", or ' '"mole fraction"') return False for sp in value['species']: amount = sp['amount'][0] sum_amount += amount # Check that amount within bounds, based on kind specified if amount < low_lim: self._error(field, 'Species ' + sp['species-name'] + ' ' + value['kind'] + ' must be greater than {:.1f}'.format(low_lim) ) elif amount > up_lim: self._error(field, 'Species ' + sp['species-name'] + ' ' + value['kind'] + ' must be less than {:.1f}'.format(up_lim) ) # Make sure mole/mass fraction sum to 1 if not np.isclose(total_amount, sum_amount): self._error(field, 'Species ' + value['kind'] + 's do not sum to {:.1f}: '.format(total_amount) + '{:f}'.format(sum_amount) )
python
def _validate_isvalid_composition(self, isvalid_composition, field, value): """Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (dict): dictionary of composition The rule's arguments are validated against this schema: {'isvalid_composition': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}} """ sum_amount = 0.0 if value['kind'] in ['mass fraction', 'mole fraction']: low_lim = 0.0 up_lim = 1.0 total_amount = 1.0 elif value['kind'] in ['mole percent']: low_lim = 0.0 up_lim = 100.0 total_amount = 100.0 else: self._error(field, 'composition kind must be "mole percent", "mass fraction", or ' '"mole fraction"') return False for sp in value['species']: amount = sp['amount'][0] sum_amount += amount # Check that amount within bounds, based on kind specified if amount < low_lim: self._error(field, 'Species ' + sp['species-name'] + ' ' + value['kind'] + ' must be greater than {:.1f}'.format(low_lim) ) elif amount > up_lim: self._error(field, 'Species ' + sp['species-name'] + ' ' + value['kind'] + ' must be less than {:.1f}'.format(up_lim) ) # Make sure mole/mass fraction sum to 1 if not np.isclose(total_amount, sum_amount): self._error(field, 'Species ' + value['kind'] + 's do not sum to {:.1f}: '.format(total_amount) + '{:f}'.format(sum_amount) )
[ "def", "_validate_isvalid_composition", "(", "self", ",", "isvalid_composition", ",", "field", ",", "value", ")", ":", "sum_amount", "=", "0.0", "if", "value", "[", "'kind'", "]", "in", "[", "'mass fraction'", ",", "'mole fraction'", "]", ":", "low_lim", "=", "0.0", "up_lim", "=", "1.0", "total_amount", "=", "1.0", "elif", "value", "[", "'kind'", "]", "in", "[", "'mole percent'", "]", ":", "low_lim", "=", "0.0", "up_lim", "=", "100.0", "total_amount", "=", "100.0", "else", ":", "self", ".", "_error", "(", "field", ",", "'composition kind must be \"mole percent\", \"mass fraction\", or '", "'\"mole fraction\"'", ")", "return", "False", "for", "sp", "in", "value", "[", "'species'", "]", ":", "amount", "=", "sp", "[", "'amount'", "]", "[", "0", "]", "sum_amount", "+=", "amount", "if", "amount", "<", "low_lim", ":", "self", ".", "_error", "(", "field", ",", "'Species '", "+", "sp", "[", "'species-name'", "]", "+", "' '", "+", "value", "[", "'kind'", "]", "+", "' must be greater than {:.1f}'", ".", "format", "(", "low_lim", ")", ")", "elif", "amount", ">", "up_lim", ":", "self", ".", "_error", "(", "field", ",", "'Species '", "+", "sp", "[", "'species-name'", "]", "+", "' '", "+", "value", "[", "'kind'", "]", "+", "' must be less than {:.1f}'", ".", "format", "(", "up_lim", ")", ")", "if", "not", "np", ".", "isclose", "(", "total_amount", ",", "sum_amount", ")", ":", "self", ".", "_error", "(", "field", ",", "'Species '", "+", "value", "[", "'kind'", "]", "+", "'s do not sum to {:.1f}: '", ".", "format", "(", "total_amount", ")", "+", "'{:f}'", ".", "format", "(", "sum_amount", ")", ")" ]
Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (dict): dictionary of composition The rule's arguments are validated against this schema: {'isvalid_composition': {'type': 'bool'}, 'field': {'type': 'str'}, 'value': {'type': 'dict'}}
[ "Checks", "for", "valid", "specification", "of", "composition", "." ]
d9341a068c1099049a3f1de41c512591f342bf64
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/validation.py#L453-L499
train
gsi-upm/soil
soil/analysis.py
convert_types_slow
def convert_types_slow(df): '''This is a slow operation.''' dtypes = get_types(df) for k, v in dtypes.items(): t = df[df['key']==k] t['value'] = t['value'].astype(v) df = df.apply(convert_row, axis=1) return df
python
def convert_types_slow(df): '''This is a slow operation.''' dtypes = get_types(df) for k, v in dtypes.items(): t = df[df['key']==k] t['value'] = t['value'].astype(v) df = df.apply(convert_row, axis=1) return df
[ "def", "convert_types_slow", "(", "df", ")", ":", "dtypes", "=", "get_types", "(", "df", ")", "for", "k", ",", "v", "in", "dtypes", ".", "items", "(", ")", ":", "t", "=", "df", "[", "df", "[", "'key'", "]", "==", "k", "]", "t", "[", "'value'", "]", "=", "t", "[", "'value'", "]", ".", "astype", "(", "v", ")", "df", "=", "df", ".", "apply", "(", "convert_row", ",", "axis", "=", "1", ")", "return", "df" ]
This is a slow operation.
[ "This", "is", "a", "slow", "operation", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/analysis.py#L63-L70
train
gsi-upm/soil
soil/analysis.py
plot_all
def plot_all(*args, **kwargs): ''' Read all the trial data and plot the result of applying a function on them. ''' dfs = do_all(*args, **kwargs) ps = [] for line in dfs: f, df, config = line df.plot(title=config['name']) ps.append(df) return ps
python
def plot_all(*args, **kwargs): ''' Read all the trial data and plot the result of applying a function on them. ''' dfs = do_all(*args, **kwargs) ps = [] for line in dfs: f, df, config = line df.plot(title=config['name']) ps.append(df) return ps
[ "def", "plot_all", "(", "*", "args", ",", "**", "kwargs", ")", ":", "dfs", "=", "do_all", "(", "*", "args", ",", "**", "kwargs", ")", "ps", "=", "[", "]", "for", "line", "in", "dfs", ":", "f", ",", "df", ",", "config", "=", "line", "df", ".", "plot", "(", "title", "=", "config", "[", "'name'", "]", ")", "ps", ".", "append", "(", "df", ")", "return", "ps" ]
Read all the trial data and plot the result of applying a function on them.
[ "Read", "all", "the", "trial", "data", "and", "plot", "the", "result", "of", "applying", "a", "function", "on", "them", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/analysis.py#L139-L149
train
gsi-upm/soil
soil/utils.py
serialize
def serialize(v, known_modules=[]): '''Get a text representation of an object.''' tname = name(v, known_modules=known_modules) func = serializer(tname) return func(v), tname
python
def serialize(v, known_modules=[]): '''Get a text representation of an object.''' tname = name(v, known_modules=known_modules) func = serializer(tname) return func(v), tname
[ "def", "serialize", "(", "v", ",", "known_modules", "=", "[", "]", ")", ":", "tname", "=", "name", "(", "v", ",", "known_modules", "=", "known_modules", ")", "func", "=", "serializer", "(", "tname", ")", "return", "func", "(", "v", ")", ",", "tname" ]
Get a text representation of an object.
[ "Get", "a", "text", "representation", "of", "an", "object", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/utils.py#L116-L120
train
gsi-upm/soil
soil/utils.py
deserialize
def deserialize(type_, value=None, **kwargs): '''Get an object from a text representation''' if not isinstance(type_, str): return type_ des = deserializer(type_, **kwargs) if value is None: return des return des(value)
python
def deserialize(type_, value=None, **kwargs): '''Get an object from a text representation''' if not isinstance(type_, str): return type_ des = deserializer(type_, **kwargs) if value is None: return des return des(value)
[ "def", "deserialize", "(", "type_", ",", "value", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "isinstance", "(", "type_", ",", "str", ")", ":", "return", "type_", "des", "=", "deserializer", "(", "type_", ",", "**", "kwargs", ")", "if", "value", "is", "None", ":", "return", "des", "return", "des", "(", "value", ")" ]
Get an object from a text representation
[ "Get", "an", "object", "from", "a", "text", "representation" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/utils.py#L155-L162
train
Genida/django-meerkat
src/meerkat/logs/parsers.py
GenericParser.content
def content(self): """ Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line). """ if self._content is None: self._content = self.parse_files() return self._content
python
def content(self): """ Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line). """ if self._content is None: self._content = self.parse_files() return self._content
[ "def", "content", "(", "self", ")", ":", "if", "self", ".", "_content", "is", "None", ":", "self", ".", "_content", "=", "self", ".", "parse_files", "(", ")", "return", "self", ".", "_content" ]
Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line).
[ "Return", "parsed", "data", ".", "Parse", "it", "if", "not", "already", "parsed", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/parsers.py#L48-L57
train
Genida/django-meerkat
src/meerkat/logs/parsers.py
GenericParser.parse_files
def parse_files(self): """ Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line). """ log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: matches = re.finditer(log_re, f.read()) for match in matches: log_lines.append(match.groupdict()) return log_lines
python
def parse_files(self): """ Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line). """ log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: matches = re.finditer(log_re, f.read()) for match in matches: log_lines.append(match.groupdict()) return log_lines
[ "def", "parse_files", "(", "self", ")", ":", "log_re", "=", "self", ".", "log_format_regex", "log_lines", "=", "[", "]", "for", "log_file", "in", "self", ".", "matching_files", "(", ")", ":", "with", "open", "(", "log_file", ")", "as", "f", ":", "matches", "=", "re", ".", "finditer", "(", "log_re", ",", "f", ".", "read", "(", ")", ")", "for", "match", "in", "matches", ":", "log_lines", ".", "append", "(", "match", ".", "groupdict", "(", ")", ")", "return", "log_lines" ]
Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line).
[ "Find", "the", "files", "and", "parse", "them", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/parsers.py#L86-L100
train
gsi-upm/soil
soil/agents/__init__.py
serialize_distribution
def serialize_distribution(network_agents, known_modules=[]): ''' When serializing an agent distribution, remove the thresholds, in order to avoid cluttering the YAML definition file. ''' d = deepcopy(list(network_agents)) for v in d: if 'threshold' in v: del v['threshold'] v['agent_type'] = serialize_type(v['agent_type'], known_modules=known_modules) return d
python
def serialize_distribution(network_agents, known_modules=[]): ''' When serializing an agent distribution, remove the thresholds, in order to avoid cluttering the YAML definition file. ''' d = deepcopy(list(network_agents)) for v in d: if 'threshold' in v: del v['threshold'] v['agent_type'] = serialize_type(v['agent_type'], known_modules=known_modules) return d
[ "def", "serialize_distribution", "(", "network_agents", ",", "known_modules", "=", "[", "]", ")", ":", "d", "=", "deepcopy", "(", "list", "(", "network_agents", ")", ")", "for", "v", "in", "d", ":", "if", "'threshold'", "in", "v", ":", "del", "v", "[", "'threshold'", "]", "v", "[", "'agent_type'", "]", "=", "serialize_type", "(", "v", "[", "'agent_type'", "]", ",", "known_modules", "=", "known_modules", ")", "return", "d" ]
When serializing an agent distribution, remove the thresholds, in order to avoid cluttering the YAML definition file.
[ "When", "serializing", "an", "agent", "distribution", "remove", "the", "thresholds", "in", "order", "to", "avoid", "cluttering", "the", "YAML", "definition", "file", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L394-L405
train
gsi-upm/soil
soil/agents/__init__.py
_validate_states
def _validate_states(states, topology): '''Validate states to avoid ignoring states during initialization''' states = states or [] if isinstance(states, dict): for x in states: assert x in topology.node else: assert len(states) <= len(topology) return states
python
def _validate_states(states, topology): '''Validate states to avoid ignoring states during initialization''' states = states or [] if isinstance(states, dict): for x in states: assert x in topology.node else: assert len(states) <= len(topology) return states
[ "def", "_validate_states", "(", "states", ",", "topology", ")", ":", "states", "=", "states", "or", "[", "]", "if", "isinstance", "(", "states", ",", "dict", ")", ":", "for", "x", "in", "states", ":", "assert", "x", "in", "topology", ".", "node", "else", ":", "assert", "len", "(", "states", ")", "<=", "len", "(", "topology", ")", "return", "states" ]
Validate states to avoid ignoring states during initialization
[ "Validate", "states", "to", "avoid", "ignoring", "states", "during", "initialization" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L423-L431
train
gsi-upm/soil
soil/agents/__init__.py
_convert_agent_types
def _convert_agent_types(ind, to_string=False, **kwargs): '''Convenience method to allow specifying agents by class or class name.''' if to_string: return serialize_distribution(ind, **kwargs) return deserialize_distribution(ind, **kwargs)
python
def _convert_agent_types(ind, to_string=False, **kwargs): '''Convenience method to allow specifying agents by class or class name.''' if to_string: return serialize_distribution(ind, **kwargs) return deserialize_distribution(ind, **kwargs)
[ "def", "_convert_agent_types", "(", "ind", ",", "to_string", "=", "False", ",", "**", "kwargs", ")", ":", "if", "to_string", ":", "return", "serialize_distribution", "(", "ind", ",", "**", "kwargs", ")", "return", "deserialize_distribution", "(", "ind", ",", "**", "kwargs", ")" ]
Convenience method to allow specifying agents by class or class name.
[ "Convenience", "method", "to", "allow", "specifying", "agents", "by", "class", "or", "class", "name", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L434-L438
train
gsi-upm/soil
soil/agents/__init__.py
_agent_from_distribution
def _agent_from_distribution(distribution, value=-1, agent_id=None): """Used in the initialization of agents given an agent distribution.""" if value < 0: value = random.random() for d in sorted(distribution, key=lambda x: x['threshold']): threshold = d['threshold'] # Check if the definition matches by id (first) or by threshold if not ((agent_id is not None and threshold == STATIC_THRESHOLD and agent_id in d['ids']) or \ (value >= threshold[0] and value < threshold[1])): continue state = {} if 'state' in d: state = deepcopy(d['state']) return d['agent_type'], state raise Exception('Distribution for value {} not found in: {}'.format(value, distribution))
python
def _agent_from_distribution(distribution, value=-1, agent_id=None): """Used in the initialization of agents given an agent distribution.""" if value < 0: value = random.random() for d in sorted(distribution, key=lambda x: x['threshold']): threshold = d['threshold'] # Check if the definition matches by id (first) or by threshold if not ((agent_id is not None and threshold == STATIC_THRESHOLD and agent_id in d['ids']) or \ (value >= threshold[0] and value < threshold[1])): continue state = {} if 'state' in d: state = deepcopy(d['state']) return d['agent_type'], state raise Exception('Distribution for value {} not found in: {}'.format(value, distribution))
[ "def", "_agent_from_distribution", "(", "distribution", ",", "value", "=", "-", "1", ",", "agent_id", "=", "None", ")", ":", "if", "value", "<", "0", ":", "value", "=", "random", ".", "random", "(", ")", "for", "d", "in", "sorted", "(", "distribution", ",", "key", "=", "lambda", "x", ":", "x", "[", "'threshold'", "]", ")", ":", "threshold", "=", "d", "[", "'threshold'", "]", "if", "not", "(", "(", "agent_id", "is", "not", "None", "and", "threshold", "==", "STATIC_THRESHOLD", "and", "agent_id", "in", "d", "[", "'ids'", "]", ")", "or", "(", "value", ">=", "threshold", "[", "0", "]", "and", "value", "<", "threshold", "[", "1", "]", ")", ")", ":", "continue", "state", "=", "{", "}", "if", "'state'", "in", "d", ":", "state", "=", "deepcopy", "(", "d", "[", "'state'", "]", ")", "return", "d", "[", "'agent_type'", "]", ",", "state", "raise", "Exception", "(", "'Distribution for value {} not found in: {}'", ".", "format", "(", "value", ",", "distribution", ")", ")" ]
Used in the initialization of agents given an agent distribution.
[ "Used", "in", "the", "initialization", "of", "agents", "given", "an", "agent", "distribution", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/agents/__init__.py#L441-L456
train
gsi-upm/soil
soil/web/__init__.py
ModularServer.launch
def launch(self, port=None): """ Run the app. """ if port is not None: self.port = port url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port) print('Interface starting at {url}'.format(url=url)) self.listen(self.port) # webbrowser.open(url) tornado.ioloop.IOLoop.instance().start()
python
def launch(self, port=None): """ Run the app. """ if port is not None: self.port = port url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port) print('Interface starting at {url}'.format(url=url)) self.listen(self.port) # webbrowser.open(url) tornado.ioloop.IOLoop.instance().start()
[ "def", "launch", "(", "self", ",", "port", "=", "None", ")", ":", "if", "port", "is", "not", "None", ":", "self", ".", "port", "=", "port", "url", "=", "'http://127.0.0.1:{PORT}'", ".", "format", "(", "PORT", "=", "self", ".", "port", ")", "print", "(", "'Interface starting at {url}'", ".", "format", "(", "url", "=", "url", ")", ")", "self", ".", "listen", "(", "self", ".", "port", ")", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ".", "start", "(", ")" ]
Run the app.
[ "Run", "the", "app", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/web/__init__.py#L245-L254
train
Genida/django-meerkat
src/meerkat/logs/stats.py
status_codes_by_date_stats
def status_codes_by_date_stats(): """ Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. """ def date_counter(queryset): return dict(Counter(map( lambda dt: ms_since_epoch(datetime.combine( make_naive(dt), datetime.min.time())), list(queryset.values_list('datetime', flat=True))))) codes = {low: date_counter( RequestLog.objects.filter(status_code__gte=low, status_code__lt=high)) for low, high in ((200, 300), (300, 400), (400, 500))} codes[500] = date_counter(RequestLog.objects.filter(status_code__gte=500)) codes['attacks'] = date_counter(RequestLog.objects.filter( status_code__in=(400, 444, 502))) stats = {} for code in (200, 300, 400, 500, 'attacks'): for date, count in codes[code].items(): if stats.get(date, None) is None: stats[date] = {200: 0, 300: 0, 400: 0, 500: 0, 'attacks': 0} stats[date][code] += count stats = sorted([(k, v) for k, v in stats.items()], key=lambda x: x[0]) return stats
python
def status_codes_by_date_stats(): """ Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. """ def date_counter(queryset): return dict(Counter(map( lambda dt: ms_since_epoch(datetime.combine( make_naive(dt), datetime.min.time())), list(queryset.values_list('datetime', flat=True))))) codes = {low: date_counter( RequestLog.objects.filter(status_code__gte=low, status_code__lt=high)) for low, high in ((200, 300), (300, 400), (400, 500))} codes[500] = date_counter(RequestLog.objects.filter(status_code__gte=500)) codes['attacks'] = date_counter(RequestLog.objects.filter( status_code__in=(400, 444, 502))) stats = {} for code in (200, 300, 400, 500, 'attacks'): for date, count in codes[code].items(): if stats.get(date, None) is None: stats[date] = {200: 0, 300: 0, 400: 0, 500: 0, 'attacks': 0} stats[date][code] += count stats = sorted([(k, v) for k, v in stats.items()], key=lambda x: x[0]) return stats
[ "def", "status_codes_by_date_stats", "(", ")", ":", "def", "date_counter", "(", "queryset", ")", ":", "return", "dict", "(", "Counter", "(", "map", "(", "lambda", "dt", ":", "ms_since_epoch", "(", "datetime", ".", "combine", "(", "make_naive", "(", "dt", ")", ",", "datetime", ".", "min", ".", "time", "(", ")", ")", ")", ",", "list", "(", "queryset", ".", "values_list", "(", "'datetime'", ",", "flat", "=", "True", ")", ")", ")", ")", ")", "codes", "=", "{", "low", ":", "date_counter", "(", "RequestLog", ".", "objects", ".", "filter", "(", "status_code__gte", "=", "low", ",", "status_code__lt", "=", "high", ")", ")", "for", "low", ",", "high", "in", "(", "(", "200", ",", "300", ")", ",", "(", "300", ",", "400", ")", ",", "(", "400", ",", "500", ")", ")", "}", "codes", "[", "500", "]", "=", "date_counter", "(", "RequestLog", ".", "objects", ".", "filter", "(", "status_code__gte", "=", "500", ")", ")", "codes", "[", "'attacks'", "]", "=", "date_counter", "(", "RequestLog", ".", "objects", ".", "filter", "(", "status_code__in", "=", "(", "400", ",", "444", ",", "502", ")", ")", ")", "stats", "=", "{", "}", "for", "code", "in", "(", "200", ",", "300", ",", "400", ",", "500", ",", "'attacks'", ")", ":", "for", "date", ",", "count", "in", "codes", "[", "code", "]", ".", "items", "(", ")", ":", "if", "stats", ".", "get", "(", "date", ",", "None", ")", "is", "None", ":", "stats", "[", "date", "]", "=", "{", "200", ":", "0", ",", "300", ":", "0", ",", "400", ":", "0", ",", "500", ":", "0", ",", "'attacks'", ":", "0", "}", "stats", "[", "date", "]", "[", "code", "]", "+=", "count", "stats", "=", "sorted", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "stats", ".", "items", "(", ")", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "return", "stats" ]
Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
[ "Get", "stats", "for", "status", "codes", "by", "date", "." ]
486502a75bb0800266db785fd32717d8c0eb8deb
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/stats.py#L38-L67
train
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
CityPubs.enter
def enter(self, pub_id, *nodes): '''Agents will try to enter. The pub checks if it is possible''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) if not pub['open'] or (pub['capacity'] < (len(nodes) + pub['occupancy'])): return False pub['occupancy'] += len(nodes) for node in nodes: node['pub'] = pub_id return True
python
def enter(self, pub_id, *nodes): '''Agents will try to enter. The pub checks if it is possible''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) if not pub['open'] or (pub['capacity'] < (len(nodes) + pub['occupancy'])): return False pub['occupancy'] += len(nodes) for node in nodes: node['pub'] = pub_id return True
[ "def", "enter", "(", "self", ",", "pub_id", ",", "*", "nodes", ")", ":", "try", ":", "pub", "=", "self", "[", "'pubs'", "]", "[", "pub_id", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Pub {} is not available'", ".", "format", "(", "pub_id", ")", ")", "if", "not", "pub", "[", "'open'", "]", "or", "(", "pub", "[", "'capacity'", "]", "<", "(", "len", "(", "nodes", ")", "+", "pub", "[", "'occupancy'", "]", ")", ")", ":", "return", "False", "pub", "[", "'occupancy'", "]", "+=", "len", "(", "nodes", ")", "for", "node", "in", "nodes", ":", "node", "[", "'pub'", "]", "=", "pub_id", "return", "True" ]
Agents will try to enter. The pub checks if it is possible
[ "Agents", "will", "try", "to", "enter", ".", "The", "pub", "checks", "if", "it", "is", "possible" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L25-L36
train
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
CityPubs.exit
def exit(self, pub_id, *node_ids): '''Agents will notify the pub they want to leave''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) for node_id in node_ids: node = self.get_agent(node_id) if pub_id == node['pub']: del node['pub'] pub['occupancy'] -= 1
python
def exit(self, pub_id, *node_ids): '''Agents will notify the pub they want to leave''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) for node_id in node_ids: node = self.get_agent(node_id) if pub_id == node['pub']: del node['pub'] pub['occupancy'] -= 1
[ "def", "exit", "(", "self", ",", "pub_id", ",", "*", "node_ids", ")", ":", "try", ":", "pub", "=", "self", "[", "'pubs'", "]", "[", "pub_id", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Pub {} is not available'", ".", "format", "(", "pub_id", ")", ")", "for", "node_id", "in", "node_ids", ":", "node", "=", "self", ".", "get_agent", "(", "node_id", ")", "if", "pub_id", "==", "node", "[", "'pub'", "]", ":", "del", "node", "[", "'pub'", "]", "pub", "[", "'occupancy'", "]", "-=", "1" ]
Agents will notify the pub they want to leave
[ "Agents", "will", "notify", "the", "pub", "they", "want", "to", "leave" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L43-L53
train
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
Patron.looking_for_friends
def looking_for_friends(self): '''Look for friends to drink with''' self.info('I am looking for friends') available_friends = list(self.get_agents(drunk=False, pub=None, state_id=self.looking_for_friends.id)) if not available_friends: self.info('Life sucks and I\'m alone!') return self.at_home befriended = self.try_friends(available_friends) if befriended: return self.looking_for_pub
python
def looking_for_friends(self): '''Look for friends to drink with''' self.info('I am looking for friends') available_friends = list(self.get_agents(drunk=False, pub=None, state_id=self.looking_for_friends.id)) if not available_friends: self.info('Life sucks and I\'m alone!') return self.at_home befriended = self.try_friends(available_friends) if befriended: return self.looking_for_pub
[ "def", "looking_for_friends", "(", "self", ")", ":", "self", ".", "info", "(", "'I am looking for friends'", ")", "available_friends", "=", "list", "(", "self", ".", "get_agents", "(", "drunk", "=", "False", ",", "pub", "=", "None", ",", "state_id", "=", "self", ".", "looking_for_friends", ".", "id", ")", ")", "if", "not", "available_friends", ":", "self", ".", "info", "(", "'Life sucks and I\\'m alone!'", ")", "return", "self", ".", "at_home", "befriended", "=", "self", ".", "try_friends", "(", "available_friends", ")", "if", "befriended", ":", "return", "self", ".", "looking_for_pub" ]
Look for friends to drink with
[ "Look", "for", "friends", "to", "drink", "with" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L73-L84
train
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
Patron.looking_for_pub
def looking_for_pub(self): '''Look for a pub that accepts me and my friends''' if self['pub'] != None: return self.sober_in_pub self.debug('I am looking for a pub') group = list(self.get_neighboring_agents()) for pub in self.env.available_pubs(): self.debug('We\'re trying to get into {}: total: {}'.format(pub, len(group))) if self.env.enter(pub, self, *group): self.info('We\'re all {} getting in {}!'.format(len(group), pub)) return self.sober_in_pub
python
def looking_for_pub(self): '''Look for a pub that accepts me and my friends''' if self['pub'] != None: return self.sober_in_pub self.debug('I am looking for a pub') group = list(self.get_neighboring_agents()) for pub in self.env.available_pubs(): self.debug('We\'re trying to get into {}: total: {}'.format(pub, len(group))) if self.env.enter(pub, self, *group): self.info('We\'re all {} getting in {}!'.format(len(group), pub)) return self.sober_in_pub
[ "def", "looking_for_pub", "(", "self", ")", ":", "if", "self", "[", "'pub'", "]", "!=", "None", ":", "return", "self", ".", "sober_in_pub", "self", ".", "debug", "(", "'I am looking for a pub'", ")", "group", "=", "list", "(", "self", ".", "get_neighboring_agents", "(", ")", ")", "for", "pub", "in", "self", ".", "env", ".", "available_pubs", "(", ")", ":", "self", ".", "debug", "(", "'We\\'re trying to get into {}: total: {}'", ".", "format", "(", "pub", ",", "len", "(", "group", ")", ")", ")", "if", "self", ".", "env", ".", "enter", "(", "pub", ",", "self", ",", "*", "group", ")", ":", "self", ".", "info", "(", "'We\\'re all {} getting in {}!'", ".", "format", "(", "len", "(", "group", ")", ",", "pub", ")", ")", "return", "self", ".", "sober_in_pub" ]
Look for a pub that accepts me and my friends
[ "Look", "for", "a", "pub", "that", "accepts", "me", "and", "my", "friends" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L87-L97
train
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
Patron.befriend
def befriend(self, other_agent, force=False): ''' Try to become friends with another agent. The chances of success depend on both agents' openness. ''' if force or self['openness'] > random(): self.env.add_edge(self, other_agent) self.info('Made some friend {}'.format(other_agent)) return True return False
python
def befriend(self, other_agent, force=False): ''' Try to become friends with another agent. The chances of success depend on both agents' openness. ''' if force or self['openness'] > random(): self.env.add_edge(self, other_agent) self.info('Made some friend {}'.format(other_agent)) return True return False
[ "def", "befriend", "(", "self", ",", "other_agent", ",", "force", "=", "False", ")", ":", "if", "force", "or", "self", "[", "'openness'", "]", ">", "random", "(", ")", ":", "self", ".", "env", ".", "add_edge", "(", "self", ",", "other_agent", ")", "self", ".", "info", "(", "'Made some friend {}'", ".", "format", "(", "other_agent", ")", ")", "return", "True", "return", "False" ]
Try to become friends with another agent. The chances of success depend on both agents' openness.
[ "Try", "to", "become", "friends", "with", "another", "agent", ".", "The", "chances", "of", "success", "depend", "on", "both", "agents", "openness", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L125-L134
train
gsi-upm/soil
examples/pubcrawl/pubcrawl.py
Patron.try_friends
def try_friends(self, others): ''' Look for random agents around me and try to befriend them''' befriended = False k = int(10*self['openness']) shuffle(others) for friend in islice(others, k): # random.choice >= 3.7 if friend == self: continue if friend.befriend(self): self.befriend(friend, force=True) self.debug('Hooray! new friend: {}'.format(friend.id)) befriended = True else: self.debug('{} does not want to be friends'.format(friend.id)) return befriended
python
def try_friends(self, others): ''' Look for random agents around me and try to befriend them''' befriended = False k = int(10*self['openness']) shuffle(others) for friend in islice(others, k): # random.choice >= 3.7 if friend == self: continue if friend.befriend(self): self.befriend(friend, force=True) self.debug('Hooray! new friend: {}'.format(friend.id)) befriended = True else: self.debug('{} does not want to be friends'.format(friend.id)) return befriended
[ "def", "try_friends", "(", "self", ",", "others", ")", ":", "befriended", "=", "False", "k", "=", "int", "(", "10", "*", "self", "[", "'openness'", "]", ")", "shuffle", "(", "others", ")", "for", "friend", "in", "islice", "(", "others", ",", "k", ")", ":", "if", "friend", "==", "self", ":", "continue", "if", "friend", ".", "befriend", "(", "self", ")", ":", "self", ".", "befriend", "(", "friend", ",", "force", "=", "True", ")", "self", ".", "debug", "(", "'Hooray! new friend: {}'", ".", "format", "(", "friend", ".", "id", ")", ")", "befriended", "=", "True", "else", ":", "self", ".", "debug", "(", "'{} does not want to be friends'", ".", "format", "(", "friend", ".", "id", ")", ")", "return", "befriended" ]
Look for random agents around me and try to befriend them
[ "Look", "for", "random", "agents", "around", "me", "and", "try", "to", "befriend", "them" ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L136-L150
train
byu-dml/metalearn
metalearn/metafeatures/common_operations.py
profile_distribution
def profile_distribution(data): """ Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector Parameters ---------- data: array of real values Returns ------- features = dictionary containing the min, max, mean, and standard deviation """ if len(data) == 0: return (data, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan) else: ddof = 1 if len(data) > 1 else 0 dist_mean = np.mean(data) dist_stdev = np.std(data, ddof=ddof) dist_min, dist_quartile1, dist_quartile2, dist_quartile3, dist_max = np.percentile(data, [0,25,50,75,100]) dist_skew = skew(data) dist_kurtosis = kurtosis(data) return (data, dist_mean, dist_stdev, dist_skew, dist_kurtosis, dist_min, dist_quartile1, dist_quartile2, dist_quartile3, dist_max)
python
def profile_distribution(data): """ Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector Parameters ---------- data: array of real values Returns ------- features = dictionary containing the min, max, mean, and standard deviation """ if len(data) == 0: return (data, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan) else: ddof = 1 if len(data) > 1 else 0 dist_mean = np.mean(data) dist_stdev = np.std(data, ddof=ddof) dist_min, dist_quartile1, dist_quartile2, dist_quartile3, dist_max = np.percentile(data, [0,25,50,75,100]) dist_skew = skew(data) dist_kurtosis = kurtosis(data) return (data, dist_mean, dist_stdev, dist_skew, dist_kurtosis, dist_min, dist_quartile1, dist_quartile2, dist_quartile3, dist_max)
[ "def", "profile_distribution", "(", "data", ")", ":", "if", "len", "(", "data", ")", "==", "0", ":", "return", "(", "data", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", ")", "else", ":", "ddof", "=", "1", "if", "len", "(", "data", ")", ">", "1", "else", "0", "dist_mean", "=", "np", ".", "mean", "(", "data", ")", "dist_stdev", "=", "np", ".", "std", "(", "data", ",", "ddof", "=", "ddof", ")", "dist_min", ",", "dist_quartile1", ",", "dist_quartile2", ",", "dist_quartile3", ",", "dist_max", "=", "np", ".", "percentile", "(", "data", ",", "[", "0", ",", "25", ",", "50", ",", "75", ",", "100", "]", ")", "dist_skew", "=", "skew", "(", "data", ")", "dist_kurtosis", "=", "kurtosis", "(", "data", ")", "return", "(", "data", ",", "dist_mean", ",", "dist_stdev", ",", "dist_skew", ",", "dist_kurtosis", ",", "dist_min", ",", "dist_quartile1", ",", "dist_quartile2", ",", "dist_quartile3", ",", "dist_max", ")" ]
Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector Parameters ---------- data: array of real values Returns ------- features = dictionary containing the min, max, mean, and standard deviation
[ "Compute", "the", "mean", "standard", "deviation", "min", "quartile1", "quartile2", "quartile3", "and", "max", "of", "a", "vector" ]
0a3b7cb339250144f6d2f70977f74fe457cecee3
https://github.com/byu-dml/metalearn/blob/0a3b7cb339250144f6d2f70977f74fe457cecee3/metalearn/metafeatures/common_operations.py#L6-L27
train
kensho-technologies/grift
grift/property_types.py
DictType.to_native
def to_native(self, value): """Return the value as a dict, raising error if conversion to dict is not possible""" if isinstance(value, dict): return value elif isinstance(value, six.string_types): native_value = json.loads(value) if isinstance(native_value, dict): return native_value else: raise ConversionError(u'Cannot load value as a dict: {}'.format(value))
python
def to_native(self, value): """Return the value as a dict, raising error if conversion to dict is not possible""" if isinstance(value, dict): return value elif isinstance(value, six.string_types): native_value = json.loads(value) if isinstance(native_value, dict): return native_value else: raise ConversionError(u'Cannot load value as a dict: {}'.format(value))
[ "def", "to_native", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "native_value", "=", "json", ".", "loads", "(", "value", ")", "if", "isinstance", "(", "native_value", ",", "dict", ")", ":", "return", "native_value", "else", ":", "raise", "ConversionError", "(", "u'Cannot load value as a dict: {}'", ".", "format", "(", "value", ")", ")" ]
Return the value as a dict, raising error if conversion to dict is not possible
[ "Return", "the", "value", "as", "a", "dict", "raising", "error", "if", "conversion", "to", "dict", "is", "not", "possible" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L14-L23
train
kensho-technologies/grift
grift/property_types.py
ListType.to_native
def to_native(self, value): """Load a value as a list, converting items if necessary""" if isinstance(value, six.string_types): value_list = value.split(self.string_delim) else: value_list = value to_native = self.member_type.to_native if self.member_type is not None else lambda x: x return [to_native(item) for item in value_list]
python
def to_native(self, value): """Load a value as a list, converting items if necessary""" if isinstance(value, six.string_types): value_list = value.split(self.string_delim) else: value_list = value to_native = self.member_type.to_native if self.member_type is not None else lambda x: x return [to_native(item) for item in value_list]
[ "def", "to_native", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value_list", "=", "value", ".", "split", "(", "self", ".", "string_delim", ")", "else", ":", "value_list", "=", "value", "to_native", "=", "self", ".", "member_type", ".", "to_native", "if", "self", ".", "member_type", "is", "not", "None", "else", "lambda", "x", ":", "x", "return", "[", "to_native", "(", "item", ")", "for", "item", "in", "value_list", "]" ]
Load a value as a list, converting items if necessary
[ "Load", "a", "value", "as", "a", "list", "converting", "items", "if", "necessary" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L47-L55
train
kensho-technologies/grift
grift/property_types.py
ListType.validate_member_type
def validate_member_type(self, value): """Validate each member of the list, if member_type exists""" if self.member_type: for item in value: self.member_type.validate(item)
python
def validate_member_type(self, value): """Validate each member of the list, if member_type exists""" if self.member_type: for item in value: self.member_type.validate(item)
[ "def", "validate_member_type", "(", "self", ",", "value", ")", ":", "if", "self", ".", "member_type", ":", "for", "item", "in", "value", ":", "self", ".", "member_type", ".", "validate", "(", "item", ")" ]
Validate each member of the list, if member_type exists
[ "Validate", "each", "member", "of", "the", "list", "if", "member_type", "exists" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L57-L61
train
kensho-technologies/grift
grift/property_types.py
ListType.validate_length
def validate_length(self, value): """Validate the length of value, if min_length or max_length was specified""" list_len = len(value) if value else 0 if self.max_length is not None and list_len > self.max_length: raise ValidationError( u'List has {} values; max length is {}'.format(list_len, self.max_length)) if self.min_length is not None and list_len < self.min_length: raise ValidationError( u'List has {} values; min length is {}'.format(list_len, self.min_length))
python
def validate_length(self, value): """Validate the length of value, if min_length or max_length was specified""" list_len = len(value) if value else 0 if self.max_length is not None and list_len > self.max_length: raise ValidationError( u'List has {} values; max length is {}'.format(list_len, self.max_length)) if self.min_length is not None and list_len < self.min_length: raise ValidationError( u'List has {} values; min length is {}'.format(list_len, self.min_length))
[ "def", "validate_length", "(", "self", ",", "value", ")", ":", "list_len", "=", "len", "(", "value", ")", "if", "value", "else", "0", "if", "self", ".", "max_length", "is", "not", "None", "and", "list_len", ">", "self", ".", "max_length", ":", "raise", "ValidationError", "(", "u'List has {} values; max length is {}'", ".", "format", "(", "list_len", ",", "self", ".", "max_length", ")", ")", "if", "self", ".", "min_length", "is", "not", "None", "and", "list_len", "<", "self", ".", "min_length", ":", "raise", "ValidationError", "(", "u'List has {} values; min length is {}'", ".", "format", "(", "list_len", ",", "self", ".", "min_length", ")", ")" ]
Validate the length of value, if min_length or max_length was specified
[ "Validate", "the", "length", "of", "value", "if", "min_length", "or", "max_length", "was", "specified" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L63-L73
train
kensho-technologies/grift
grift/property_types.py
NetworkType.validate_resource
def validate_resource(self, value): """Validate the network resource with exponential backoff""" def do_backoff(*args, **kwargs): """Call self._test_connection with exponential backoff, for self._max_tries attempts""" attempts = 0 while True: try: self._test_connection(*args, **kwargs) break except ValidationError: wait_secs = min(self._max_wait, 2 ** attempts) attempts += 1 if attempts < self._max_tries: time.sleep(wait_secs) else: raise do_backoff(value)
python
def validate_resource(self, value): """Validate the network resource with exponential backoff""" def do_backoff(*args, **kwargs): """Call self._test_connection with exponential backoff, for self._max_tries attempts""" attempts = 0 while True: try: self._test_connection(*args, **kwargs) break except ValidationError: wait_secs = min(self._max_wait, 2 ** attempts) attempts += 1 if attempts < self._max_tries: time.sleep(wait_secs) else: raise do_backoff(value)
[ "def", "validate_resource", "(", "self", ",", "value", ")", ":", "def", "do_backoff", "(", "*", "args", ",", "**", "kwargs", ")", ":", "attempts", "=", "0", "while", "True", ":", "try", ":", "self", ".", "_test_connection", "(", "*", "args", ",", "**", "kwargs", ")", "break", "except", "ValidationError", ":", "wait_secs", "=", "min", "(", "self", ".", "_max_wait", ",", "2", "**", "attempts", ")", "attempts", "+=", "1", "if", "attempts", "<", "self", ".", "_max_tries", ":", "time", ".", "sleep", "(", "wait_secs", ")", "else", ":", "raise", "do_backoff", "(", "value", ")" ]
Validate the network resource with exponential backoff
[ "Validate", "the", "network", "resource", "with", "exponential", "backoff" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L101-L119
train
byu-dml/metalearn
metalearn/metafeatures/metafeatures.py
Metafeatures.list_metafeatures
def list_metafeatures(cls, group="all"): """ Returns a list of metafeatures computable by the Metafeatures class. """ # todo make group for intractable metafeatures for wide datasets or # datasets with high cardinality categorical columns: # PredPCA1, PredPCA2, PredPCA3, PredEigen1, PredEigen2, PredEigen3, # PredDet, kNN1NErrRate, kNN1NKappa, LinearDiscriminantAnalysisKappa, # LinearDiscriminantAnalysisErrRate if group == "all": return copy.deepcopy(cls.IDS) elif group == "landmarking": return list(filter( lambda mf_id: "ErrRate" in mf_id or "Kappa" in mf_id, cls.IDS )) elif group == "target_dependent": return list(filter( cls._resource_is_target_dependent, cls.IDS )) else: raise ValueError(f"Unknown group {group}")
python
def list_metafeatures(cls, group="all"): """ Returns a list of metafeatures computable by the Metafeatures class. """ # todo make group for intractable metafeatures for wide datasets or # datasets with high cardinality categorical columns: # PredPCA1, PredPCA2, PredPCA3, PredEigen1, PredEigen2, PredEigen3, # PredDet, kNN1NErrRate, kNN1NKappa, LinearDiscriminantAnalysisKappa, # LinearDiscriminantAnalysisErrRate if group == "all": return copy.deepcopy(cls.IDS) elif group == "landmarking": return list(filter( lambda mf_id: "ErrRate" in mf_id or "Kappa" in mf_id, cls.IDS )) elif group == "target_dependent": return list(filter( cls._resource_is_target_dependent, cls.IDS )) else: raise ValueError(f"Unknown group {group}")
[ "def", "list_metafeatures", "(", "cls", ",", "group", "=", "\"all\"", ")", ":", "if", "group", "==", "\"all\"", ":", "return", "copy", ".", "deepcopy", "(", "cls", ".", "IDS", ")", "elif", "group", "==", "\"landmarking\"", ":", "return", "list", "(", "filter", "(", "lambda", "mf_id", ":", "\"ErrRate\"", "in", "mf_id", "or", "\"Kappa\"", "in", "mf_id", ",", "cls", ".", "IDS", ")", ")", "elif", "group", "==", "\"target_dependent\"", ":", "return", "list", "(", "filter", "(", "cls", ".", "_resource_is_target_dependent", ",", "cls", ".", "IDS", ")", ")", "else", ":", "raise", "ValueError", "(", "f\"Unknown group {group}\"", ")" ]
Returns a list of metafeatures computable by the Metafeatures class.
[ "Returns", "a", "list", "of", "metafeatures", "computable", "by", "the", "Metafeatures", "class", "." ]
0a3b7cb339250144f6d2f70977f74fe457cecee3
https://github.com/byu-dml/metalearn/blob/0a3b7cb339250144f6d2f70977f74fe457cecee3/metalearn/metafeatures/metafeatures.py#L49-L69
train
byu-dml/metalearn
metalearn/metafeatures/metafeatures.py
Metafeatures._sample_rows
def _sample_rows(self, X, Y, sample_shape, seed): """ Stratified uniform sampling of rows, according to the classes in Y. Ensures there are enough samples from each class in Y for cross validation. """ if sample_shape[0] is None or X.shape[0] <= sample_shape[0]: X_sample, Y_sample = X, Y elif Y is None: np.random.seed(seed) row_indices = np.random.choice( X.shape[0], size=sample_shape[0], replace=False ) X_sample, Y_sample = X.iloc[row_indices], Y else: drop_size = X.shape[0] - sample_shape[0] sample_size = sample_shape[0] sss = StratifiedShuffleSplit( n_splits=2, test_size=drop_size, train_size=sample_size, random_state=seed ) row_indices, _ = next(sss.split(X, Y)) X_sample, Y_sample = X.iloc[row_indices], Y.iloc[row_indices] return (X_sample, Y_sample)
python
def _sample_rows(self, X, Y, sample_shape, seed): """ Stratified uniform sampling of rows, according to the classes in Y. Ensures there are enough samples from each class in Y for cross validation. """ if sample_shape[0] is None or X.shape[0] <= sample_shape[0]: X_sample, Y_sample = X, Y elif Y is None: np.random.seed(seed) row_indices = np.random.choice( X.shape[0], size=sample_shape[0], replace=False ) X_sample, Y_sample = X.iloc[row_indices], Y else: drop_size = X.shape[0] - sample_shape[0] sample_size = sample_shape[0] sss = StratifiedShuffleSplit( n_splits=2, test_size=drop_size, train_size=sample_size, random_state=seed ) row_indices, _ = next(sss.split(X, Y)) X_sample, Y_sample = X.iloc[row_indices], Y.iloc[row_indices] return (X_sample, Y_sample)
[ "def", "_sample_rows", "(", "self", ",", "X", ",", "Y", ",", "sample_shape", ",", "seed", ")", ":", "if", "sample_shape", "[", "0", "]", "is", "None", "or", "X", ".", "shape", "[", "0", "]", "<=", "sample_shape", "[", "0", "]", ":", "X_sample", ",", "Y_sample", "=", "X", ",", "Y", "elif", "Y", "is", "None", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "row_indices", "=", "np", ".", "random", ".", "choice", "(", "X", ".", "shape", "[", "0", "]", ",", "size", "=", "sample_shape", "[", "0", "]", ",", "replace", "=", "False", ")", "X_sample", ",", "Y_sample", "=", "X", ".", "iloc", "[", "row_indices", "]", ",", "Y", "else", ":", "drop_size", "=", "X", ".", "shape", "[", "0", "]", "-", "sample_shape", "[", "0", "]", "sample_size", "=", "sample_shape", "[", "0", "]", "sss", "=", "StratifiedShuffleSplit", "(", "n_splits", "=", "2", ",", "test_size", "=", "drop_size", ",", "train_size", "=", "sample_size", ",", "random_state", "=", "seed", ")", "row_indices", ",", "_", "=", "next", "(", "sss", ".", "split", "(", "X", ",", "Y", ")", ")", "X_sample", ",", "Y_sample", "=", "X", ".", "iloc", "[", "row_indices", "]", ",", "Y", ".", "iloc", "[", "row_indices", "]", "return", "(", "X_sample", ",", "Y_sample", ")" ]
Stratified uniform sampling of rows, according to the classes in Y. Ensures there are enough samples from each class in Y for cross validation.
[ "Stratified", "uniform", "sampling", "of", "rows", "according", "to", "the", "classes", "in", "Y", ".", "Ensures", "there", "are", "enough", "samples", "from", "each", "class", "in", "Y", "for", "cross", "validation", "." ]
0a3b7cb339250144f6d2f70977f74fe457cecee3
https://github.com/byu-dml/metalearn/blob/0a3b7cb339250144f6d2f70977f74fe457cecee3/metalearn/metafeatures/metafeatures.py#L466-L488
train
kensho-technologies/grift
grift/loaders.py
VaultLoader._fetch_secrets
def _fetch_secrets(vault_url, path, token): """Read data from the vault path""" url = _url_joiner(vault_url, 'v1', path) resp = requests.get(url, headers=VaultLoader._get_headers(token)) resp.raise_for_status() data = resp.json() if data.get('errors'): raise VaultException(u'Error fetching Vault secrets from path {}: {}' .format(path, data['errors'])) return data['data']
python
def _fetch_secrets(vault_url, path, token): """Read data from the vault path""" url = _url_joiner(vault_url, 'v1', path) resp = requests.get(url, headers=VaultLoader._get_headers(token)) resp.raise_for_status() data = resp.json() if data.get('errors'): raise VaultException(u'Error fetching Vault secrets from path {}: {}' .format(path, data['errors'])) return data['data']
[ "def", "_fetch_secrets", "(", "vault_url", ",", "path", ",", "token", ")", ":", "url", "=", "_url_joiner", "(", "vault_url", ",", "'v1'", ",", "path", ")", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "VaultLoader", ".", "_get_headers", "(", "token", ")", ")", "resp", ".", "raise_for_status", "(", ")", "data", "=", "resp", ".", "json", "(", ")", "if", "data", ".", "get", "(", "'errors'", ")", ":", "raise", "VaultException", "(", "u'Error fetching Vault secrets from path {}: {}'", ".", "format", "(", "path", ",", "data", "[", "'errors'", "]", ")", ")", "return", "data", "[", "'data'", "]" ]
Read data from the vault path
[ "Read", "data", "from", "the", "vault", "path" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L140-L149
train
kensho-technologies/grift
grift/loaders.py
VaultLoader._fetch_app_role_token
def _fetch_app_role_token(vault_url, role_id, secret_id): """Get a Vault token, using the RoleID and SecretID""" url = _url_joiner(vault_url, 'v1/auth/approle/login') resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id}) resp.raise_for_status() data = resp.json() if data.get('errors'): raise VaultException(u'Error fetching Vault token: {}'.format(data['errors'])) return data['auth']['client_token']
python
def _fetch_app_role_token(vault_url, role_id, secret_id): """Get a Vault token, using the RoleID and SecretID""" url = _url_joiner(vault_url, 'v1/auth/approle/login') resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id}) resp.raise_for_status() data = resp.json() if data.get('errors'): raise VaultException(u'Error fetching Vault token: {}'.format(data['errors'])) return data['auth']['client_token']
[ "def", "_fetch_app_role_token", "(", "vault_url", ",", "role_id", ",", "secret_id", ")", ":", "url", "=", "_url_joiner", "(", "vault_url", ",", "'v1/auth/approle/login'", ")", "resp", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "{", "'role_id'", ":", "role_id", ",", "'secret_id'", ":", "secret_id", "}", ")", "resp", ".", "raise_for_status", "(", ")", "data", "=", "resp", ".", "json", "(", ")", "if", "data", ".", "get", "(", "'errors'", ")", ":", "raise", "VaultException", "(", "u'Error fetching Vault token: {}'", ".", "format", "(", "data", "[", "'errors'", "]", ")", ")", "return", "data", "[", "'auth'", "]", "[", "'client_token'", "]" ]
Get a Vault token, using the RoleID and SecretID
[ "Get", "a", "Vault", "token", "using", "the", "RoleID", "and", "SecretID" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L152-L160
train
kensho-technologies/grift
grift/loaders.py
VaultLoader.reload
def reload(self): """Reread secrets from the vault path""" self._source = self._fetch_secrets(self._vault_url, self._path, self._token)
python
def reload(self): """Reread secrets from the vault path""" self._source = self._fetch_secrets(self._vault_url, self._path, self._token)
[ "def", "reload", "(", "self", ")", ":", "self", ".", "_source", "=", "self", ".", "_fetch_secrets", "(", "self", ".", "_vault_url", ",", "self", ".", "_path", ",", "self", ".", "_token", ")" ]
Reread secrets from the vault path
[ "Reread", "secrets", "from", "the", "vault", "path" ]
b8767d1604c1a0a25eace6cdd04b53b57afa9757
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/loaders.py#L162-L164
train
inveniosoftware/invenio-search-ui
invenio_search_ui/views.py
sorted_options
def sorted_options(sort_options): """Sort sort options for display. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A dictionary with sorting options for Invenio-Search-JS. """ return [ { 'title': v['title'], 'value': ('-{0}'.format(k) if v.get('default_order', 'asc') == 'desc' else k), } for k, v in sorted(sort_options.items(), key=lambda x: x[1].get('order', 0)) ]
python
def sorted_options(sort_options): """Sort sort options for display. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A dictionary with sorting options for Invenio-Search-JS. """ return [ { 'title': v['title'], 'value': ('-{0}'.format(k) if v.get('default_order', 'asc') == 'desc' else k), } for k, v in sorted(sort_options.items(), key=lambda x: x[1].get('order', 0)) ]
[ "def", "sorted_options", "(", "sort_options", ")", ":", "return", "[", "{", "'title'", ":", "v", "[", "'title'", "]", ",", "'value'", ":", "(", "'-{0}'", ".", "format", "(", "k", ")", "if", "v", ".", "get", "(", "'default_order'", ",", "'asc'", ")", "==", "'desc'", "else", "k", ")", ",", "}", "for", "k", ",", "v", "in", "sorted", "(", "sort_options", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ".", "get", "(", "'order'", ",", "0", ")", ")", "]" ]
Sort sort options for display. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A dictionary with sorting options for Invenio-Search-JS.
[ "Sort", "sort", "options", "for", "display", "." ]
4b61737f938cbfdc1aad6602a73f3a24d53b3312
https://github.com/inveniosoftware/invenio-search-ui/blob/4b61737f938cbfdc1aad6602a73f3a24d53b3312/invenio_search_ui/views.py#L29-L44
train
bitlabstudio/django-libs
django_libs/utils/converter.py
html_to_plain_text
def html_to_plain_text(html): """Converts html code into formatted plain text.""" # Use BeautifulSoup to normalize the html soup = BeautifulSoup(html, "html.parser") # Init the parser parser = HTML2PlainParser() parser.feed(str(soup.encode('utf-8'))) # Strip the end of the plain text result = parser.text.rstrip() # Add footnotes if parser.links: result += '\n\n' for link in parser.links: result += '[{}]: {}\n'.format(link[0], link[1]) return result
python
def html_to_plain_text(html): """Converts html code into formatted plain text.""" # Use BeautifulSoup to normalize the html soup = BeautifulSoup(html, "html.parser") # Init the parser parser = HTML2PlainParser() parser.feed(str(soup.encode('utf-8'))) # Strip the end of the plain text result = parser.text.rstrip() # Add footnotes if parser.links: result += '\n\n' for link in parser.links: result += '[{}]: {}\n'.format(link[0], link[1]) return result
[ "def", "html_to_plain_text", "(", "html", ")", ":", "soup", "=", "BeautifulSoup", "(", "html", ",", "\"html.parser\"", ")", "parser", "=", "HTML2PlainParser", "(", ")", "parser", ".", "feed", "(", "str", "(", "soup", ".", "encode", "(", "'utf-8'", ")", ")", ")", "result", "=", "parser", ".", "text", ".", "rstrip", "(", ")", "if", "parser", ".", "links", ":", "result", "+=", "'\\n\\n'", "for", "link", "in", "parser", ".", "links", ":", "result", "+=", "'[{}]: {}\\n'", ".", "format", "(", "link", "[", "0", "]", ",", "link", "[", "1", "]", ")", "return", "result" ]
Converts html code into formatted plain text.
[ "Converts", "html", "code", "into", "formatted", "plain", "text", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/converter.py#L112-L126
train
bitlabstudio/django-libs
django_libs/utils/converter.py
HTML2PlainParser.handle_data
def handle_data(self, data): """Handles data between tags.""" # Only proceed with unignored elements if self.lasttag not in self.ignored_elements: # Remove any predefined linebreaks text = data.replace('\n', '') # If there's some text left, proceed! if text: if self.lasttag == 'li': # Use a special prefix for list elements self.text += ' * ' self.text += text if self.lasttag in self.newline_after_elements: # Add a linebreak at the end of the content self.text += '\n'
python
def handle_data(self, data): """Handles data between tags.""" # Only proceed with unignored elements if self.lasttag not in self.ignored_elements: # Remove any predefined linebreaks text = data.replace('\n', '') # If there's some text left, proceed! if text: if self.lasttag == 'li': # Use a special prefix for list elements self.text += ' * ' self.text += text if self.lasttag in self.newline_after_elements: # Add a linebreak at the end of the content self.text += '\n'
[ "def", "handle_data", "(", "self", ",", "data", ")", ":", "if", "self", ".", "lasttag", "not", "in", "self", ".", "ignored_elements", ":", "text", "=", "data", ".", "replace", "(", "'\\n'", ",", "''", ")", "if", "text", ":", "if", "self", ".", "lasttag", "==", "'li'", ":", "self", ".", "text", "+=", "' * '", "self", ".", "text", "+=", "text", "if", "self", ".", "lasttag", "in", "self", ".", "newline_after_elements", ":", "self", ".", "text", "+=", "'\\n'" ]
Handles data between tags.
[ "Handles", "data", "between", "tags", "." ]
2c5376cda084bf16edea540e0f6999f1d844afd0
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/converter.py#L70-L84
train
flavio/scsgate
scsgate/reactor.py
Reactor.run
def run(self): """ Starts the thread """ task = None monitor_task = MonitorTask( notification_endpoint=self._handle_message) while True: if self._terminate: self._logger.info("scsgate.Reactor exiting") self._connection.close() break try: task = self._request_queue.get_nowait() self._logger.debug("scsgate.Reactor: got task {}".format(task)) except queue.Empty: task = monitor_task try: task.execute(connection=self._connection) except ExecutionError as err: self._logger.error(err)
python
def run(self): """ Starts the thread """ task = None monitor_task = MonitorTask( notification_endpoint=self._handle_message) while True: if self._terminate: self._logger.info("scsgate.Reactor exiting") self._connection.close() break try: task = self._request_queue.get_nowait() self._logger.debug("scsgate.Reactor: got task {}".format(task)) except queue.Empty: task = monitor_task try: task.execute(connection=self._connection) except ExecutionError as err: self._logger.error(err)
[ "def", "run", "(", "self", ")", ":", "task", "=", "None", "monitor_task", "=", "MonitorTask", "(", "notification_endpoint", "=", "self", ".", "_handle_message", ")", "while", "True", ":", "if", "self", ".", "_terminate", ":", "self", ".", "_logger", ".", "info", "(", "\"scsgate.Reactor exiting\"", ")", "self", ".", "_connection", ".", "close", "(", ")", "break", "try", ":", "task", "=", "self", ".", "_request_queue", ".", "get_nowait", "(", ")", "self", ".", "_logger", ".", "debug", "(", "\"scsgate.Reactor: got task {}\"", ".", "format", "(", "task", ")", ")", "except", "queue", ".", "Empty", ":", "task", "=", "monitor_task", "try", ":", "task", ".", "execute", "(", "connection", "=", "self", ".", "_connection", ")", "except", "ExecutionError", "as", "err", ":", "self", ".", "_logger", ".", "error", "(", "err", ")" ]
Starts the thread
[ "Starts", "the", "thread" ]
aad1d181eef4714ab475f4ff7fcfac4a6425fbb4
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/reactor.py#L31-L52
train
gsi-upm/soil
examples/custom_generator/mymodule.py
mygenerator
def mygenerator(n=5, n_edges=5): ''' Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops. ''' G = nx.Graph() for i in range(n): G.add_node(i) for i in range(n_edges): nodes = list(G.nodes) n_in = choice(nodes) nodes.remove(n_in) # Avoid loops n_out = choice(nodes) G.add_edge(n_in, n_out) return G
python
def mygenerator(n=5, n_edges=5): ''' Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops. ''' G = nx.Graph() for i in range(n): G.add_node(i) for i in range(n_edges): nodes = list(G.nodes) n_in = choice(nodes) nodes.remove(n_in) # Avoid loops n_out = choice(nodes) G.add_edge(n_in, n_out) return G
[ "def", "mygenerator", "(", "n", "=", "5", ",", "n_edges", "=", "5", ")", ":", "G", "=", "nx", ".", "Graph", "(", ")", "for", "i", "in", "range", "(", "n", ")", ":", "G", ".", "add_node", "(", "i", ")", "for", "i", "in", "range", "(", "n_edges", ")", ":", "nodes", "=", "list", "(", "G", ".", "nodes", ")", "n_in", "=", "choice", "(", "nodes", ")", "nodes", ".", "remove", "(", "n_in", ")", "n_out", "=", "choice", "(", "nodes", ")", "G", ".", "add_edge", "(", "n_in", ",", "n_out", ")", "return", "G" ]
Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops.
[ "Just", "a", "simple", "generator", "that", "creates", "a", "network", "with", "n", "nodes", "and", "n_edges", "edges", ".", "Edges", "are", "assigned", "randomly", "only", "avoiding", "self", "loops", "." ]
a3ea434f237f039c3cadbc2e0a83ae626d77b818
https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/custom_generator/mymodule.py#L5-L21
train
dbarsam/python-vsgen
vsgen/project.py
VSGProject.insert_files
def insert_files(self, rootpath, directoryInFilter=None, directoryExFilter=None, compileInFilter=None, compileExFilter=None, contentInFilter=None, contentExFilter=None): """ Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters. :param str rootpath: The absolute path to the root directory. :param list directoryInFilter: A list of fnmatch expressions to match directories to be included. A `None` value will default to :attr:`DirectoryInFilter`. :param list directoryExFilter: A list of fnmatch expressions to match directories to be excluded. A `None` value will default to :attr:`DirectoryExFilter`. :param list compileInFilter: A list of fnmatch expressions to match compile files to be included. A `None` value will default to :attr:`CompileInFilter`. :param list compileExFilter: A list of fnmatch expressions to match compile files to be excludes. A `None` value will default to :attr:`CompileExFilter`. :param list contentInFilter: A list of fnmatch expressions to match content files to be includes. A `None` value will default to :attr:`ContentInFilter`. :param list contentExFilter: A list of fnmatch expressions to match content files to be excludes. A `None` value will default to :attr:`ContentExFilter`. """ # Overrides directoryInFilter = self.DirectoryInFilter if directoryInFilter is None else directoryInFilter directoryExFilter = self.DirectoryExFilter if directoryExFilter is None else directoryExFilter compileInFilter = self.CompileInFilter if compileInFilter is None else compileInFilter compileExFilter = self.CompileExFilter if compileExFilter is None else compileExFilter contentInFilter = self.ContentInFilter if contentInFilter is None else contentInFilter contentExFilter = self.ContentExFilter if contentExFilter is None else contentExFilter def filter(text, filters, explicit): """ Convience filter function :param text text: The target text. :param list filters: The collection of fnmatch expressions :param bool explicit: Flag denoting an the empty filter collection return match failure. """ if explicit: return any(fnmatch.fnmatch(text, f) for f in filters) return not filters or any(fnmatch.fnmatch(text, f) for f in filters) for root, dirnames, filenames in os.walk(rootpath): searchdir = os.path.normpath(os.path.normcase(root)) # If the root dir matches an excluded directory, stop any further searches if filter(searchdir, directoryExFilter, True): dirnames[:] = [] elif filter(searchdir, directoryInFilter, False): for filepath in [os.path.join(root, filename) for filename in filenames]: if filter(filepath, compileInFilter, False) and not filter(filepath, compileExFilter, True): self.CompileFiles.append(filepath) elif filter(filepath, contentInFilter, False) and not filter(filepath, contentExFilter, True): self.ContentFiles.append(filepath)
python
def insert_files(self, rootpath, directoryInFilter=None, directoryExFilter=None, compileInFilter=None, compileExFilter=None, contentInFilter=None, contentExFilter=None): """ Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters. :param str rootpath: The absolute path to the root directory. :param list directoryInFilter: A list of fnmatch expressions to match directories to be included. A `None` value will default to :attr:`DirectoryInFilter`. :param list directoryExFilter: A list of fnmatch expressions to match directories to be excluded. A `None` value will default to :attr:`DirectoryExFilter`. :param list compileInFilter: A list of fnmatch expressions to match compile files to be included. A `None` value will default to :attr:`CompileInFilter`. :param list compileExFilter: A list of fnmatch expressions to match compile files to be excludes. A `None` value will default to :attr:`CompileExFilter`. :param list contentInFilter: A list of fnmatch expressions to match content files to be includes. A `None` value will default to :attr:`ContentInFilter`. :param list contentExFilter: A list of fnmatch expressions to match content files to be excludes. A `None` value will default to :attr:`ContentExFilter`. """ # Overrides directoryInFilter = self.DirectoryInFilter if directoryInFilter is None else directoryInFilter directoryExFilter = self.DirectoryExFilter if directoryExFilter is None else directoryExFilter compileInFilter = self.CompileInFilter if compileInFilter is None else compileInFilter compileExFilter = self.CompileExFilter if compileExFilter is None else compileExFilter contentInFilter = self.ContentInFilter if contentInFilter is None else contentInFilter contentExFilter = self.ContentExFilter if contentExFilter is None else contentExFilter def filter(text, filters, explicit): """ Convience filter function :param text text: The target text. :param list filters: The collection of fnmatch expressions :param bool explicit: Flag denoting an the empty filter collection return match failure. """ if explicit: return any(fnmatch.fnmatch(text, f) for f in filters) return not filters or any(fnmatch.fnmatch(text, f) for f in filters) for root, dirnames, filenames in os.walk(rootpath): searchdir = os.path.normpath(os.path.normcase(root)) # If the root dir matches an excluded directory, stop any further searches if filter(searchdir, directoryExFilter, True): dirnames[:] = [] elif filter(searchdir, directoryInFilter, False): for filepath in [os.path.join(root, filename) for filename in filenames]: if filter(filepath, compileInFilter, False) and not filter(filepath, compileExFilter, True): self.CompileFiles.append(filepath) elif filter(filepath, contentInFilter, False) and not filter(filepath, contentExFilter, True): self.ContentFiles.append(filepath)
[ "def", "insert_files", "(", "self", ",", "rootpath", ",", "directoryInFilter", "=", "None", ",", "directoryExFilter", "=", "None", ",", "compileInFilter", "=", "None", ",", "compileExFilter", "=", "None", ",", "contentInFilter", "=", "None", ",", "contentExFilter", "=", "None", ")", ":", "directoryInFilter", "=", "self", ".", "DirectoryInFilter", "if", "directoryInFilter", "is", "None", "else", "directoryInFilter", "directoryExFilter", "=", "self", ".", "DirectoryExFilter", "if", "directoryExFilter", "is", "None", "else", "directoryExFilter", "compileInFilter", "=", "self", ".", "CompileInFilter", "if", "compileInFilter", "is", "None", "else", "compileInFilter", "compileExFilter", "=", "self", ".", "CompileExFilter", "if", "compileExFilter", "is", "None", "else", "compileExFilter", "contentInFilter", "=", "self", ".", "ContentInFilter", "if", "contentInFilter", "is", "None", "else", "contentInFilter", "contentExFilter", "=", "self", ".", "ContentExFilter", "if", "contentExFilter", "is", "None", "else", "contentExFilter", "def", "filter", "(", "text", ",", "filters", ",", "explicit", ")", ":", "if", "explicit", ":", "return", "any", "(", "fnmatch", ".", "fnmatch", "(", "text", ",", "f", ")", "for", "f", "in", "filters", ")", "return", "not", "filters", "or", "any", "(", "fnmatch", ".", "fnmatch", "(", "text", ",", "f", ")", "for", "f", "in", "filters", ")", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "rootpath", ")", ":", "searchdir", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "normcase", "(", "root", ")", ")", "if", "filter", "(", "searchdir", ",", "directoryExFilter", ",", "True", ")", ":", "dirnames", "[", ":", "]", "=", "[", "]", "elif", "filter", "(", "searchdir", ",", "directoryInFilter", ",", "False", ")", ":", "for", "filepath", "in", "[", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", "for", "filename", "in", "filenames", "]", ":", "if", "filter", "(", "filepath", ",", "compileInFilter", ",", "False", ")", "and", "not", "filter", "(", "filepath", ",", "compileExFilter", ",", "True", ")", ":", "self", ".", "CompileFiles", ".", "append", "(", "filepath", ")", "elif", "filter", "(", "filepath", ",", "contentInFilter", ",", "False", ")", "and", "not", "filter", "(", "filepath", ",", "contentExFilter", ",", "True", ")", ":", "self", ".", "ContentFiles", ".", "append", "(", "filepath", ")" ]
Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters. :param str rootpath: The absolute path to the root directory. :param list directoryInFilter: A list of fnmatch expressions to match directories to be included. A `None` value will default to :attr:`DirectoryInFilter`. :param list directoryExFilter: A list of fnmatch expressions to match directories to be excluded. A `None` value will default to :attr:`DirectoryExFilter`. :param list compileInFilter: A list of fnmatch expressions to match compile files to be included. A `None` value will default to :attr:`CompileInFilter`. :param list compileExFilter: A list of fnmatch expressions to match compile files to be excludes. A `None` value will default to :attr:`CompileExFilter`. :param list contentInFilter: A list of fnmatch expressions to match content files to be includes. A `None` value will default to :attr:`ContentInFilter`. :param list contentExFilter: A list of fnmatch expressions to match content files to be excludes. A `None` value will default to :attr:`ContentExFilter`.
[ "Inserts", "files", "by", "recursive", "traversing", "the", "rootpath", "and", "inserting", "files", "according", "the", "addition", "filter", "parameters", "." ]
640191bb018a1ff7d7b7a4982e0d3c1a423ba878
https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/project.py#L165-L209
train