identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Evaluator.__len__
(self)
Returns number of recorded attempts.
Returns number of recorded attempts.
def __len__(self) -> int: """Returns number of recorded attempts.""" return len(self._log)
[ "def", "__len__", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "_log", ")" ]
[ 531, 4 ]
[ 533, 29 ]
python
en
['en', 'en', 'en']
True
Agent.add_parser_arguments
(cls, parser: "argparse.ArgumentParser")
Add agent's parameters to the argument parser.
Add agent's parameters to the argument parser.
def add_parser_arguments(cls, parser: "argparse.ArgumentParser") -> None: """Add agent's parameters to the argument parser.""" del parser
[ "def", "add_parser_arguments", "(", "cls", ",", "parser", ":", "\"argparse.ArgumentParser\"", ")", "->", "None", ":", "del", "parser" ]
[ 70, 4 ]
[ 72, 18 ]
python
en
['en', 'en', 'en']
True
Agent.name
(cls)
Name of the agent for --agent flag.
Name of the agent for --agent flag.
def name(cls) -> str: """Name of the agent for --agent flag.""" name = cls.__name__ if name.endswith('Agent'): name = name[:-5] return name.lower()
[ "def", "name", "(", "cls", ")", "->", "str", ":", "name", "=", "cls", ".", "__name__", "if", "name", ".", "endswith", "(", "'Agent'", ")", ":", "name", "=", "name", "[", ":", "-", "5", "]", "return", "name", ".", "lower", "(", ")" ]
[ 75, 4 ]
[ 80, 27 ]
python
en
['en', 'en', 'en']
True
Agent.train
(cls, task_ids: TaskIds, action_tier_name: str, **kwargs)
Train an agent and returns a state.
Train an agent and returns a state.
def train(cls, task_ids: TaskIds, action_tier_name: str, **kwargs) -> State: """Train an agent and returns a state."""
[ "def", "train", "(", "cls", ",", "task_ids", ":", "TaskIds", ",", "action_tier_name", ":", "str", ",", "*", "*", "kwargs", ")", "->", "State", ":" ]
[ 84, 4 ]
[ 86, 49 ]
python
en
['en', 'en', 'en']
True
Agent.eval
(cls, state: State, task_ids: TaskIds, max_attempts_per_task: int, action_tier_name, **kwargs)
Runs evaluation and logs all attemps with phyre.Evaluator.
Runs evaluation and logs all attemps with phyre.Evaluator.
def eval(cls, state: State, task_ids: TaskIds, max_attempts_per_task: int, action_tier_name, **kwargs) -> phyre.Evaluator: """Runs evaluation and logs all attemps with phyre.Evaluator."""
[ "def", "eval", "(", "cls", ",", "state", ":", "State", ",", "task_ids", ":", "TaskIds", ",", "max_attempts_per_task", ":", "int", ",", "action_tier_name", ",", "*", "*", "kwargs", ")", "->", "phyre", ".", "Evaluator", ":" ]
[ 89, 4 ]
[ 91, 72 ]
python
en
['en', 'en', 'en']
True
MaxHeapWithSideLoad.pop_key
(self, key)
Remove key from the heap.
Remove key from the heap.
def pop_key(self, key): """Remove key from the heap.""" entry = self.key_to_entry[key] del self.key_to_entry[key] entry[-1] = 0 return entry[1], -entry[0]
[ "def", "pop_key", "(", "self", ",", "key", ")", ":", "entry", "=", "self", ".", "key_to_entry", "[", "key", "]", "del", "self", ".", "key_to_entry", "[", "key", "]", "entry", "[", "-", "1", "]", "=", "0", "return", "entry", "[", "1", "]", ",", "-", "entry", "[", "0", "]" ]
[ 133, 4 ]
[ 138, 34 ]
python
en
['en', 'en', 'en']
True
MaxHeapWithSideLoad.push
(self, key, priority)
Push a new key into the heap.
Push a new key into the heap.
def push(self, key, priority): """Push a new key into the heap.""" assert key not in self.key_to_entry, key entry = [-priority, key, 1] self.key_to_entry[key] = entry heapq.heappush(self.heap, entry)
[ "def", "push", "(", "self", ",", "key", ",", "priority", ")", ":", "assert", "key", "not", "in", "self", ".", "key_to_entry", ",", "key", "entry", "=", "[", "-", "priority", ",", "key", ",", "1", "]", "self", ".", "key_to_entry", "[", "key", "]", "=", "entry", "heapq", ".", "heappush", "(", "self", ".", "heap", ",", "entry", ")" ]
[ 140, 4 ]
[ 145, 40 ]
python
en
['en', 'mg', 'en']
True
MaxHeapWithSideLoad.pop_max
(self)
Get (key, priority) pair with the highest priority.
Get (key, priority) pair with the highest priority.
def pop_max(self): """Get (key, priority) pair with the highest priority.""" while True: priority, key, is_valid = heapq.heappop(self.heap) if not is_valid: continue del self.key_to_entry[key] return key, -priority
[ "def", "pop_max", "(", "self", ")", ":", "while", "True", ":", "priority", ",", "key", ",", "is_valid", "=", "heapq", ".", "heappop", "(", "self", ".", "heap", ")", "if", "not", "is_valid", ":", "continue", "del", "self", ".", "key_to_entry", "[", "key", "]", "return", "key", ",", "-", "priority" ]
[ 147, 4 ]
[ 154, 33 ]
python
en
['en', 'en', 'en']
True
MaxHeapWithSideLoad.copy
(self)
Create a clone of the queue.
Create a clone of the queue.
def copy(self): """Create a clone of the queue.""" return MaxHeapWithSideLoad([[k, -v] for v, k, is_valid in self.heap if is_valid])
[ "def", "copy", "(", "self", ")", ":", "return", "MaxHeapWithSideLoad", "(", "[", "[", "k", ",", "-", "v", "]", "for", "v", ",", "k", ",", "is_valid", "in", "self", ".", "heap", "if", "is_valid", "]", ")" ]
[ 156, 4 ]
[ 159, 49 ]
python
en
['en', 'en', 'en']
True
DQNAgent._extract_prefix_flags
(cls, prefix='dqn_', **kwargs)
Extract DQN-related train and test command line flags.
Extract DQN-related train and test command line flags.
def _extract_prefix_flags(cls, prefix='dqn_', **kwargs): """Extract DQN-related train and test command line flags.""" train_kwargs, eval_kwargs = {}, {} for k, v in kwargs.items(): if k.startswith(prefix): flag = k.split('_', 1)[1] if flag in cls.EVAL_FLAG_NAMES: eval_kwargs[flag] = v else: train_kwargs[flag] = v return train_kwargs, eval_kwargs
[ "def", "_extract_prefix_flags", "(", "cls", ",", "prefix", "=", "'dqn_'", ",", "*", "*", "kwargs", ")", ":", "train_kwargs", ",", "eval_kwargs", "=", "{", "}", ",", "{", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", ".", "startswith", "(", "prefix", ")", ":", "flag", "=", "k", ".", "split", "(", "'_'", ",", "1", ")", "[", "1", "]", "if", "flag", "in", "cls", ".", "EVAL_FLAG_NAMES", ":", "eval_kwargs", "[", "flag", "]", "=", "v", "else", ":", "train_kwargs", "[", "flag", "]", "=", "v", "return", "train_kwargs", ",", "eval_kwargs" ]
[ 471, 4 ]
[ 482, 40 ]
python
en
['en', 'en', 'en']
True
FwdAgent.print_pixel_accs_summary
(cls, pxl_accs_lst, phyre_movable_ch)
Print out the accuracy for each class, avg over moving class etc Args: pxl_accs_lst: List with each element (B, phyre.NUM_CLASSES) phyre_movable_ch: The channels in phyre for movable objs
Print out the accuracy for each class, avg over moving class etc Args: pxl_accs_lst: List with each element (B, phyre.NUM_CLASSES) phyre_movable_ch: The channels in phyre for movable objs
def print_pixel_accs_summary(cls, pxl_accs_lst, phyre_movable_ch): """ Print out the accuracy for each class, avg over moving class etc Args: pxl_accs_lst: List with each element (B, phyre.NUM_CLASSES) phyre_movable_ch: The channels in phyre for movable objs """ pxl_accs = np.concatenate(pxl_accs_lst, axis=0) logging.info('Pixel accuracies for each color: %s', np.mean(pxl_accs, axis=0)) pxl_accs_movable = pxl_accs[:, phyre_movable_ch] logging.info( 'Avg pixel accuracies for moving color (ignoring nan): %s', np.nanmean(pxl_accs_movable))
[ "def", "print_pixel_accs_summary", "(", "cls", ",", "pxl_accs_lst", ",", "phyre_movable_ch", ")", ":", "pxl_accs", "=", "np", ".", "concatenate", "(", "pxl_accs_lst", ",", "axis", "=", "0", ")", "logging", ".", "info", "(", "'Pixel accuracies for each color: %s'", ",", "np", ".", "mean", "(", "pxl_accs", ",", "axis", "=", "0", ")", ")", "pxl_accs_movable", "=", "pxl_accs", "[", ":", ",", "phyre_movable_ch", "]", "logging", ".", "info", "(", "'Avg pixel accuracies for moving color (ignoring nan): %s'", ",", "np", ".", "nanmean", "(", "pxl_accs_movable", ")", ")" ]
[ 602, 4 ]
[ 615, 41 ]
python
en
['en', 'error', 'th']
False
FwdAgent.read_actions_override
(cls, action_str)
Parse the action string into a list Format is x1:y1:r1::x2:y2:r2:: .. so on
Parse the action string into a list Format is x1:y1:r1::x2:y2:r2:: .. so on
def read_actions_override(cls, action_str): """ Parse the action string into a list Format is x1:y1:r1::x2:y2:r2:: .. so on """ return [[float(el) for el in action.split(':')] for action in action_str.split('::')]
[ "def", "read_actions_override", "(", "cls", ",", "action_str", ")", ":", "return", "[", "[", "float", "(", "el", ")", "for", "el", "in", "action", ".", "split", "(", "':'", ")", "]", "for", "action", "in", "action_str", ".", "split", "(", "'::'", ")", "]" ]
[ 618, 4 ]
[ 624, 53 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_table_list
(self, cursor)
Return a list of table and view names in the current database.
Return a list of table and view names in the current database.
def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" cursor.execute(""" SELECT c.relname, CASE WHEN {} THEN 'p' WHEN c.relkind IN ('m', 'v') THEN 'v' ELSE 't' END FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid) """.format('c.relispartition' if self.connection.features.supports_table_partitions else 'FALSE')) return [TableInfo(*row) for row in cursor.fetchall() if row[0] not in self.ignored_tables]
[ "def", "get_table_list", "(", "self", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "\"\"\"\n SELECT c.relname,\n CASE WHEN {} THEN 'p' WHEN c.relkind IN ('m', 'v') THEN 'v' ELSE 't' END\n FROM pg_catalog.pg_class c\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v')\n AND n.nspname NOT IN ('pg_catalog', 'pg_toast')\n AND pg_catalog.pg_table_is_visible(c.oid)\n \"\"\"", ".", "format", "(", "'c.relispartition'", "if", "self", ".", "connection", ".", "features", ".", "supports_table_partitions", "else", "'FALSE'", ")", ")", "return", "[", "TableInfo", "(", "*", "row", ")", "for", "row", "in", "cursor", ".", "fetchall", "(", ")", "if", "row", "[", "0", "]", "not", "in", "self", ".", "ignored_tables", "]" ]
[ 46, 4 ]
[ 57, 98 ]
python
en
['en', 'en', 'en']
True
DatabaseIntrospection.get_table_description
(self, cursor, table_name)
Return a description of the table with the DB-API cursor.description interface.
Return a description of the table with the DB-API cursor.description interface.
def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ # Query the pg_catalog tables as cursor.description does not reliably # return the nullable property and information_schema.columns does not # contain details of materialized views. cursor.execute(""" SELECT a.attname AS column_name, NOT (a.attnotnull OR (t.typtype = 'd' AND t.typnotnull)) AS is_nullable, pg_get_expr(ad.adbin, ad.adrelid) AS column_default, CASE WHEN collname = 'default' THEN NULL ELSE collname END AS collation FROM pg_attribute a LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum LEFT JOIN pg_collation co ON a.attcollation = co.oid JOIN pg_type t ON a.atttypid = t.oid JOIN pg_class c ON a.attrelid = c.oid JOIN pg_namespace n ON c.relnamespace = n.oid WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v') AND c.relname = %s AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid) """, [table_name]) field_map = {line[0]: line[1:] for line in cursor.fetchall()} cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name)) return [ FieldInfo( line.name, line.type_code, line.display_size, line.internal_size, line.precision, line.scale, *field_map[line.name], ) for line in cursor.description ]
[ "def", "get_table_description", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "# Query the pg_catalog tables as cursor.description does not reliably", "# return the nullable property and information_schema.columns does not", "# contain details of materialized views.", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n a.attname AS column_name,\n NOT (a.attnotnull OR (t.typtype = 'd' AND t.typnotnull)) AS is_nullable,\n pg_get_expr(ad.adbin, ad.adrelid) AS column_default,\n CASE WHEN collname = 'default' THEN NULL ELSE collname END AS collation\n FROM pg_attribute a\n LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum\n LEFT JOIN pg_collation co ON a.attcollation = co.oid\n JOIN pg_type t ON a.atttypid = t.oid\n JOIN pg_class c ON a.attrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v')\n AND c.relname = %s\n AND n.nspname NOT IN ('pg_catalog', 'pg_toast')\n AND pg_catalog.pg_table_is_visible(c.oid)\n \"\"\"", ",", "[", "table_name", "]", ")", "field_map", "=", "{", "line", "[", "0", "]", ":", "line", "[", "1", ":", "]", "for", "line", "in", "cursor", ".", "fetchall", "(", ")", "}", "cursor", ".", "execute", "(", "\"SELECT * FROM %s LIMIT 1\"", "%", "self", ".", "connection", ".", "ops", ".", "quote_name", "(", "table_name", ")", ")", "return", "[", "FieldInfo", "(", "line", ".", "name", ",", "line", ".", "type_code", ",", "line", ".", "display_size", ",", "line", ".", "internal_size", ",", "line", ".", "precision", ",", "line", ".", "scale", ",", "*", "field_map", "[", "line", ".", "name", "]", ",", ")", "for", "line", "in", "cursor", ".", "description", "]" ]
[ 59, 4 ]
[ 97, 9 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_relations
(self, cursor, table_name)
Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table.
Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table.
def get_relations(self, cursor, table_name): """ Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table. """ return {row[0]: (row[2], row[1]) for row in self.get_key_columns(cursor, table_name)}
[ "def", "get_relations", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "return", "{", "row", "[", "0", "]", ":", "(", "row", "[", "2", "]", ",", "row", "[", "1", "]", ")", "for", "row", "in", "self", ".", "get_key_columns", "(", "cursor", ",", "table_name", ")", "}" ]
[ 118, 4 ]
[ 123, 93 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_constraints
(self, cursor, table_name)
Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. Also retrieve the definition of expression-based indexes.
Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. Also retrieve the definition of expression-based indexes.
def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. Also retrieve the definition of expression-based indexes. """ constraints = {} # Loop over the key table, collecting things as constraints. The column # array must return column names in the same order in which they were # created. cursor.execute(""" SELECT c.conname, array( SELECT attname FROM unnest(c.conkey) WITH ORDINALITY cols(colid, arridx) JOIN pg_attribute AS ca ON cols.colid = ca.attnum WHERE ca.attrelid = c.conrelid ORDER BY cols.arridx ), c.contype, (SELECT fkc.relname || '.' || fka.attname FROM pg_attribute AS fka JOIN pg_class AS fkc ON fka.attrelid = fkc.oid WHERE fka.attrelid = c.confrelid AND fka.attnum = c.confkey[1]), cl.reloptions FROM pg_constraint AS c JOIN pg_class AS cl ON c.conrelid = cl.oid WHERE cl.relname = %s AND pg_catalog.pg_table_is_visible(cl.oid) """, [table_name]) for constraint, columns, kind, used_cols, options in cursor.fetchall(): constraints[constraint] = { "columns": columns, "primary_key": kind == "p", "unique": kind in ["p", "u"], "foreign_key": tuple(used_cols.split(".", 1)) if kind == "f" else None, "check": kind == "c", "index": False, "definition": None, "options": options, } # Now get indexes cursor.execute(""" SELECT indexname, array_agg(attname ORDER BY arridx), indisunique, indisprimary, array_agg(ordering ORDER BY arridx), amname, exprdef, s2.attoptions FROM ( SELECT c2.relname as indexname, idx.*, attr.attname, am.amname, CASE WHEN idx.indexprs IS NOT NULL THEN pg_get_indexdef(idx.indexrelid) END AS exprdef, CASE am.amname WHEN %s THEN CASE (option & 1) WHEN 1 THEN 'DESC' ELSE 'ASC' END END as ordering, c2.reloptions as attoptions FROM ( SELECT * FROM pg_index i, unnest(i.indkey, i.indoption) WITH ORDINALITY koi(key, option, arridx) ) idx LEFT JOIN pg_class c ON idx.indrelid = c.oid LEFT JOIN pg_class c2 ON idx.indexrelid = c2.oid LEFT JOIN pg_am am ON c2.relam = am.oid LEFT JOIN pg_attribute attr ON attr.attrelid = c.oid AND attr.attnum = idx.key WHERE c.relname = %s AND pg_catalog.pg_table_is_visible(c.oid) ) s2 GROUP BY indexname, indisunique, indisprimary, amname, exprdef, attoptions; """, [self.index_default_access_method, table_name]) for index, columns, unique, primary, orders, type_, definition, options in cursor.fetchall(): if index not in constraints: basic_index = ( type_ == self.index_default_access_method and # '_btree' references # django.contrib.postgres.indexes.BTreeIndex.suffix. not index.endswith('_btree') and options is None ) constraints[index] = { "columns": columns if columns != [None] else [], "orders": orders if orders != [None] else [], "primary_key": primary, "unique": unique, "foreign_key": None, "check": False, "index": True, "type": Index.suffix if basic_index else type_, "definition": definition, "options": options, } return constraints
[ "def", "get_constraints", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "constraints", "=", "{", "}", "# Loop over the key table, collecting things as constraints. The column", "# array must return column names in the same order in which they were", "# created.", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n c.conname,\n array(\n SELECT attname\n FROM unnest(c.conkey) WITH ORDINALITY cols(colid, arridx)\n JOIN pg_attribute AS ca ON cols.colid = ca.attnum\n WHERE ca.attrelid = c.conrelid\n ORDER BY cols.arridx\n ),\n c.contype,\n (SELECT fkc.relname || '.' || fka.attname\n FROM pg_attribute AS fka\n JOIN pg_class AS fkc ON fka.attrelid = fkc.oid\n WHERE fka.attrelid = c.confrelid AND fka.attnum = c.confkey[1]),\n cl.reloptions\n FROM pg_constraint AS c\n JOIN pg_class AS cl ON c.conrelid = cl.oid\n WHERE cl.relname = %s AND pg_catalog.pg_table_is_visible(cl.oid)\n \"\"\"", ",", "[", "table_name", "]", ")", "for", "constraint", ",", "columns", ",", "kind", ",", "used_cols", ",", "options", "in", "cursor", ".", "fetchall", "(", ")", ":", "constraints", "[", "constraint", "]", "=", "{", "\"columns\"", ":", "columns", ",", "\"primary_key\"", ":", "kind", "==", "\"p\"", ",", "\"unique\"", ":", "kind", "in", "[", "\"p\"", ",", "\"u\"", "]", ",", "\"foreign_key\"", ":", "tuple", "(", "used_cols", ".", "split", "(", "\".\"", ",", "1", ")", ")", "if", "kind", "==", "\"f\"", "else", "None", ",", "\"check\"", ":", "kind", "==", "\"c\"", ",", "\"index\"", ":", "False", ",", "\"definition\"", ":", "None", ",", "\"options\"", ":", "options", ",", "}", "# Now get indexes", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n indexname, array_agg(attname ORDER BY arridx), indisunique, indisprimary,\n array_agg(ordering ORDER BY arridx), amname, exprdef, s2.attoptions\n FROM (\n SELECT\n c2.relname as indexname, idx.*, attr.attname, am.amname,\n CASE\n WHEN idx.indexprs IS NOT NULL THEN\n pg_get_indexdef(idx.indexrelid)\n END AS exprdef,\n CASE am.amname\n WHEN %s THEN\n CASE (option & 1)\n WHEN 1 THEN 'DESC' ELSE 'ASC'\n END\n END as ordering,\n c2.reloptions as attoptions\n FROM (\n SELECT *\n FROM pg_index i, unnest(i.indkey, i.indoption) WITH ORDINALITY koi(key, option, arridx)\n ) idx\n LEFT JOIN pg_class c ON idx.indrelid = c.oid\n LEFT JOIN pg_class c2 ON idx.indexrelid = c2.oid\n LEFT JOIN pg_am am ON c2.relam = am.oid\n LEFT JOIN pg_attribute attr ON attr.attrelid = c.oid AND attr.attnum = idx.key\n WHERE c.relname = %s AND pg_catalog.pg_table_is_visible(c.oid)\n ) s2\n GROUP BY indexname, indisunique, indisprimary, amname, exprdef, attoptions;\n \"\"\"", ",", "[", "self", ".", "index_default_access_method", ",", "table_name", "]", ")", "for", "index", ",", "columns", ",", "unique", ",", "primary", ",", "orders", ",", "type_", ",", "definition", ",", "options", "in", "cursor", ".", "fetchall", "(", ")", ":", "if", "index", "not", "in", "constraints", ":", "basic_index", "=", "(", "type_", "==", "self", ".", "index_default_access_method", "and", "# '_btree' references", "# django.contrib.postgres.indexes.BTreeIndex.suffix.", "not", "index", ".", "endswith", "(", "'_btree'", ")", "and", "options", "is", "None", ")", "constraints", "[", "index", "]", "=", "{", "\"columns\"", ":", "columns", "if", "columns", "!=", "[", "None", "]", "else", "[", "]", ",", "\"orders\"", ":", "orders", "if", "orders", "!=", "[", "None", "]", "else", "[", "]", ",", "\"primary_key\"", ":", "primary", ",", "\"unique\"", ":", "unique", ",", "\"foreign_key\"", ":", "None", ",", "\"check\"", ":", "False", ",", "\"index\"", ":", "True", ",", "\"type\"", ":", "Index", ".", "suffix", "if", "basic_index", "else", "type_", ",", "\"definition\"", ":", "definition", ",", "\"options\"", ":", "options", ",", "}", "return", "constraints" ]
[ 141, 4 ]
[ 233, 26 ]
python
en
['en', 'error', 'th']
False
_normalize_mode
(im, initial_call=False)
Takes an image (or frame), returns an image in a mode that is appropriate for saving in a Gif. It may return the original image, or it may return an image converted to palette or 'L' mode. UNDONE: What is the point of mucking with the initial call palette, for an image that shouldn't have a palette, or it would be a mode 'P' and get returned in the RAWMODE clause. :param im: Image object :param initial_call: Default false, set to true for a single frame. :returns: Image object
Takes an image (or frame), returns an image in a mode that is appropriate for saving in a Gif.
def _normalize_mode(im, initial_call=False): """ Takes an image (or frame), returns an image in a mode that is appropriate for saving in a Gif. It may return the original image, or it may return an image converted to palette or 'L' mode. UNDONE: What is the point of mucking with the initial call palette, for an image that shouldn't have a palette, or it would be a mode 'P' and get returned in the RAWMODE clause. :param im: Image object :param initial_call: Default false, set to true for a single frame. :returns: Image object """ if im.mode in RAWMODE: im.load() return im if Image.getmodebase(im.mode) == "RGB": if initial_call: palette_size = 256 if im.palette: palette_size = len(im.palette.getdata()[1]) // 3 return im.convert("P", palette=Image.ADAPTIVE, colors=palette_size) else: return im.convert("P") return im.convert("L")
[ "def", "_normalize_mode", "(", "im", ",", "initial_call", "=", "False", ")", ":", "if", "im", ".", "mode", "in", "RAWMODE", ":", "im", ".", "load", "(", ")", "return", "im", "if", "Image", ".", "getmodebase", "(", "im", ".", "mode", ")", "==", "\"RGB\"", ":", "if", "initial_call", ":", "palette_size", "=", "256", "if", "im", ".", "palette", ":", "palette_size", "=", "len", "(", "im", ".", "palette", ".", "getdata", "(", ")", "[", "1", "]", ")", "//", "3", "return", "im", ".", "convert", "(", "\"P\"", ",", "palette", "=", "Image", ".", "ADAPTIVE", ",", "colors", "=", "palette_size", ")", "else", ":", "return", "im", ".", "convert", "(", "\"P\"", ")", "return", "im", ".", "convert", "(", "\"L\"", ")" ]
[ 350, 0 ]
[ 377, 26 ]
python
en
['en', 'error', 'th']
False
_normalize_palette
(im, palette, info)
Normalizes the palette for image. - Sets the palette to the incoming palette, if provided. - Ensures that there's a palette for L mode images - Optimizes the palette if necessary/desired. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: Image object
Normalizes the palette for image. - Sets the palette to the incoming palette, if provided. - Ensures that there's a palette for L mode images - Optimizes the palette if necessary/desired.
def _normalize_palette(im, palette, info): """ Normalizes the palette for image. - Sets the palette to the incoming palette, if provided. - Ensures that there's a palette for L mode images - Optimizes the palette if necessary/desired. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: Image object """ source_palette = None if palette: # a bytes palette if isinstance(palette, (bytes, bytearray, list)): source_palette = bytearray(palette[:768]) if isinstance(palette, ImagePalette.ImagePalette): source_palette = bytearray(palette.palette) if im.mode == "P": if not source_palette: source_palette = im.im.getpalette("RGB")[:768] else: # L-mode if not source_palette: source_palette = bytearray(i // 3 for i in range(768)) im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette) used_palette_colors = _get_optimize(im, info) if used_palette_colors is not None: return im.remap_palette(used_palette_colors, source_palette) im.palette.palette = source_palette return im
[ "def", "_normalize_palette", "(", "im", ",", "palette", ",", "info", ")", ":", "source_palette", "=", "None", "if", "palette", ":", "# a bytes palette", "if", "isinstance", "(", "palette", ",", "(", "bytes", ",", "bytearray", ",", "list", ")", ")", ":", "source_palette", "=", "bytearray", "(", "palette", "[", ":", "768", "]", ")", "if", "isinstance", "(", "palette", ",", "ImagePalette", ".", "ImagePalette", ")", ":", "source_palette", "=", "bytearray", "(", "palette", ".", "palette", ")", "if", "im", ".", "mode", "==", "\"P\"", ":", "if", "not", "source_palette", ":", "source_palette", "=", "im", ".", "im", ".", "getpalette", "(", "\"RGB\"", ")", "[", ":", "768", "]", "else", ":", "# L-mode", "if", "not", "source_palette", ":", "source_palette", "=", "bytearray", "(", "i", "//", "3", "for", "i", "in", "range", "(", "768", ")", ")", "im", ".", "palette", "=", "ImagePalette", ".", "ImagePalette", "(", "\"RGB\"", ",", "palette", "=", "source_palette", ")", "used_palette_colors", "=", "_get_optimize", "(", "im", ",", "info", ")", "if", "used_palette_colors", "is", "not", "None", ":", "return", "im", ".", "remap_palette", "(", "used_palette_colors", ",", "source_palette", ")", "im", ".", "palette", ".", "palette", "=", "source_palette", "return", "im" ]
[ 380, 0 ]
[ 413, 13 ]
python
en
['en', 'error', 'th']
False
_get_optimize
(im, info)
Palette optimization is a potentially expensive operation. This function determines if the palette should be optimized using some heuristics, then returns the list of palette entries in use. :param im: Image object :param info: encoderinfo :returns: list of indexes of palette entries in use, or None
Palette optimization is a potentially expensive operation.
def _get_optimize(im, info): """ Palette optimization is a potentially expensive operation. This function determines if the palette should be optimized using some heuristics, then returns the list of palette entries in use. :param im: Image object :param info: encoderinfo :returns: list of indexes of palette entries in use, or None """ if im.mode in ("P", "L") and info and info.get("optimize", 0): # Potentially expensive operation. # The palette saves 3 bytes per color not used, but palette # lengths are restricted to 3*(2**N) bytes. Max saving would # be 768 -> 6 bytes if we went all the way down to 2 colors. # * If we're over 128 colors, we can't save any space. # * If there aren't any holes, it's not worth collapsing. # * If we have a 'large' image, the palette is in the noise. # create the new palette if not every color is used optimise = _FORCE_OPTIMIZE or im.mode == "L" if optimise or im.width * im.height < 512 * 512: # check which colors are used used_palette_colors = [] for i, count in enumerate(im.histogram()): if count: used_palette_colors.append(i) if optimise or ( len(used_palette_colors) <= 128 and max(used_palette_colors) > len(used_palette_colors) ): return used_palette_colors
[ "def", "_get_optimize", "(", "im", ",", "info", ")", ":", "if", "im", ".", "mode", "in", "(", "\"P\"", ",", "\"L\"", ")", "and", "info", "and", "info", ".", "get", "(", "\"optimize\"", ",", "0", ")", ":", "# Potentially expensive operation.", "# The palette saves 3 bytes per color not used, but palette", "# lengths are restricted to 3*(2**N) bytes. Max saving would", "# be 768 -> 6 bytes if we went all the way down to 2 colors.", "# * If we're over 128 colors, we can't save any space.", "# * If there aren't any holes, it's not worth collapsing.", "# * If we have a 'large' image, the palette is in the noise.", "# create the new palette if not every color is used", "optimise", "=", "_FORCE_OPTIMIZE", "or", "im", ".", "mode", "==", "\"L\"", "if", "optimise", "or", "im", ".", "width", "*", "im", ".", "height", "<", "512", "*", "512", ":", "# check which colors are used", "used_palette_colors", "=", "[", "]", "for", "i", ",", "count", "in", "enumerate", "(", "im", ".", "histogram", "(", ")", ")", ":", "if", "count", ":", "used_palette_colors", ".", "append", "(", "i", ")", "if", "optimise", "or", "(", "len", "(", "used_palette_colors", ")", "<=", "128", "and", "max", "(", "used_palette_colors", ")", ">", "len", "(", "used_palette_colors", ")", ")", ":", "return", "used_palette_colors" ]
[ 682, 0 ]
[ 716, 42 ]
python
en
['en', 'error', 'th']
False
_get_header_palette
(palette_bytes)
Returns the palette, null padded to the next power of 2 (*3) bytes suitable for direct inclusion in the GIF header :param palette_bytes: Unpadded palette bytes, in RGBRGB form :returns: Null padded palette
Returns the palette, null padded to the next power of 2 (*3) bytes suitable for direct inclusion in the GIF header
def _get_header_palette(palette_bytes): """ Returns the palette, null padded to the next power of 2 (*3) bytes suitable for direct inclusion in the GIF header :param palette_bytes: Unpadded palette bytes, in RGBRGB form :returns: Null padded palette """ color_table_size = _get_color_table_size(palette_bytes) # add the missing amount of bytes # the palette has to be 2<<n in size actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3 if actual_target_size_diff > 0: palette_bytes += o8(0) * 3 * actual_target_size_diff return palette_bytes
[ "def", "_get_header_palette", "(", "palette_bytes", ")", ":", "color_table_size", "=", "_get_color_table_size", "(", "palette_bytes", ")", "# add the missing amount of bytes", "# the palette has to be 2<<n in size", "actual_target_size_diff", "=", "(", "2", "<<", "color_table_size", ")", "-", "len", "(", "palette_bytes", ")", "//", "3", "if", "actual_target_size_diff", ">", "0", ":", "palette_bytes", "+=", "o8", "(", "0", ")", "*", "3", "*", "actual_target_size_diff", "return", "palette_bytes" ]
[ 729, 0 ]
[ 744, 24 ]
python
en
['en', 'error', 'th']
False
_get_palette_bytes
(im)
Gets the palette for inclusion in the gif header :param im: Image object :returns: Bytes, len<=768 suitable for inclusion in gif header
Gets the palette for inclusion in the gif header
def _get_palette_bytes(im): """ Gets the palette for inclusion in the gif header :param im: Image object :returns: Bytes, len<=768 suitable for inclusion in gif header """ return im.palette.palette
[ "def", "_get_palette_bytes", "(", "im", ")", ":", "return", "im", ".", "palette", ".", "palette" ]
[ 747, 0 ]
[ 754, 29 ]
python
en
['en', 'error', 'th']
False
_get_global_header
(im, info)
Return a list of strings representing a GIF header
Return a list of strings representing a GIF header
def _get_global_header(im, info): """Return a list of strings representing a GIF header""" # Header Block # http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp version = b"87a" for extensionKey in ["transparency", "duration", "loop", "comment"]: if info and extensionKey in info: if (extensionKey == "duration" and info[extensionKey] == 0) or ( extensionKey == "comment" and not (1 <= len(info[extensionKey]) <= 255) ): continue version = b"89a" break else: if im.info.get("version") == b"89a": version = b"89a" background = _get_background(im, info.get("background")) palette_bytes = _get_palette_bytes(im) color_table_size = _get_color_table_size(palette_bytes) return [ b"GIF" # signature + version # version + o16(im.size[0]) # canvas width + o16(im.size[1]), # canvas height # Logical Screen Descriptor # size of global color table + global color table flag o8(color_table_size + 128), # packed fields # background + reserved/aspect o8(background) + o8(0), # Global Color Table _get_header_palette(palette_bytes), ]
[ "def", "_get_global_header", "(", "im", ",", "info", ")", ":", "# Header Block", "# http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp", "version", "=", "b\"87a\"", "for", "extensionKey", "in", "[", "\"transparency\"", ",", "\"duration\"", ",", "\"loop\"", ",", "\"comment\"", "]", ":", "if", "info", "and", "extensionKey", "in", "info", ":", "if", "(", "extensionKey", "==", "\"duration\"", "and", "info", "[", "extensionKey", "]", "==", "0", ")", "or", "(", "extensionKey", "==", "\"comment\"", "and", "not", "(", "1", "<=", "len", "(", "info", "[", "extensionKey", "]", ")", "<=", "255", ")", ")", ":", "continue", "version", "=", "b\"89a\"", "break", "else", ":", "if", "im", ".", "info", ".", "get", "(", "\"version\"", ")", "==", "b\"89a\"", ":", "version", "=", "b\"89a\"", "background", "=", "_get_background", "(", "im", ",", "info", ".", "get", "(", "\"background\"", ")", ")", "palette_bytes", "=", "_get_palette_bytes", "(", "im", ")", "color_table_size", "=", "_get_color_table_size", "(", "palette_bytes", ")", "return", "[", "b\"GIF\"", "# signature", "+", "version", "# version", "+", "o16", "(", "im", ".", "size", "[", "0", "]", ")", "# canvas width", "+", "o16", "(", "im", ".", "size", "[", "1", "]", ")", ",", "# canvas height", "# Logical Screen Descriptor", "# size of global color table + global color table flag", "o8", "(", "color_table_size", "+", "128", ")", ",", "# packed fields", "# background + reserved/aspect", "o8", "(", "background", ")", "+", "o8", "(", "0", ")", ",", "# Global Color Table", "_get_header_palette", "(", "palette_bytes", ")", ",", "]" ]
[ 777, 0 ]
[ 813, 5 ]
python
en
['en', 'en', 'en']
True
getheader
(im, palette=None, info=None)
Legacy Method to get Gif data from image. Warning:: May modify image data. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: tuple of(list of header items, optimized palette)
Legacy Method to get Gif data from image.
def getheader(im, palette=None, info=None): """ Legacy Method to get Gif data from image. Warning:: May modify image data. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: tuple of(list of header items, optimized palette) """ used_palette_colors = _get_optimize(im, info) if info is None: info = {} if "background" not in info and "background" in im.info: info["background"] = im.info["background"] im_mod = _normalize_palette(im, palette, info) im.palette = im_mod.palette im.im = im_mod.im header = _get_global_header(im, info) return header, used_palette_colors
[ "def", "getheader", "(", "im", ",", "palette", "=", "None", ",", "info", "=", "None", ")", ":", "used_palette_colors", "=", "_get_optimize", "(", "im", ",", "info", ")", "if", "info", "is", "None", ":", "info", "=", "{", "}", "if", "\"background\"", "not", "in", "info", "and", "\"background\"", "in", "im", ".", "info", ":", "info", "[", "\"background\"", "]", "=", "im", ".", "info", "[", "\"background\"", "]", "im_mod", "=", "_normalize_palette", "(", "im", ",", "palette", ",", "info", ")", "im", ".", "palette", "=", "im_mod", ".", "palette", "im", ".", "im", "=", "im_mod", ".", "im", "header", "=", "_get_global_header", "(", "im", ",", "info", ")", "return", "header", ",", "used_palette_colors" ]
[ 836, 0 ]
[ 861, 38 ]
python
en
['en', 'error', 'th']
False
getdata
(im, offset=(0, 0), **params)
Legacy Method Return a list of strings representing this image. The first string is a local image header, the rest contains encoded image data. :param im: Image object :param offset: Tuple of (x, y) pixels. Defaults to (0,0) :param \\**params: E.g. duration or other encoder info parameters :returns: List of Bytes containing gif encoded frame data
Legacy Method
def getdata(im, offset=(0, 0), **params): """ Legacy Method Return a list of strings representing this image. The first string is a local image header, the rest contains encoded image data. :param im: Image object :param offset: Tuple of (x, y) pixels. Defaults to (0,0) :param \\**params: E.g. duration or other encoder info parameters :returns: List of Bytes containing gif encoded frame data """ class Collector: data = [] def write(self, data): self.data.append(data) im.load() # make sure raster data is available fp = Collector() _write_frame_data(fp, im, offset, params) return fp.data
[ "def", "getdata", "(", "im", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "*", "*", "params", ")", ":", "class", "Collector", ":", "data", "=", "[", "]", "def", "write", "(", "self", ",", "data", ")", ":", "self", ".", "data", ".", "append", "(", "data", ")", "im", ".", "load", "(", ")", "# make sure raster data is available", "fp", "=", "Collector", "(", ")", "_write_frame_data", "(", "fp", ",", "im", ",", "offset", ",", "params", ")", "return", "fp", ".", "data" ]
[ 866, 0 ]
[ 893, 18 ]
python
en
['en', 'error', 'th']
False
LogEntry.get_change_message
(self)
If self.change_message is a JSON structure, interpret it as a change string, properly translated.
If self.change_message is a JSON structure, interpret it as a change string, properly translated.
def get_change_message(self): """ If self.change_message is a JSON structure, interpret it as a change string, properly translated. """ if self.change_message and self.change_message[0] == '[': try: change_message = json.loads(self.change_message) except json.JSONDecodeError: return self.change_message messages = [] for sub_message in change_message: if 'added' in sub_message: if sub_message['added']: sub_message['added']['name'] = gettext(sub_message['added']['name']) messages.append(gettext('Added {name} “{object}”.').format(**sub_message['added'])) else: messages.append(gettext('Added.')) elif 'changed' in sub_message: sub_message['changed']['fields'] = get_text_list( [gettext(field_name) for field_name in sub_message['changed']['fields']], gettext('and') ) if 'name' in sub_message['changed']: sub_message['changed']['name'] = gettext(sub_message['changed']['name']) messages.append(gettext('Changed {fields} for {name} “{object}”.').format( **sub_message['changed'] )) else: messages.append(gettext('Changed {fields}.').format(**sub_message['changed'])) elif 'deleted' in sub_message: sub_message['deleted']['name'] = gettext(sub_message['deleted']['name']) messages.append(gettext('Deleted {name} “{object}”.').format(**sub_message['deleted'])) change_message = ' '.join(msg[0].upper() + msg[1:] for msg in messages) return change_message or gettext('No fields changed.') else: return self.change_message
[ "def", "get_change_message", "(", "self", ")", ":", "if", "self", ".", "change_message", "and", "self", ".", "change_message", "[", "0", "]", "==", "'['", ":", "try", ":", "change_message", "=", "json", ".", "loads", "(", "self", ".", "change_message", ")", "except", "json", ".", "JSONDecodeError", ":", "return", "self", ".", "change_message", "messages", "=", "[", "]", "for", "sub_message", "in", "change_message", ":", "if", "'added'", "in", "sub_message", ":", "if", "sub_message", "[", "'added'", "]", ":", "sub_message", "[", "'added'", "]", "[", "'name'", "]", "=", "gettext", "(", "sub_message", "[", "'added'", "]", "[", "'name'", "]", ")", "messages", ".", "append", "(", "gettext", "(", "'Added {name} “{object}”.').fo", "r", "m", "at(**s", "u", "b", "_", "message['ad", "d", "ed']))", "", "", "", "else", ":", "messages", ".", "append", "(", "gettext", "(", "'Added.'", ")", ")", "elif", "'changed'", "in", "sub_message", ":", "sub_message", "[", "'changed'", "]", "[", "'fields'", "]", "=", "get_text_list", "(", "[", "gettext", "(", "field_name", ")", "for", "field_name", "in", "sub_message", "[", "'changed'", "]", "[", "'fields'", "]", "]", ",", "gettext", "(", "'and'", ")", ")", "if", "'name'", "in", "sub_message", "[", "'changed'", "]", ":", "sub_message", "[", "'changed'", "]", "[", "'name'", "]", "=", "gettext", "(", "sub_message", "[", "'changed'", "]", "[", "'name'", "]", ")", "messages", ".", "append", "(", "gettext", "(", "'Changed {fields} for {name} “{object}”.').fo", "r", "m", "at(", "", "*", "*", "sub_message", "[", "'changed'", "]", ")", ")", "else", ":", "messages", ".", "append", "(", "gettext", "(", "'Changed {fields}.'", ")", ".", "format", "(", "*", "*", "sub_message", "[", "'changed'", "]", ")", ")", "elif", "'deleted'", "in", "sub_message", ":", "sub_message", "[", "'deleted'", "]", "[", "'name'", "]", "=", "gettext", "(", "sub_message", "[", "'deleted'", "]", "[", "'name'", "]", ")", "messages", ".", "append", "(", "gettext", "(", "'Deleted {name} “{object}”.').fo", "r", "m", "at(**s", "u", "b", "_", "message['de", "l", "eted']))", "", "", "", "change_message", "=", "' '", ".", "join", "(", "msg", "[", "0", "]", ".", "upper", "(", ")", "+", "msg", "[", "1", ":", "]", "for", "msg", "in", "messages", ")", "return", "change_message", "or", "gettext", "(", "'No fields changed.'", ")", "else", ":", "return", "self", ".", "change_message" ]
[ 95, 4 ]
[ 133, 38 ]
python
en
['en', 'error', 'th']
False
LogEntry.get_edited_object
(self)
Return the edited object represented by this log entry.
Return the edited object represented by this log entry.
def get_edited_object(self): """Return the edited object represented by this log entry.""" return self.content_type.get_object_for_this_type(pk=self.object_id)
[ "def", "get_edited_object", "(", "self", ")", ":", "return", "self", ".", "content_type", ".", "get_object_for_this_type", "(", "pk", "=", "self", ".", "object_id", ")" ]
[ 135, 4 ]
[ 137, 76 ]
python
en
['en', 'en', 'en']
True
LogEntry.get_admin_url
(self)
Return the admin URL to edit the object represented by this log entry.
Return the admin URL to edit the object represented by this log entry.
def get_admin_url(self): """ Return the admin URL to edit the object represented by this log entry. """ if self.content_type and self.object_id: url_name = 'admin:%s_%s_change' % (self.content_type.app_label, self.content_type.model) try: return reverse(url_name, args=(quote(self.object_id),)) except NoReverseMatch: pass return None
[ "def", "get_admin_url", "(", "self", ")", ":", "if", "self", ".", "content_type", "and", "self", ".", "object_id", ":", "url_name", "=", "'admin:%s_%s_change'", "%", "(", "self", ".", "content_type", ".", "app_label", ",", "self", ".", "content_type", ".", "model", ")", "try", ":", "return", "reverse", "(", "url_name", ",", "args", "=", "(", "quote", "(", "self", ".", "object_id", ")", ",", ")", ")", "except", "NoReverseMatch", ":", "pass", "return", "None" ]
[ 139, 4 ]
[ 149, 19 ]
python
en
['en', 'error', 'th']
False
glibc_version_string
()
Returns glibc version string, or None if not using glibc.
Returns glibc version string, or None if not using glibc.
def glibc_version_string(): "Returns glibc version string, or None if not using glibc." # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure out # which libc our process is actually using. process_namespace = ctypes.CDLL(None) try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: # Symbol doesn't exist -> therefore, we are not linked to # glibc. return None # Call gnu_get_libc_version, which returns a string like "2.5" gnu_get_libc_version.restype = ctypes.c_char_p version_str = gnu_get_libc_version() # py2 / py3 compatibility: if not isinstance(version_str, str): version_str = version_str.decode("ascii") return version_str
[ "def", "glibc_version_string", "(", ")", ":", "# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen", "# manpage says, \"If filename is NULL, then the returned handle is for the", "# main program\". This way we can let the linker do the work to figure out", "# which libc our process is actually using.", "process_namespace", "=", "ctypes", ".", "CDLL", "(", "None", ")", "try", ":", "gnu_get_libc_version", "=", "process_namespace", ".", "gnu_get_libc_version", "except", "AttributeError", ":", "# Symbol doesn't exist -> therefore, we are not linked to", "# glibc.", "return", "None", "# Call gnu_get_libc_version, which returns a string like \"2.5\"", "gnu_get_libc_version", ".", "restype", "=", "ctypes", ".", "c_char_p", "version_str", "=", "gnu_get_libc_version", "(", ")", "# py2 / py3 compatibility:", "if", "not", "isinstance", "(", "version_str", ",", "str", ")", ":", "version_str", "=", "version_str", ".", "decode", "(", "\"ascii\"", ")", "return", "version_str" ]
[ 9, 0 ]
[ 31, 22 ]
python
en
['en', 'en', 'en']
True
libc_ver
()
Try to determine the glibc version Returns a tuple of strings (lib, version) which default to empty strings in case the lookup fails.
Try to determine the glibc version
def libc_ver(): """Try to determine the glibc version Returns a tuple of strings (lib, version) which default to empty strings in case the lookup fails. """ glibc_version = glibc_version_string() if glibc_version is None: return ("", "") else: return ("glibc", glibc_version)
[ "def", "libc_ver", "(", ")", ":", "glibc_version", "=", "glibc_version_string", "(", ")", "if", "glibc_version", "is", "None", ":", "return", "(", "\"\"", ",", "\"\"", ")", "else", ":", "return", "(", "\"glibc\"", ",", "glibc_version", ")" ]
[ 75, 0 ]
[ 85, 39 ]
python
en
['en', 'en', 'en']
True
handle_recording
()
Play back the caller's recording.
Play back the caller's recording.
def handle_recording(): """Play back the caller's recording.""" recording_url = request.values.get("RecordingUrl", None) resp = VoiceResponse() resp.say("Listen to your recorded message.") resp.play(recording_url) resp.say("Goodbye.") return str(resp)
[ "def", "handle_recording", "(", ")", ":", "recording_url", "=", "request", ".", "values", ".", "get", "(", "\"RecordingUrl\"", ",", "None", ")", "resp", "=", "VoiceResponse", "(", ")", "resp", ".", "say", "(", "\"Listen to your recorded message.\"", ")", "resp", ".", "play", "(", "recording_url", ")", "resp", ".", "say", "(", "\"Goodbye.\"", ")", "return", "str", "(", "resp", ")" ]
[ 8, 0 ]
[ 17, 20 ]
python
en
['en', 'en', 'en']
True
sms_reply
()
Respond to incoming calls with a simple text message.
Respond to incoming calls with a simple text message.
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Start our TwiML response resp = MessagingResponse() # Add a message resp.message("The Robots are coming! Head for the hills!") return str(resp)
[ "def", "sms_reply", "(", ")", ":", "# Start our TwiML response", "resp", "=", "MessagingResponse", "(", ")", "# Add a message", "resp", ".", "message", "(", "\"The Robots are coming! Head for the hills!\"", ")", "return", "str", "(", "resp", ")" ]
[ 6, 0 ]
[ 14, 20 ]
python
en
['en', 'en', 'en']
True
get_voice_twiml
()
Respond to incoming calls with a simple text message.
Respond to incoming calls with a simple text message.
def get_voice_twiml(): """Respond to incoming calls with a simple text message.""" resp = VoiceResponse() if "To" in request.form: resp.dial(request.form["To"], caller_id="+15017122661") else: resp.say("Thanks for calling!") return Response(str(resp), mimetype='text/xml')
[ "def", "get_voice_twiml", "(", ")", ":", "resp", "=", "VoiceResponse", "(", ")", "if", "\"To\"", "in", "request", ".", "form", ":", "resp", ".", "dial", "(", "request", ".", "form", "[", "\"To\"", "]", ",", "caller_id", "=", "\"+15017122661\"", ")", "else", ":", "resp", ".", "say", "(", "\"Thanks for calling!\"", ")", "return", "Response", "(", "str", "(", "resp", ")", ",", "mimetype", "=", "'text/xml'", ")" ]
[ 7, 0 ]
[ 16, 51 ]
python
en
['en', 'en', 'en']
True
PrettyHelpFormatter._format_option_strings
( self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", " )
Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') :param mvarfmt: metavar format string :param optsep: separator
Return a comma-separated list of option strings and metavars.
def _format_option_strings( self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", " ) -> str: """ Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') :param mvarfmt: metavar format string :param optsep: separator """ opts = [] if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if len(opts) > 1: opts.insert(1, optsep) if option.takes_value(): assert option.dest is not None metavar = option.metavar or option.dest.lower() opts.append(mvarfmt.format(metavar.lower())) return "".join(opts)
[ "def", "_format_option_strings", "(", "self", ",", "option", ":", "optparse", ".", "Option", ",", "mvarfmt", ":", "str", "=", "\" <{}>\"", ",", "optsep", ":", "str", "=", "\", \"", ")", "->", "str", ":", "opts", "=", "[", "]", "if", "option", ".", "_short_opts", ":", "opts", ".", "append", "(", "option", ".", "_short_opts", "[", "0", "]", ")", "if", "option", ".", "_long_opts", ":", "opts", ".", "append", "(", "option", ".", "_long_opts", "[", "0", "]", ")", "if", "len", "(", "opts", ")", ">", "1", ":", "opts", ".", "insert", "(", "1", ",", "optsep", ")", "if", "option", ".", "takes_value", "(", ")", ":", "assert", "option", ".", "dest", "is", "not", "None", "metavar", "=", "option", ".", "metavar", "or", "option", ".", "dest", ".", "lower", "(", ")", "opts", ".", "append", "(", "mvarfmt", ".", "format", "(", "metavar", ".", "lower", "(", ")", ")", ")", "return", "\"\"", ".", "join", "(", "opts", ")" ]
[ 30, 4 ]
[ 54, 28 ]
python
en
['en', 'error', 'th']
False
PrettyHelpFormatter.format_usage
(self, usage: str)
Ensure there is only one newline between usage and the first heading if there is no description.
Ensure there is only one newline between usage and the first heading if there is no description.
def format_usage(self, usage: str) -> str: """ Ensure there is only one newline between usage and the first heading if there is no description. """ msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " ")) return msg
[ "def", "format_usage", "(", "self", ",", "usage", ":", "str", ")", "->", "str", ":", "msg", "=", "\"\\nUsage: {}\\n\"", ".", "format", "(", "self", ".", "indent_lines", "(", "textwrap", ".", "dedent", "(", "usage", ")", ",", "\" \"", ")", ")", "return", "msg" ]
[ 61, 4 ]
[ 67, 18 ]
python
en
['en', 'error', 'th']
False
CustomOptionParser.insert_option_group
( self, idx: int, *args: Any, **kwargs: Any )
Insert an OptionGroup at a given position.
Insert an OptionGroup at a given position.
def insert_option_group( self, idx: int, *args: Any, **kwargs: Any ) -> optparse.OptionGroup: """Insert an OptionGroup at a given position.""" group = self.add_option_group(*args, **kwargs) self.option_groups.pop() self.option_groups.insert(idx, group) return group
[ "def", "insert_option_group", "(", "self", ",", "idx", ":", "int", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "optparse", ".", "OptionGroup", ":", "group", "=", "self", ".", "add_option_group", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "option_groups", ".", "pop", "(", ")", "self", ".", "option_groups", ".", "insert", "(", "idx", ",", "group", ")", "return", "group" ]
[ 132, 4 ]
[ 141, 20 ]
python
en
['en', 'en', 'en']
True
CustomOptionParser.option_list_all
(self)
Get a list of all options, including those in option groups.
Get a list of all options, including those in option groups.
def option_list_all(self) -> List[optparse.Option]: """Get a list of all options, including those in option groups.""" res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list) return res
[ "def", "option_list_all", "(", "self", ")", "->", "List", "[", "optparse", ".", "Option", "]", ":", "res", "=", "self", ".", "option_list", "[", ":", "]", "for", "i", "in", "self", ".", "option_groups", ":", "res", ".", "extend", "(", "i", ".", "option_list", ")", "return", "res" ]
[ 144, 4 ]
[ 150, 18 ]
python
en
['en', 'en', 'en']
True
ConfigOptionParser._update_defaults
(self, defaults: Dict[str, Any])
Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).
Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).
def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]: """Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).""" # Accumulate complex default state. self.values = optparse.Values(self.defaults) late_eval = set() # Then set the options with those values for key, val in self._get_ordered_configuration_items(): # '--' because configuration supports only long names option = self.get_option("--" + key) # Ignore options not present in this parser. E.g. non-globals put # in [global] by users that want them to apply to all applicable # commands. if option is None: continue assert option.dest is not None if option.action in ("store_true", "store_false"): try: val = strtobool(val) except ValueError: self.error( "{} is not a valid value for {} option, " # noqa "please specify a boolean value like yes/no, " "true/false or 1/0 instead.".format(val, key) ) elif option.action == "count": with suppress(ValueError): val = strtobool(val) with suppress(ValueError): val = int(val) if not isinstance(val, int) or val < 0: self.error( "{} is not a valid value for {} option, " # noqa "please instead specify either a non-negative integer " "or a boolean value like yes/no or false/true " "which is equivalent to 1/0.".format(val, key) ) elif option.action == "append": val = val.split() val = [self.check_default(option, key, v) for v in val] elif option.action == "callback": assert option.callback is not None late_eval.add(option.dest) opt_str = option.get_opt_string() val = option.convert_value(opt_str, val) # From take_action args = option.callback_args or () kwargs = option.callback_kwargs or {} option.callback(option, opt_str, val, self, *args, **kwargs) else: val = self.check_default(option, key, val) defaults[option.dest] = val for key in late_eval: defaults[key] = getattr(self.values, key) self.values = None return defaults
[ "def", "_update_defaults", "(", "self", ",", "defaults", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# Accumulate complex default state.", "self", ".", "values", "=", "optparse", ".", "Values", "(", "self", ".", "defaults", ")", "late_eval", "=", "set", "(", ")", "# Then set the options with those values", "for", "key", ",", "val", "in", "self", ".", "_get_ordered_configuration_items", "(", ")", ":", "# '--' because configuration supports only long names", "option", "=", "self", ".", "get_option", "(", "\"--\"", "+", "key", ")", "# Ignore options not present in this parser. E.g. non-globals put", "# in [global] by users that want them to apply to all applicable", "# commands.", "if", "option", "is", "None", ":", "continue", "assert", "option", ".", "dest", "is", "not", "None", "if", "option", ".", "action", "in", "(", "\"store_true\"", ",", "\"store_false\"", ")", ":", "try", ":", "val", "=", "strtobool", "(", "val", ")", "except", "ValueError", ":", "self", ".", "error", "(", "\"{} is not a valid value for {} option, \"", "# noqa", "\"please specify a boolean value like yes/no, \"", "\"true/false or 1/0 instead.\"", ".", "format", "(", "val", ",", "key", ")", ")", "elif", "option", ".", "action", "==", "\"count\"", ":", "with", "suppress", "(", "ValueError", ")", ":", "val", "=", "strtobool", "(", "val", ")", "with", "suppress", "(", "ValueError", ")", ":", "val", "=", "int", "(", "val", ")", "if", "not", "isinstance", "(", "val", ",", "int", ")", "or", "val", "<", "0", ":", "self", ".", "error", "(", "\"{} is not a valid value for {} option, \"", "# noqa", "\"please instead specify either a non-negative integer \"", "\"or a boolean value like yes/no or false/true \"", "\"which is equivalent to 1/0.\"", ".", "format", "(", "val", ",", "key", ")", ")", "elif", "option", ".", "action", "==", "\"append\"", ":", "val", "=", "val", ".", "split", "(", ")", "val", "=", "[", "self", ".", "check_default", "(", "option", ",", "key", ",", "v", ")", "for", "v", "in", "val", "]", "elif", "option", ".", "action", "==", "\"callback\"", ":", "assert", "option", ".", "callback", "is", "not", "None", "late_eval", ".", "add", "(", "option", ".", "dest", ")", "opt_str", "=", "option", ".", "get_opt_string", "(", ")", "val", "=", "option", ".", "convert_value", "(", "opt_str", ",", "val", ")", "# From take_action", "args", "=", "option", ".", "callback_args", "or", "(", ")", "kwargs", "=", "option", ".", "callback_kwargs", "or", "{", "}", "option", ".", "callback", "(", "option", ",", "opt_str", ",", "val", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "val", "=", "self", ".", "check_default", "(", "option", ",", "key", ",", "val", ")", "defaults", "[", "option", ".", "dest", "]", "=", "val", "for", "key", "in", "late_eval", ":", "defaults", "[", "key", "]", "=", "getattr", "(", "self", ".", "values", ",", "key", ")", "self", ".", "values", "=", "None", "return", "defaults" ]
[ 203, 4 ]
[ 265, 23 ]
python
en
['en', 'en', 'en']
True
ConfigOptionParser.get_default_values
(self)
Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.
Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.
def get_default_values(self) -> optparse.Values: """Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.""" if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return optparse.Values(self.defaults) # Load the configuration, or error out in case of an error try: self.config.load() except ConfigurationError as err: self.exit(UNKNOWN_ERROR, str(err)) defaults = self._update_defaults(self.defaults.copy()) # ours for option in self._get_all_options(): assert option.dest is not None default = defaults.get(option.dest) if isinstance(default, str): opt_str = option.get_opt_string() defaults[option.dest] = option.check_value(opt_str, default) return optparse.Values(defaults)
[ "def", "get_default_values", "(", "self", ")", "->", "optparse", ".", "Values", ":", "if", "not", "self", ".", "process_default_values", ":", "# Old, pre-Optik 1.5 behaviour.", "return", "optparse", ".", "Values", "(", "self", ".", "defaults", ")", "# Load the configuration, or error out in case of an error", "try", ":", "self", ".", "config", ".", "load", "(", ")", "except", "ConfigurationError", "as", "err", ":", "self", ".", "exit", "(", "UNKNOWN_ERROR", ",", "str", "(", "err", ")", ")", "defaults", "=", "self", ".", "_update_defaults", "(", "self", ".", "defaults", ".", "copy", "(", ")", ")", "# ours", "for", "option", "in", "self", ".", "_get_all_options", "(", ")", ":", "assert", "option", ".", "dest", "is", "not", "None", "default", "=", "defaults", ".", "get", "(", "option", ".", "dest", ")", "if", "isinstance", "(", "default", ",", "str", ")", ":", "opt_str", "=", "option", ".", "get_opt_string", "(", ")", "defaults", "[", "option", ".", "dest", "]", "=", "option", ".", "check_value", "(", "opt_str", ",", "default", ")", "return", "optparse", ".", "Values", "(", "defaults", ")" ]
[ 267, 4 ]
[ 287, 40 ]
python
en
['en', 'en', 'en']
True
_xml_escape
(data)
Escape &, <, >, ", ', etc. in a string of data.
Escape &, <, >, ", ', etc. in a string of data.
def _xml_escape(data): """Escape &, <, >, ", ', etc. in a string of data.""" # ampersand must be replaced first from_symbols = '&><"\'' to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split()) for from_,to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) return data
[ "def", "_xml_escape", "(", "data", ")", ":", "# ampersand must be replaced first\r", "from_symbols", "=", "'&><\"\\''", "to_symbols", "=", "(", "'&'", "+", "s", "+", "';'", "for", "s", "in", "\"amp gt lt quot apos\"", ".", "split", "(", ")", ")", "for", "from_", ",", "to_", "in", "zip", "(", "from_symbols", ",", "to_symbols", ")", ":", "data", "=", "data", ".", "replace", "(", "from_", ",", "to_", ")", "return", "data" ]
[ 161, 0 ]
[ 169, 15 ]
python
en
['en', 'en', 'en']
True
col
(loc,strg)
Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string.
Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string.
def col (loc,strg): """Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. """ s = strg return 1 if 0<loc<len(s) and s[loc-1] == '\n' else loc - s.rfind("\n", 0, loc)
[ "def", "col", "(", "loc", ",", "strg", ")", ":", "s", "=", "strg", "return", "1", "if", "0", "<", "loc", "<", "len", "(", "s", ")", "and", "s", "[", "loc", "-", "1", "]", "==", "'\\n'", "else", "loc", "-", "s", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "loc", ")" ]
[ 944, 0 ]
[ 955, 82 ]
python
en
['en', 'en', 'en']
True
lineno
(loc,strg)
Returns current line number within a string, counting newlines as line separators. The first line is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string.
Returns current line number within a string, counting newlines as line separators. The first line is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string.
def lineno(loc,strg): """Returns current line number within a string, counting newlines as line separators. The first line is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. """ return strg.count("\n",0,loc) + 1
[ "def", "lineno", "(", "loc", ",", "strg", ")", ":", "return", "strg", ".", "count", "(", "\"\\n\"", ",", "0", ",", "loc", ")", "+", "1" ]
[ 957, 0 ]
[ 967, 37 ]
python
en
['en', 'en', 'en']
True
line
( loc, strg )
Returns the line of text containing loc within a string, counting newlines as line separators.
Returns the line of text containing loc within a string, counting newlines as line separators.
def line( loc, strg ): """Returns the line of text containing loc within a string, counting newlines as line separators. """ lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR+1:nextCR] else: return strg[lastCR+1:]
[ "def", "line", "(", "loc", ",", "strg", ")", ":", "lastCR", "=", "strg", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "loc", ")", "nextCR", "=", "strg", ".", "find", "(", "\"\\n\"", ",", "loc", ")", "if", "nextCR", ">=", "0", ":", "return", "strg", "[", "lastCR", "+", "1", ":", "nextCR", "]", "else", ":", "return", "strg", "[", "lastCR", "+", "1", ":", "]" ]
[ 969, 0 ]
[ 977, 30 ]
python
en
['en', 'en', 'en']
True
nullDebugAction
(*args)
Do-nothing' debug action, to suppress debugging output during parsing.
Do-nothing' debug action, to suppress debugging output during parsing.
def nullDebugAction(*args): """'Do-nothing' debug action, to suppress debugging output during parsing.""" pass
[ "def", "nullDebugAction", "(", "*", "args", ")", ":", "pass" ]
[ 988, 0 ]
[ 990, 8 ]
python
en
['en', 'jv', 'en']
True
ParseBaseException._from_exception
(cls, pe)
internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses
internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses
def _from_exception(cls, pe): """ internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses """ return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
[ "def", "_from_exception", "(", "cls", ",", "pe", ")", ":", "return", "cls", "(", "pe", ".", "pstr", ",", "pe", ".", "loc", ",", "pe", ".", "msg", ",", "pe", ".", "parserElement", ")" ]
[ 197, 4 ]
[ 202, 61 ]
python
en
['en', 'ja', 'th']
False
ParseBaseException.__getattr__
( self, aname )
supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text
supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text
def __getattr__( self, aname ): """supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text """ if( aname == "lineno" ): return lineno( self.loc, self.pstr ) elif( aname in ("col", "column") ): return col( self.loc, self.pstr ) elif( aname == "line" ): return line( self.loc, self.pstr ) else: raise AttributeError(aname)
[ "def", "__getattr__", "(", "self", ",", "aname", ")", ":", "if", "(", "aname", "==", "\"lineno\"", ")", ":", "return", "lineno", "(", "self", ".", "loc", ",", "self", ".", "pstr", ")", "elif", "(", "aname", "in", "(", "\"col\"", ",", "\"column\"", ")", ")", ":", "return", "col", "(", "self", ".", "loc", ",", "self", ".", "pstr", ")", "elif", "(", "aname", "==", "\"line\"", ")", ":", "return", "line", "(", "self", ".", "loc", ",", "self", ".", "pstr", ")", "else", ":", "raise", "AttributeError", "(", "aname", ")" ]
[ 204, 4 ]
[ 217, 39 ]
python
en
['en', 'en', 'en']
True
ParseBaseException.markInputline
( self, markerString = ">!<" )
Extracts the exception line from the input string, and marks the location of the exception with a special symbol.
Extracts the exception line from the input string, and marks the location of the exception with a special symbol.
def markInputline( self, markerString = ">!<" ): """Extracts the exception line from the input string, and marks the location of the exception with a special symbol. """ line_str = self.line line_column = self.column - 1 if markerString: line_str = "".join((line_str[:line_column], markerString, line_str[line_column:])) return line_str.strip()
[ "def", "markInputline", "(", "self", ",", "markerString", "=", "\">!<\"", ")", ":", "line_str", "=", "self", ".", "line", "line_column", "=", "self", ".", "column", "-", "1", "if", "markerString", ":", "line_str", "=", "\"\"", ".", "join", "(", "(", "line_str", "[", ":", "line_column", "]", ",", "markerString", ",", "line_str", "[", "line_column", ":", "]", ")", ")", "return", "line_str", ".", "strip", "(", ")" ]
[ 224, 4 ]
[ 233, 31 ]
python
en
['en', 'en', 'en']
True
ParseResults.haskeys
( self )
Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.
Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.
def haskeys( self ): """Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.""" return bool(self.__tokdict)
[ "def", "haskeys", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "__tokdict", ")" ]
[ 482, 4 ]
[ 485, 35 ]
python
en
['en', 'en', 'en']
True
ParseResults.pop
( self, *args, **kwargs)
Removes and returns item at specified index (default=C{last}). Supports both C{list} and C{dict} semantics for C{pop()}. If passed no argument or an integer argument, it will use C{list} semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use C{dict} semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in C{dict.pop()}. Example:: def remove_first(tokens): tokens.pop(0) print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + OneOrMore(Word(nums)) print(patt.parseString("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.addParseAction(remove_LABEL) print(patt.parseString("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: AAB ['AAB', '123', '321']
Removes and returns item at specified index (default=C{last}). Supports both C{list} and C{dict} semantics for C{pop()}. If passed no argument or an integer argument, it will use C{list} semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use C{dict} semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in C{dict.pop()}. Example:: def remove_first(tokens): tokens.pop(0) print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + OneOrMore(Word(nums)) print(patt.parseString("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.addParseAction(remove_LABEL) print(patt.parseString("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: AAB ['AAB', '123', '321']
def pop( self, *args, **kwargs): """ Removes and returns item at specified index (default=C{last}). Supports both C{list} and C{dict} semantics for C{pop()}. If passed no argument or an integer argument, it will use C{list} semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use C{dict} semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in C{dict.pop()}. Example:: def remove_first(tokens): tokens.pop(0) print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + OneOrMore(Word(nums)) print(patt.parseString("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.addParseAction(remove_LABEL) print(patt.parseString("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: AAB ['AAB', '123', '321'] """ if not args: args = [-1] for k,v in kwargs.items(): if k == 'default': args = (args[0], v) else: raise TypeError("pop() got an unexpected keyword argument '%s'" % k) if (isinstance(args[0], int) or len(args) == 1 or args[0] in self): index = args[0] ret = self[index] del self[index] return ret else: defaultvalue = args[1] return defaultvalue
[ "def", "pop", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "args", ":", "args", "=", "[", "-", "1", "]", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "==", "'default'", ":", "args", "=", "(", "args", "[", "0", "]", ",", "v", ")", "else", ":", "raise", "TypeError", "(", "\"pop() got an unexpected keyword argument '%s'\"", "%", "k", ")", "if", "(", "isinstance", "(", "args", "[", "0", "]", ",", "int", ")", "or", "len", "(", "args", ")", "==", "1", "or", "args", "[", "0", "]", "in", "self", ")", ":", "index", "=", "args", "[", "0", "]", "ret", "=", "self", "[", "index", "]", "del", "self", "[", "index", "]", "return", "ret", "else", ":", "defaultvalue", "=", "args", "[", "1", "]", "return", "defaultvalue" ]
[ 487, 4 ]
[ 537, 31 ]
python
en
['en', 'ja', 'th']
False
ParseResults.get
(self, key, defaultValue=None)
Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None
Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None
def get(self, key, defaultValue=None): """ Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None """ if key in self: return self[key] else: return defaultValue
[ "def", "get", "(", "self", ",", "key", ",", "defaultValue", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", "[", "key", "]", "else", ":", "return", "defaultValue" ]
[ 539, 4 ]
[ 559, 31 ]
python
en
['en', 'ja', 'th']
False
ParseResults.insert
( self, index, insStr )
Inserts new element at location index in the list of parsed tokens. Similar to C{list.insert()}. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to insert the parse location in the front of the parsed results def insert_locn(locn, tokens): tokens.insert(0, locn) print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
Inserts new element at location index in the list of parsed tokens. Similar to C{list.insert()}. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to insert the parse location in the front of the parsed results def insert_locn(locn, tokens): tokens.insert(0, locn) print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
def insert( self, index, insStr ): """ Inserts new element at location index in the list of parsed tokens. Similar to C{list.insert()}. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to insert the parse location in the front of the parsed results def insert_locn(locn, tokens): tokens.insert(0, locn) print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321'] """ self.__toklist.insert(index, insStr) # fixup indices in token dictionary for name,occurrences in self.__tokdict.items(): for k, (value, position) in enumerate(occurrences): occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
[ "def", "insert", "(", "self", ",", "index", ",", "insStr", ")", ":", "self", ".", "__toklist", ".", "insert", "(", "index", ",", "insStr", ")", "# fixup indices in token dictionary\r", "for", "name", ",", "occurrences", "in", "self", ".", "__tokdict", ".", "items", "(", ")", ":", "for", "k", ",", "(", "value", ",", "position", ")", "in", "enumerate", "(", "occurrences", ")", ":", "occurrences", "[", "k", "]", "=", "_ParseResultsWithOffset", "(", "value", ",", "position", "+", "(", "position", ">", "index", ")", ")" ]
[ 561, 4 ]
[ 579, 94 ]
python
en
['en', 'ja', 'th']
False
ParseResults.append
( self, item )
Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
def append( self, item ): """ Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] """ self.__toklist.append(item)
[ "def", "append", "(", "self", ",", "item", ")", ":", "self", ".", "__toklist", ".", "append", "(", "item", ")" ]
[ 581, 4 ]
[ 593, 35 ]
python
en
['en', 'ja', 'th']
False
ParseResults.extend
( self, itemseq )
Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([t[::-1] for t in tokens])) return ''.join(tokens) print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([t[::-1] for t in tokens])) return ''.join(tokens) print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
def extend( self, itemseq ): """ Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([t[::-1] for t in tokens])) return ''.join(tokens) print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' """ if isinstance(itemseq, ParseResults): self += itemseq else: self.__toklist.extend(itemseq)
[ "def", "extend", "(", "self", ",", "itemseq", ")", ":", "if", "isinstance", "(", "itemseq", ",", "ParseResults", ")", ":", "self", "+=", "itemseq", "else", ":", "self", ".", "__toklist", ".", "extend", "(", "itemseq", ")" ]
[ 595, 4 ]
[ 611, 42 ]
python
en
['en', 'ja', 'th']
False
ParseResults.clear
( self )
Clear all elements and results names.
Clear all elements and results names.
def clear( self ): """ Clear all elements and results names. """ del self.__toklist[:] self.__tokdict.clear()
[ "def", "clear", "(", "self", ")", ":", "del", "self", ".", "__toklist", "[", ":", "]", "self", ".", "__tokdict", ".", "clear", "(", ")" ]
[ 613, 4 ]
[ 618, 30 ]
python
en
['en', 'ja', 'th']
False
ParseResults.asList
( self )
Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj'] # Use asList() to create an actual list result_list = result.asList() print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj'] # Use asList() to create an actual list result_list = result.asList() print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
def asList( self ): """ Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj'] # Use asList() to create an actual list result_list = result.asList() print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj'] """ return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist]
[ "def", "asList", "(", "self", ")", ":", "return", "[", "res", ".", "asList", "(", ")", "if", "isinstance", "(", "res", ",", "ParseResults", ")", "else", "res", "for", "res", "in", "self", ".", "__toklist", "]" ]
[ 680, 4 ]
[ 694, 96 ]
python
en
['en', 'ja', 'th']
False
ParseResults.asDict
( self )
Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.asDict() print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.asDict() print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
def asDict( self ): """ Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.asDict() print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} """ if PY_3: item_fn = self.items else: item_fn = self.iteritems def toItem(obj): if isinstance(obj, ParseResults): if obj.haskeys(): return obj.asDict() else: return [toItem(v) for v in obj] else: return obj return dict((k,toItem(v)) for k,v in item_fn())
[ "def", "asDict", "(", "self", ")", ":", "if", "PY_3", ":", "item_fn", "=", "self", ".", "items", "else", ":", "item_fn", "=", "self", ".", "iteritems", "def", "toItem", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "ParseResults", ")", ":", "if", "obj", ".", "haskeys", "(", ")", ":", "return", "obj", ".", "asDict", "(", ")", "else", ":", "return", "[", "toItem", "(", "v", ")", "for", "v", "in", "obj", "]", "else", ":", "return", "obj", "return", "dict", "(", "(", "k", ",", "toItem", "(", "v", ")", ")", "for", "k", ",", "v", "in", "item_fn", "(", ")", ")" ]
[ 696, 4 ]
[ 729, 55 ]
python
en
['en', 'ja', 'th']
False
ParseResults.copy
( self )
Returns a new copy of a C{ParseResults} object.
Returns a new copy of a C{ParseResults} object.
def copy( self ): """ Returns a new copy of a C{ParseResults} object. """ ret = ParseResults( self.__toklist ) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update( self.__accumNames ) ret.__name = self.__name return ret
[ "def", "copy", "(", "self", ")", ":", "ret", "=", "ParseResults", "(", "self", ".", "__toklist", ")", "ret", ".", "__tokdict", "=", "self", ".", "__tokdict", ".", "copy", "(", ")", "ret", ".", "__parent", "=", "self", ".", "__parent", "ret", ".", "__accumNames", ".", "update", "(", "self", ".", "__accumNames", ")", "ret", ".", "__name", "=", "self", ".", "__name", "return", "ret" ]
[ 731, 4 ]
[ 740, 18 ]
python
en
['en', 'ja', 'th']
False
ParseResults.asXML
( self, doctag=None, namedItemsOnly=False, indent="", formatted=True )
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ): """ (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. """ nl = "\n" out = [] namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items() for v in vlist) nextLevelIndent = indent + " " # collapse out indents if formatting is not desired if not formatted: indent = "" nextLevelIndent = "" nl = "" selfTag = None if doctag is not None: selfTag = doctag else: if self.__name: selfTag = self.__name if not selfTag: if namedItemsOnly: return "" else: selfTag = "ITEM" out += [ nl, indent, "<", selfTag, ">" ] for i,res in enumerate(self.__toklist): if isinstance(res,ParseResults): if i in namedItems: out += [ res.asXML(namedItems[i], namedItemsOnly and doctag is None, nextLevelIndent, formatted)] else: out += [ res.asXML(None, namedItemsOnly and doctag is None, nextLevelIndent, formatted)] else: # individual token, see if there is a name for it resTag = None if i in namedItems: resTag = namedItems[i] if not resTag: if namedItemsOnly: continue else: resTag = "ITEM" xmlBodyText = _xml_escape(_ustr(res)) out += [ nl, nextLevelIndent, "<", resTag, ">", xmlBodyText, "</", resTag, ">" ] out += [ nl, indent, "</", selfTag, ">" ] return "".join(out)
[ "def", "asXML", "(", "self", ",", "doctag", "=", "None", ",", "namedItemsOnly", "=", "False", ",", "indent", "=", "\"\"", ",", "formatted", "=", "True", ")", ":", "nl", "=", "\"\\n\"", "out", "=", "[", "]", "namedItems", "=", "dict", "(", "(", "v", "[", "1", "]", ",", "k", ")", "for", "(", "k", ",", "vlist", ")", "in", "self", ".", "__tokdict", ".", "items", "(", ")", "for", "v", "in", "vlist", ")", "nextLevelIndent", "=", "indent", "+", "\" \"", "# collapse out indents if formatting is not desired\r", "if", "not", "formatted", ":", "indent", "=", "\"\"", "nextLevelIndent", "=", "\"\"", "nl", "=", "\"\"", "selfTag", "=", "None", "if", "doctag", "is", "not", "None", ":", "selfTag", "=", "doctag", "else", ":", "if", "self", ".", "__name", ":", "selfTag", "=", "self", ".", "__name", "if", "not", "selfTag", ":", "if", "namedItemsOnly", ":", "return", "\"\"", "else", ":", "selfTag", "=", "\"ITEM\"", "out", "+=", "[", "nl", ",", "indent", ",", "\"<\"", ",", "selfTag", ",", "\">\"", "]", "for", "i", ",", "res", "in", "enumerate", "(", "self", ".", "__toklist", ")", ":", "if", "isinstance", "(", "res", ",", "ParseResults", ")", ":", "if", "i", "in", "namedItems", ":", "out", "+=", "[", "res", ".", "asXML", "(", "namedItems", "[", "i", "]", ",", "namedItemsOnly", "and", "doctag", "is", "None", ",", "nextLevelIndent", ",", "formatted", ")", "]", "else", ":", "out", "+=", "[", "res", ".", "asXML", "(", "None", ",", "namedItemsOnly", "and", "doctag", "is", "None", ",", "nextLevelIndent", ",", "formatted", ")", "]", "else", ":", "# individual token, see if there is a name for it\r", "resTag", "=", "None", "if", "i", "in", "namedItems", ":", "resTag", "=", "namedItems", "[", "i", "]", "if", "not", "resTag", ":", "if", "namedItemsOnly", ":", "continue", "else", ":", "resTag", "=", "\"ITEM\"", "xmlBodyText", "=", "_xml_escape", "(", "_ustr", "(", "res", ")", ")", "out", "+=", "[", "nl", ",", "nextLevelIndent", ",", "\"<\"", ",", "resTag", ",", "\">\"", ",", "xmlBodyText", ",", "\"</\"", ",", "resTag", ",", "\">\"", "]", "out", "+=", "[", "nl", ",", "indent", ",", "\"</\"", ",", "selfTag", ",", "\">\"", "]", "return", "\"\"", ".", "join", "(", "out", ")" ]
[ 742, 4 ]
[ 801, 27 ]
python
en
['en', 'ja', 'th']
False
ParseResults.getName
(self)
Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example:: integer = Word(nums) ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") house_number_expr = Suppress('#') + Word(nums, alphanums) user_data = (Group(house_number_expr)("house_number") | Group(ssn_expr)("ssn") | Group(integer)("age")) user_info = OneOrMore(user_data) result = user_info.parseString("22 111-22-3333 #221B") for item in result: print(item.getName(), ':', item[0]) prints:: age : 22 ssn : 111-22-3333 house_number : 221B
Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example:: integer = Word(nums) ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") house_number_expr = Suppress('#') + Word(nums, alphanums) user_data = (Group(house_number_expr)("house_number") | Group(ssn_expr)("ssn") | Group(integer)("age")) user_info = OneOrMore(user_data) result = user_info.parseString("22 111-22-3333 #221B") for item in result: print(item.getName(), ':', item[0]) prints:: age : 22 ssn : 111-22-3333 house_number : 221B
def getName(self): """ Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example:: integer = Word(nums) ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") house_number_expr = Suppress('#') + Word(nums, alphanums) user_data = (Group(house_number_expr)("house_number") | Group(ssn_expr)("ssn") | Group(integer)("age")) user_info = OneOrMore(user_data) result = user_info.parseString("22 111-22-3333 #221B") for item in result: print(item.getName(), ':', item[0]) prints:: age : 22 ssn : 111-22-3333 house_number : 221B """ if self.__name: return self.__name elif self.__parent: par = self.__parent() if par: return par.__lookup(self) else: return None elif (len(self) == 1 and len(self.__tokdict) == 1 and next(iter(self.__tokdict.values()))[0][1] in (0,-1)): return next(iter(self.__tokdict.keys())) else: return None
[ "def", "getName", "(", "self", ")", ":", "if", "self", ".", "__name", ":", "return", "self", ".", "__name", "elif", "self", ".", "__parent", ":", "par", "=", "self", ".", "__parent", "(", ")", "if", "par", ":", "return", "par", ".", "__lookup", "(", "self", ")", "else", ":", "return", "None", "elif", "(", "len", "(", "self", ")", "==", "1", "and", "len", "(", "self", ".", "__tokdict", ")", "==", "1", "and", "next", "(", "iter", "(", "self", ".", "__tokdict", ".", "values", "(", ")", ")", ")", "[", "0", "]", "[", "1", "]", "in", "(", "0", ",", "-", "1", ")", ")", ":", "return", "next", "(", "iter", "(", "self", ".", "__tokdict", ".", "keys", "(", ")", ")", ")", "else", ":", "return", "None" ]
[ 810, 4 ]
[ 845, 23 ]
python
en
['en', 'ja', 'th']
False
ParseResults.dump
(self, indent='', depth=0, full=True)
Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(result.dump()) prints:: ['12', '/', '31', '/', '1999'] - day: 1999 - month: 31 - year: 12
Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(result.dump()) prints:: ['12', '/', '31', '/', '1999'] - day: 1999 - month: 31 - year: 12
def dump(self, indent='', depth=0, full=True): """ Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(result.dump()) prints:: ['12', '/', '31', '/', '1999'] - day: 1999 - month: 31 - year: 12 """ out = [] NL = '\n' out.append( indent+_ustr(self.asList()) ) if full: if self.haskeys(): items = sorted((str(k), v) for k,v in self.items()) for k,v in items: if out: out.append(NL) out.append( "%s%s- %s: " % (indent,(' '*depth), k) ) if isinstance(v,ParseResults): if v: out.append( v.dump(indent,depth+1) ) else: out.append(_ustr(v)) else: out.append(repr(v)) elif any(isinstance(vv,ParseResults) for vv in self): v = self for i,vv in enumerate(v): if isinstance(vv,ParseResults): out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),vv.dump(indent,depth+1) )) else: out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),_ustr(vv))) return "".join(out)
[ "def", "dump", "(", "self", ",", "indent", "=", "''", ",", "depth", "=", "0", ",", "full", "=", "True", ")", ":", "out", "=", "[", "]", "NL", "=", "'\\n'", "out", ".", "append", "(", "indent", "+", "_ustr", "(", "self", ".", "asList", "(", ")", ")", ")", "if", "full", ":", "if", "self", ".", "haskeys", "(", ")", ":", "items", "=", "sorted", "(", "(", "str", "(", "k", ")", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ")", "for", "k", ",", "v", "in", "items", ":", "if", "out", ":", "out", ".", "append", "(", "NL", ")", "out", ".", "append", "(", "\"%s%s- %s: \"", "%", "(", "indent", ",", "(", "' '", "*", "depth", ")", ",", "k", ")", ")", "if", "isinstance", "(", "v", ",", "ParseResults", ")", ":", "if", "v", ":", "out", ".", "append", "(", "v", ".", "dump", "(", "indent", ",", "depth", "+", "1", ")", ")", "else", ":", "out", ".", "append", "(", "_ustr", "(", "v", ")", ")", "else", ":", "out", ".", "append", "(", "repr", "(", "v", ")", ")", "elif", "any", "(", "isinstance", "(", "vv", ",", "ParseResults", ")", "for", "vv", "in", "self", ")", ":", "v", "=", "self", "for", "i", ",", "vv", "in", "enumerate", "(", "v", ")", ":", "if", "isinstance", "(", "vv", ",", "ParseResults", ")", ":", "out", ".", "append", "(", "\"\\n%s%s[%d]:\\n%s%s%s\"", "%", "(", "indent", ",", "(", "' '", "*", "(", "depth", ")", ")", ",", "i", ",", "indent", ",", "(", "' '", "*", "(", "depth", "+", "1", ")", ")", ",", "vv", ".", "dump", "(", "indent", ",", "depth", "+", "1", ")", ")", ")", "else", ":", "out", ".", "append", "(", "\"\\n%s%s[%d]:\\n%s%s%s\"", "%", "(", "indent", ",", "(", "' '", "*", "(", "depth", ")", ")", ",", "i", ",", "indent", ",", "(", "' '", "*", "(", "depth", "+", "1", ")", ")", ",", "_ustr", "(", "vv", ")", ")", ")", "return", "\"\"", ".", "join", "(", "out", ")" ]
[ 847, 4 ]
[ 890, 27 ]
python
en
['en', 'ja', 'th']
False
ParseResults.pprint
(self, *args, **kwargs)
Pretty-printer for parsed results as a list, using the C{pprint} module. Accepts additional positional or keyword args as defined for the C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint}) Example:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(delimitedList(term))) result = func.parseString("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']]
Pretty-printer for parsed results as a list, using the C{pprint} module. Accepts additional positional or keyword args as defined for the C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint}) Example:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(delimitedList(term))) result = func.parseString("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']]
def pprint(self, *args, **kwargs): """ Pretty-printer for parsed results as a list, using the C{pprint} module. Accepts additional positional or keyword args as defined for the C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint}) Example:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(delimitedList(term))) result = func.parseString("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']] """ pprint.pprint(self.asList(), *args, **kwargs)
[ "def", "pprint", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pprint", ".", "pprint", "(", "self", ".", "asList", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 892, 4 ]
[ 913, 53 ]
python
en
['en', 'ja', 'th']
False
ParserElement.setDefaultWhitespaceChars
( chars )
r""" Overrides the default whitespace chars Example:: # default whitespace chars are space, <TAB> and newline OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.setDefaultWhitespaceChars(" \t") OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
r""" Overrides the default whitespace chars Example:: # default whitespace chars are space, <TAB> and newline OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.setDefaultWhitespaceChars(" \t") OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
def setDefaultWhitespaceChars( chars ): r""" Overrides the default whitespace chars Example:: # default whitespace chars are space, <TAB> and newline OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.setDefaultWhitespaceChars(" \t") OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] """ ParserElement.DEFAULT_WHITE_CHARS = chars
[ "def", "setDefaultWhitespaceChars", "(", "chars", ")", ":", "ParserElement", ".", "DEFAULT_WHITE_CHARS", "=", "chars" ]
[ 1085, 4 ]
[ 1097, 49 ]
python
cy
['en', 'cy', 'hi']
False
ParserElement.inlineLiteralsUsing
(cls)
Set class to be used for inclusion of string literals into a parser. Example:: # default literal class used is Literal integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inlineLiteralsUsing(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
Set class to be used for inclusion of string literals into a parser. Example:: # default literal class used is Literal integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inlineLiteralsUsing(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
def inlineLiteralsUsing(cls): """ Set class to be used for inclusion of string literals into a parser. Example:: # default literal class used is Literal integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inlineLiteralsUsing(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '12', '31'] """ ParserElement._literalStringClass = cls
[ "def", "inlineLiteralsUsing", "(", "cls", ")", ":", "ParserElement", ".", "_literalStringClass", "=", "cls" ]
[ 1100, 4 ]
[ 1118, 47 ]
python
en
['en', 'ja', 'th']
False
ParserElement.copy
( self )
Make a copy of this C{ParserElement}. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K") integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) prints:: [5120, 100, 655360, 268435456] Equivalent form of C{expr.copy()} is just C{expr()}:: integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
Make a copy of this C{ParserElement}. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K") integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) prints:: [5120, 100, 655360, 268435456] Equivalent form of C{expr.copy()} is just C{expr()}:: integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
def copy( self ): """ Make a copy of this C{ParserElement}. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K") integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) prints:: [5120, 100, 655360, 268435456] Equivalent form of C{expr.copy()} is just C{expr()}:: integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") """ cpy = copy.copy( self ) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS return cpy
[ "def", "copy", "(", "self", ")", ":", "cpy", "=", "copy", ".", "copy", "(", "self", ")", "cpy", ".", "parseAction", "=", "self", ".", "parseAction", "[", ":", "]", "cpy", ".", "ignoreExprs", "=", "self", ".", "ignoreExprs", "[", ":", "]", "if", "self", ".", "copyDefaultWhiteChars", ":", "cpy", ".", "whiteChars", "=", "ParserElement", ".", "DEFAULT_WHITE_CHARS", "return", "cpy" ]
[ 1143, 4 ]
[ 1164, 18 ]
python
en
['en', 'ja', 'th']
False
ParserElement.setName
( self, name )
Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
def setName( self, name ): """ Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) """ self.name = name self.errmsg = "Expected " + self.name if hasattr(self,"exception"): self.exception.msg = self.errmsg return self
[ "def", "setName", "(", "self", ",", "name", ")", ":", "self", ".", "name", "=", "name", "self", ".", "errmsg", "=", "\"Expected \"", "+", "self", ".", "name", "if", "hasattr", "(", "self", ",", "\"exception\"", ")", ":", "self", ".", "exception", ".", "msg", "=", "self", ".", "errmsg", "return", "self" ]
[ 1166, 4 ]
[ 1178, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.setResultsName
( self, name, listAllMatches=False )
Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
def setResultsName( self, name, listAllMatches=False ): """ Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day") """ newself = self.copy() if name.endswith("*"): name = name[:-1] listAllMatches=True newself.resultsName = name newself.modalResults = not listAllMatches return newself
[ "def", "setResultsName", "(", "self", ",", "name", ",", "listAllMatches", "=", "False", ")", ":", "newself", "=", "self", ".", "copy", "(", ")", "if", "name", ".", "endswith", "(", "\"*\"", ")", ":", "name", "=", "name", "[", ":", "-", "1", "]", "listAllMatches", "=", "True", "newself", ".", "resultsName", "=", "name", "newself", ".", "modalResults", "=", "not", "listAllMatches", "return", "newself" ]
[ 1180, 4 ]
[ 1206, 22 ]
python
en
['en', 'ja', 'th']
False
ParserElement.setBreak
(self,breakFlag = True)
Method to invoke the Python pdb debugger when this element is about to be parsed. Set C{breakFlag} to True to enable, False to disable.
Method to invoke the Python pdb debugger when this element is about to be parsed. Set C{breakFlag} to True to enable, False to disable.
def setBreak(self,breakFlag = True): """Method to invoke the Python pdb debugger when this element is about to be parsed. Set C{breakFlag} to True to enable, False to disable. """ if breakFlag: _parseMethod = self._parse def breaker(instring, loc, doActions=True, callPreParse=True): import pdb pdb.set_trace() return _parseMethod( instring, loc, doActions, callPreParse ) breaker._originalParseMethod = _parseMethod self._parse = breaker else: if hasattr(self._parse,"_originalParseMethod"): self._parse = self._parse._originalParseMethod return self
[ "def", "setBreak", "(", "self", ",", "breakFlag", "=", "True", ")", ":", "if", "breakFlag", ":", "_parseMethod", "=", "self", ".", "_parse", "def", "breaker", "(", "instring", ",", "loc", ",", "doActions", "=", "True", ",", "callPreParse", "=", "True", ")", ":", "import", "pdb", "pdb", ".", "set_trace", "(", ")", "return", "_parseMethod", "(", "instring", ",", "loc", ",", "doActions", ",", "callPreParse", ")", "breaker", ".", "_originalParseMethod", "=", "_parseMethod", "self", ".", "_parse", "=", "breaker", "else", ":", "if", "hasattr", "(", "self", ".", "_parse", ",", "\"_originalParseMethod\"", ")", ":", "self", ".", "_parse", "=", "self", ".", "_parse", ".", "_originalParseMethod", "return", "self" ]
[ 1208, 4 ]
[ 1224, 19 ]
python
en
['en', 'en', 'en']
True
ParserElement.setParseAction
( self, *fns, **kwargs )
Define action to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
Define action to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
def setParseAction( self, *fns, **kwargs ): """ Define action to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] """ self.parseAction = list(map(_trim_arity, list(fns))) self.callDuringTry = kwargs.get("callDuringTry", False) return self
[ "def", "setParseAction", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parseAction", "=", "list", "(", "map", "(", "_trim_arity", ",", "list", "(", "fns", ")", ")", ")", "self", ".", "callDuringTry", "=", "kwargs", ".", "get", "(", "\"callDuringTry\"", ",", "False", ")", "return", "self" ]
[ 1226, 4 ]
[ 1262, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.addParseAction
( self, *fns, **kwargs )
Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}. See examples in L{I{copy}<copy>}.
Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}. See examples in L{I{copy}<copy>}.
def addParseAction( self, *fns, **kwargs ): """ Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}. See examples in L{I{copy}<copy>}. """ self.parseAction += list(map(_trim_arity, list(fns))) self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) return self
[ "def", "addParseAction", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parseAction", "+=", "list", "(", "map", "(", "_trim_arity", ",", "list", "(", "fns", ")", ")", ")", "self", ".", "callDuringTry", "=", "self", ".", "callDuringTry", "or", "kwargs", ".", "get", "(", "\"callDuringTry\"", ",", "False", ")", "return", "self" ]
[ 1264, 4 ]
[ 1272, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.addCondition
(self, *fns, **kwargs)
Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) year_int = integer.copy() year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) year_int = integer.copy() year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
def addCondition(self, *fns, **kwargs): """Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) year_int = integer.copy() year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) """ msg = kwargs.get("message", "failed user-defined condition") exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException for fn in fns: def pa(s,l,t): if not bool(_trim_arity(fn)(s,l,t)): raise exc_type(s,l,msg) self.parseAction.append(pa) self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) return self
[ "def", "addCondition", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "kwargs", ".", "get", "(", "\"message\"", ",", "\"failed user-defined condition\"", ")", "exc_type", "=", "ParseFatalException", "if", "kwargs", ".", "get", "(", "\"fatal\"", ",", "False", ")", "else", "ParseException", "for", "fn", "in", "fns", ":", "def", "pa", "(", "s", ",", "l", ",", "t", ")", ":", "if", "not", "bool", "(", "_trim_arity", "(", "fn", ")", "(", "s", ",", "l", ",", "t", ")", ")", ":", "raise", "exc_type", "(", "s", ",", "l", ",", "msg", ")", "self", ".", "parseAction", ".", "append", "(", "pa", ")", "self", ".", "callDuringTry", "=", "self", ".", "callDuringTry", "or", "kwargs", ".", "get", "(", "\"callDuringTry\"", ",", "False", ")", "return", "self" ]
[ 1274, 4 ]
[ 1299, 19 ]
python
en
['en', 'en', 'en']
True
ParserElement.setFailAction
( self, fn )
Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments C{fn(s,loc,expr,err)} where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw C{L{ParseFatalException}} if it is desired to stop parsing immediately.
Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments C{fn(s,loc,expr,err)} where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw C{L{ParseFatalException}} if it is desired to stop parsing immediately.
def setFailAction( self, fn ): """Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments C{fn(s,loc,expr,err)} where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw C{L{ParseFatalException}} if it is desired to stop parsing immediately.""" self.failAction = fn return self
[ "def", "setFailAction", "(", "self", ",", "fn", ")", ":", "self", ".", "failAction", "=", "fn", "return", "self" ]
[ 1301, 4 ]
[ 1312, 19 ]
python
en
['en', 'en', 'en']
True
ParserElement.enablePackrat
(cache_size_limit=128)
Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. Parameters: - cache_size_limit - (default=C{128}) - if an integer value is provided will limit the size of the packrat cache; if None is passed, then the cache size will be unbounded; if 0 is passed, the cache will be effectively disabled. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method C{ParserElement.enablePackrat()}. If your program uses C{psyco} to "compile as you go", you must call C{enablePackrat} before calling C{psyco.full()}. If you do not do this, Python will crash. For best results, call C{enablePackrat()} immediately after importing pyparsing. Example:: import pyparsing pyparsing.ParserElement.enablePackrat()
Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. Parameters: - cache_size_limit - (default=C{128}) - if an integer value is provided will limit the size of the packrat cache; if None is passed, then the cache size will be unbounded; if 0 is passed, the cache will be effectively disabled. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method C{ParserElement.enablePackrat()}. If your program uses C{psyco} to "compile as you go", you must call C{enablePackrat} before calling C{psyco.full()}. If you do not do this, Python will crash. For best results, call C{enablePackrat()} immediately after importing pyparsing. Example:: import pyparsing pyparsing.ParserElement.enablePackrat()
def enablePackrat(cache_size_limit=128): """Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. Parameters: - cache_size_limit - (default=C{128}) - if an integer value is provided will limit the size of the packrat cache; if None is passed, then the cache size will be unbounded; if 0 is passed, the cache will be effectively disabled. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method C{ParserElement.enablePackrat()}. If your program uses C{psyco} to "compile as you go", you must call C{enablePackrat} before calling C{psyco.full()}. If you do not do this, Python will crash. For best results, call C{enablePackrat()} immediately after importing pyparsing. Example:: import pyparsing pyparsing.ParserElement.enablePackrat() """ if not ParserElement._packratEnabled: ParserElement._packratEnabled = True if cache_size_limit is None: ParserElement.packrat_cache = ParserElement._UnboundedCache() else: ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit) ParserElement._parse = ParserElement._parseCache
[ "def", "enablePackrat", "(", "cache_size_limit", "=", "128", ")", ":", "if", "not", "ParserElement", ".", "_packratEnabled", ":", "ParserElement", ".", "_packratEnabled", "=", "True", "if", "cache_size_limit", "is", "None", ":", "ParserElement", ".", "packrat_cache", "=", "ParserElement", ".", "_UnboundedCache", "(", ")", "else", ":", "ParserElement", ".", "packrat_cache", "=", "ParserElement", ".", "_FifoCache", "(", "cache_size_limit", ")", "ParserElement", ".", "_parse", "=", "ParserElement", ".", "_parseCache" ]
[ 1536, 4 ]
[ 1568, 60 ]
python
en
['en', 'en', 'en']
True
ParserElement.parseString
( self, instring, parseAll=False )
Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be successfully parsed, then set C{parseAll} to True (equivalent to ending the grammar with C{L{StringEnd()}}). Note: C{parseString} implicitly calls C{expandtabs()} on the input string, in order to report proper column numbers in parse actions. If the input string contains tabs and the grammar uses parse actions that use the C{loc} argument to index into the string being parsed, you can ensure you have a consistent view of the input string by: - calling C{parseWithTabs} on your grammar before calling C{parseString} (see L{I{parseWithTabs}<parseWithTabs>}) - define your parse action using the full C{(s,loc,toks)} signature, and reference the input string using the parse action's C{s} argument - explictly expand the tabs in your input string before calling C{parseString} Example:: Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be successfully parsed, then set C{parseAll} to True (equivalent to ending the grammar with C{L{StringEnd()}}). Note: C{parseString} implicitly calls C{expandtabs()} on the input string, in order to report proper column numbers in parse actions. If the input string contains tabs and the grammar uses parse actions that use the C{loc} argument to index into the string being parsed, you can ensure you have a consistent view of the input string by: - calling C{parseWithTabs} on your grammar before calling C{parseString} (see L{I{parseWithTabs}<parseWithTabs>}) - define your parse action using the full C{(s,loc,toks)} signature, and reference the input string using the parse action's C{s} argument - explictly expand the tabs in your input string before calling C{parseString} Example:: Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
def parseString( self, instring, parseAll=False ): """ Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be successfully parsed, then set C{parseAll} to True (equivalent to ending the grammar with C{L{StringEnd()}}). Note: C{parseString} implicitly calls C{expandtabs()} on the input string, in order to report proper column numbers in parse actions. If the input string contains tabs and the grammar uses parse actions that use the C{loc} argument to index into the string being parsed, you can ensure you have a consistent view of the input string by: - calling C{parseWithTabs} on your grammar before calling C{parseString} (see L{I{parseWithTabs}<parseWithTabs>}) - define your parse action using the full C{(s,loc,toks)} signature, and reference the input string using the parse action's C{s} argument - explictly expand the tabs in your input string before calling C{parseString} Example:: Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text """ ParserElement.resetCache() if not self.streamlined: self.streamline() #~ self.saveAsList = True for e in self.ignoreExprs: e.streamline() if not self.keepTabs: instring = instring.expandtabs() try: loc, tokens = self._parse( instring, 0 ) if parseAll: loc = self.preParse( instring, loc ) se = Empty() + StringEnd() se._parse( instring, loc ) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc else: return tokens
[ "def", "parseString", "(", "self", ",", "instring", ",", "parseAll", "=", "False", ")", ":", "ParserElement", ".", "resetCache", "(", ")", "if", "not", "self", ".", "streamlined", ":", "self", ".", "streamline", "(", ")", "#~ self.saveAsList = True\r", "for", "e", "in", "self", ".", "ignoreExprs", ":", "e", ".", "streamline", "(", ")", "if", "not", "self", ".", "keepTabs", ":", "instring", "=", "instring", ".", "expandtabs", "(", ")", "try", ":", "loc", ",", "tokens", "=", "self", ".", "_parse", "(", "instring", ",", "0", ")", "if", "parseAll", ":", "loc", "=", "self", ".", "preParse", "(", "instring", ",", "loc", ")", "se", "=", "Empty", "(", ")", "+", "StringEnd", "(", ")", "se", ".", "_parse", "(", "instring", ",", "loc", ")", "except", "ParseBaseException", "as", "exc", ":", "if", "ParserElement", ".", "verbose_stacktrace", ":", "raise", "else", ":", "# catch and re-raise exception from here, clears out pyparsing internal stack trace\r", "raise", "exc", "else", ":", "return", "tokens" ]
[ 1570, 4 ]
[ 1618, 25 ]
python
en
['en', 'ja', 'th']
False
ParserElement.scanString
( self, instring, maxMatches=_MAX_INT, overlap=False )
Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional C{maxMatches} argument, to clip scanning after 'n' matches are found. If C{overlap} is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See L{I{parseString}<parseString>} for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens,start,end in Word(alphas).scanString(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd
Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional C{maxMatches} argument, to clip scanning after 'n' matches are found. If C{overlap} is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See L{I{parseString}<parseString>} for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens,start,end in Word(alphas).scanString(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd
def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ): """ Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional C{maxMatches} argument, to clip scanning after 'n' matches are found. If C{overlap} is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See L{I{parseString}<parseString>} for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens,start,end in Word(alphas).scanString(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd """ if not self.streamlined: self.streamline() for e in self.ignoreExprs: e.streamline() if not self.keepTabs: instring = _ustr(instring).expandtabs() instrlen = len(instring) loc = 0 preparseFn = self.preParse parseFn = self._parse ParserElement.resetCache() matches = 0 try: while loc <= instrlen and matches < maxMatches: try: preloc = preparseFn( instring, loc ) nextLoc,tokens = parseFn( instring, preloc, callPreParse=False ) except ParseException: loc = preloc+1 else: if nextLoc > loc: matches += 1 yield tokens, preloc, nextLoc if overlap: nextloc = preparseFn( instring, loc ) if nextloc > loc: loc = nextLoc else: loc += 1 else: loc = nextLoc else: loc = preloc+1 except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc
[ "def", "scanString", "(", "self", ",", "instring", ",", "maxMatches", "=", "_MAX_INT", ",", "overlap", "=", "False", ")", ":", "if", "not", "self", ".", "streamlined", ":", "self", ".", "streamline", "(", ")", "for", "e", "in", "self", ".", "ignoreExprs", ":", "e", ".", "streamline", "(", ")", "if", "not", "self", ".", "keepTabs", ":", "instring", "=", "_ustr", "(", "instring", ")", ".", "expandtabs", "(", ")", "instrlen", "=", "len", "(", "instring", ")", "loc", "=", "0", "preparseFn", "=", "self", ".", "preParse", "parseFn", "=", "self", ".", "_parse", "ParserElement", ".", "resetCache", "(", ")", "matches", "=", "0", "try", ":", "while", "loc", "<=", "instrlen", "and", "matches", "<", "maxMatches", ":", "try", ":", "preloc", "=", "preparseFn", "(", "instring", ",", "loc", ")", "nextLoc", ",", "tokens", "=", "parseFn", "(", "instring", ",", "preloc", ",", "callPreParse", "=", "False", ")", "except", "ParseException", ":", "loc", "=", "preloc", "+", "1", "else", ":", "if", "nextLoc", ">", "loc", ":", "matches", "+=", "1", "yield", "tokens", ",", "preloc", ",", "nextLoc", "if", "overlap", ":", "nextloc", "=", "preparseFn", "(", "instring", ",", "loc", ")", "if", "nextloc", ">", "loc", ":", "loc", "=", "nextLoc", "else", ":", "loc", "+=", "1", "else", ":", "loc", "=", "nextLoc", "else", ":", "loc", "=", "preloc", "+", "1", "except", "ParseBaseException", "as", "exc", ":", "if", "ParserElement", ".", "verbose_stacktrace", ":", "raise", "else", ":", "# catch and re-raise exception from here, clears out pyparsing internal stack trace\r", "raise", "exc" ]
[ 1620, 4 ]
[ 1689, 25 ]
python
en
['en', 'ja', 'th']
False
ParserElement.transformString
( self, instring )
Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
def transformString( self, instring ): """ Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. """ out = [] lastE = 0 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to # keep string locs straight between transformString and scanString self.keepTabs = True try: for t,s,e in self.scanString( instring ): out.append( instring[lastE:s] ) if t: if isinstance(t,ParseResults): out += t.asList() elif isinstance(t,list): out += t else: out.append(t) lastE = e out.append(instring[lastE:]) out = [o for o in out if o] return "".join(map(_ustr,_flatten(out))) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc
[ "def", "transformString", "(", "self", ",", "instring", ")", ":", "out", "=", "[", "]", "lastE", "=", "0", "# force preservation of <TAB>s, to minimize unwanted transformation of string, and to\r", "# keep string locs straight between transformString and scanString\r", "self", ".", "keepTabs", "=", "True", "try", ":", "for", "t", ",", "s", ",", "e", "in", "self", ".", "scanString", "(", "instring", ")", ":", "out", ".", "append", "(", "instring", "[", "lastE", ":", "s", "]", ")", "if", "t", ":", "if", "isinstance", "(", "t", ",", "ParseResults", ")", ":", "out", "+=", "t", ".", "asList", "(", ")", "elif", "isinstance", "(", "t", ",", "list", ")", ":", "out", "+=", "t", "else", ":", "out", ".", "append", "(", "t", ")", "lastE", "=", "e", "out", ".", "append", "(", "instring", "[", "lastE", ":", "]", ")", "out", "=", "[", "o", "for", "o", "in", "out", "if", "o", "]", "return", "\"\"", ".", "join", "(", "map", "(", "_ustr", ",", "_flatten", "(", "out", ")", ")", ")", "except", "ParseBaseException", "as", "exc", ":", "if", "ParserElement", ".", "verbose_stacktrace", ":", "raise", "else", ":", "# catch and re-raise exception from here, clears out pyparsing internal stack trace\r", "raise", "exc" ]
[ 1691, 4 ]
[ 1732, 25 ]
python
en
['en', 'ja', 'th']
False
ParserElement.searchString
( self, instring, maxMatches=_MAX_INT )
Another extension to C{L{scanString}}, simplifying the access to the tokens found to match the given parse expression. May be called with optional C{maxMatches} argument, to clip searching after 'n' matches are found. Example:: # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters cap_word = Word(alphas.upper(), alphas.lower()) print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) prints:: ['More', 'Iron', 'Lead', 'Gold', 'I']
Another extension to C{L{scanString}}, simplifying the access to the tokens found to match the given parse expression. May be called with optional C{maxMatches} argument, to clip searching after 'n' matches are found. Example:: # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters cap_word = Word(alphas.upper(), alphas.lower()) print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) prints:: ['More', 'Iron', 'Lead', 'Gold', 'I']
def searchString( self, instring, maxMatches=_MAX_INT ): """ Another extension to C{L{scanString}}, simplifying the access to the tokens found to match the given parse expression. May be called with optional C{maxMatches} argument, to clip searching after 'n' matches are found. Example:: # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters cap_word = Word(alphas.upper(), alphas.lower()) print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) prints:: ['More', 'Iron', 'Lead', 'Gold', 'I'] """ try: return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ]) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc
[ "def", "searchString", "(", "self", ",", "instring", ",", "maxMatches", "=", "_MAX_INT", ")", ":", "try", ":", "return", "ParseResults", "(", "[", "t", "for", "t", ",", "s", ",", "e", "in", "self", ".", "scanString", "(", "instring", ",", "maxMatches", ")", "]", ")", "except", "ParseBaseException", "as", "exc", ":", "if", "ParserElement", ".", "verbose_stacktrace", ":", "raise", "else", ":", "# catch and re-raise exception from here, clears out pyparsing internal stack trace\r", "raise", "exc" ]
[ 1734, 4 ]
[ 1755, 25 ]
python
en
['en', 'ja', 'th']
False
ParserElement.split
(self, instring, maxsplit=_MAX_INT, includeSeparators=False)
Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): """ Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] """ splits = 0 last = 0 for t,s,e in self.scanString(instring, maxMatches=maxsplit): yield instring[last:s] if includeSeparators: yield t[0] last = e yield instring[last:]
[ "def", "split", "(", "self", ",", "instring", ",", "maxsplit", "=", "_MAX_INT", ",", "includeSeparators", "=", "False", ")", ":", "splits", "=", "0", "last", "=", "0", "for", "t", ",", "s", ",", "e", "in", "self", ".", "scanString", "(", "instring", ",", "maxMatches", "=", "maxsplit", ")", ":", "yield", "instring", "[", "last", ":", "s", "]", "if", "includeSeparators", ":", "yield", "t", "[", "0", "]", "last", "=", "e", "yield", "instring", "[", "last", ":", "]" ]
[ 1757, 4 ]
[ 1777, 29 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__add__
(self, other )
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!']
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!']
def __add__(self, other ): """ Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!'] """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And( [ self, other ] )
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "And", "(", "[", "self", ",", "other", "]", ")" ]
[ 1779, 4 ]
[ 1797, 37 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__radd__
(self, other )
Implementation of + operator when left operand is not a C{L{ParserElement}}
Implementation of + operator when left operand is not a C{L{ParserElement}}
def __radd__(self, other ): """ Implementation of + operator when left operand is not a C{L{ParserElement}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other + self
[ "def", "__radd__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "other", "+", "self" ]
[ 1799, 4 ]
[ 1809, 27 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__sub__
(self, other)
Implementation of - operator, returns C{L{And}} with error stop
Implementation of - operator, returns C{L{And}} with error stop
def __sub__(self, other): """ Implementation of - operator, returns C{L{And}} with error stop """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And( [ self, And._ErrorStop(), other ] )
[ "def", "__sub__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "And", "(", "[", "self", ",", "And", ".", "_ErrorStop", "(", ")", ",", "other", "]", ")" ]
[ 1811, 4 ]
[ 1821, 55 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__rsub__
(self, other )
Implementation of - operator when left operand is not a C{L{ParserElement}}
Implementation of - operator when left operand is not a C{L{ParserElement}}
def __rsub__(self, other ): """ Implementation of - operator when left operand is not a C{L{ParserElement}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other - self
[ "def", "__rsub__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "other", "-", "self" ]
[ 1823, 4 ]
[ 1833, 27 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__mul__
(self,other)
Implementation of * operator, allows use of C{expr * 3} in place of C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples may also include C{None} as in: - C{expr*(n,None)} or C{expr*(n,)} is equivalent to C{expr*n + L{ZeroOrMore}(expr)} (read as "at least n instances of C{expr}") - C{expr*(None,n)} is equivalent to C{expr*(0,n)} (read as "0 to n instances of C{expr}") - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)} - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} Note that C{expr*(None,n)} does not raise an exception if more than n exprs exist in the input stream; that is, C{expr*(None,n)} does not enforce a maximum number of expr occurrences. If this behavior is desired, then write C{expr*(None,n) + ~expr}
Implementation of * operator, allows use of C{expr * 3} in place of C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples may also include C{None} as in: - C{expr*(n,None)} or C{expr*(n,)} is equivalent to C{expr*n + L{ZeroOrMore}(expr)} (read as "at least n instances of C{expr}") - C{expr*(None,n)} is equivalent to C{expr*(0,n)} (read as "0 to n instances of C{expr}") - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)} - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} Note that C{expr*(None,n)} does not raise an exception if more than n exprs exist in the input stream; that is, C{expr*(None,n)} does not enforce a maximum number of expr occurrences. If this behavior is desired, then write C{expr*(None,n) + ~expr}
def __mul__(self,other): """ Implementation of * operator, allows use of C{expr * 3} in place of C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples may also include C{None} as in: - C{expr*(n,None)} or C{expr*(n,)} is equivalent to C{expr*n + L{ZeroOrMore}(expr)} (read as "at least n instances of C{expr}") - C{expr*(None,n)} is equivalent to C{expr*(0,n)} (read as "0 to n instances of C{expr}") - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)} - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} Note that C{expr*(None,n)} does not raise an exception if more than n exprs exist in the input stream; that is, C{expr*(None,n)} does not enforce a maximum number of expr occurrences. If this behavior is desired, then write C{expr*(None,n) + ~expr} """ if isinstance(other,int): minElements, optElements = other,0 elif isinstance(other,tuple): other = (other + (None, None))[:2] if other[0] is None: other = (0, other[1]) if isinstance(other[0],int) and other[1] is None: if other[0] == 0: return ZeroOrMore(self) if other[0] == 1: return OneOrMore(self) else: return self*other[0] + ZeroOrMore(self) elif isinstance(other[0],int) and isinstance(other[1],int): minElements, optElements = other optElements -= minElements else: raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1])) else: raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other)) if minElements < 0: raise ValueError("cannot multiply ParserElement by negative value") if optElements < 0: raise ValueError("second tuple value must be greater or equal to first tuple value") if minElements == optElements == 0: raise ValueError("cannot multiply ParserElement by 0 or (0,0)") if (optElements): def makeOptionalList(n): if n>1: return Optional(self + makeOptionalList(n-1)) else: return Optional(self) if minElements: if minElements == 1: ret = self + makeOptionalList(optElements) else: ret = And([self]*minElements) + makeOptionalList(optElements) else: ret = makeOptionalList(optElements) else: if minElements == 1: ret = self else: ret = And([self]*minElements) return ret
[ "def", "__mul__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "int", ")", ":", "minElements", ",", "optElements", "=", "other", ",", "0", "elif", "isinstance", "(", "other", ",", "tuple", ")", ":", "other", "=", "(", "other", "+", "(", "None", ",", "None", ")", ")", "[", ":", "2", "]", "if", "other", "[", "0", "]", "is", "None", ":", "other", "=", "(", "0", ",", "other", "[", "1", "]", ")", "if", "isinstance", "(", "other", "[", "0", "]", ",", "int", ")", "and", "other", "[", "1", "]", "is", "None", ":", "if", "other", "[", "0", "]", "==", "0", ":", "return", "ZeroOrMore", "(", "self", ")", "if", "other", "[", "0", "]", "==", "1", ":", "return", "OneOrMore", "(", "self", ")", "else", ":", "return", "self", "*", "other", "[", "0", "]", "+", "ZeroOrMore", "(", "self", ")", "elif", "isinstance", "(", "other", "[", "0", "]", ",", "int", ")", "and", "isinstance", "(", "other", "[", "1", "]", ",", "int", ")", ":", "minElements", ",", "optElements", "=", "other", "optElements", "-=", "minElements", "else", ":", "raise", "TypeError", "(", "\"cannot multiply 'ParserElement' and ('%s','%s') objects\"", ",", "type", "(", "other", "[", "0", "]", ")", ",", "type", "(", "other", "[", "1", "]", ")", ")", "else", ":", "raise", "TypeError", "(", "\"cannot multiply 'ParserElement' and '%s' objects\"", ",", "type", "(", "other", ")", ")", "if", "minElements", "<", "0", ":", "raise", "ValueError", "(", "\"cannot multiply ParserElement by negative value\"", ")", "if", "optElements", "<", "0", ":", "raise", "ValueError", "(", "\"second tuple value must be greater or equal to first tuple value\"", ")", "if", "minElements", "==", "optElements", "==", "0", ":", "raise", "ValueError", "(", "\"cannot multiply ParserElement by 0 or (0,0)\"", ")", "if", "(", "optElements", ")", ":", "def", "makeOptionalList", "(", "n", ")", ":", "if", "n", ">", "1", ":", "return", "Optional", "(", "self", "+", "makeOptionalList", "(", "n", "-", "1", ")", ")", "else", ":", "return", "Optional", "(", "self", ")", "if", "minElements", ":", "if", "minElements", "==", "1", ":", "ret", "=", "self", "+", "makeOptionalList", "(", "optElements", ")", "else", ":", "ret", "=", "And", "(", "[", "self", "]", "*", "minElements", ")", "+", "makeOptionalList", "(", "optElements", ")", "else", ":", "ret", "=", "makeOptionalList", "(", "optElements", ")", "else", ":", "if", "minElements", "==", "1", ":", "ret", "=", "self", "else", ":", "ret", "=", "And", "(", "[", "self", "]", "*", "minElements", ")", "return", "ret" ]
[ 1835, 4 ]
[ 1901, 18 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__or__
(self, other )
Implementation of | operator - returns C{L{MatchFirst}}
Implementation of | operator - returns C{L{MatchFirst}}
def __or__(self, other ): """ Implementation of | operator - returns C{L{MatchFirst}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return MatchFirst( [ self, other ] )
[ "def", "__or__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "MatchFirst", "(", "[", "self", ",", "other", "]", ")" ]
[ 1906, 4 ]
[ 1916, 44 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__ror__
(self, other )
Implementation of | operator when left operand is not a C{L{ParserElement}}
Implementation of | operator when left operand is not a C{L{ParserElement}}
def __ror__(self, other ): """ Implementation of | operator when left operand is not a C{L{ParserElement}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other | self
[ "def", "__ror__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "other", "|", "self" ]
[ 1918, 4 ]
[ 1928, 27 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__xor__
(self, other )
Implementation of ^ operator - returns C{L{Or}}
Implementation of ^ operator - returns C{L{Or}}
def __xor__(self, other ): """ Implementation of ^ operator - returns C{L{Or}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return Or( [ self, other ] )
[ "def", "__xor__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "Or", "(", "[", "self", ",", "other", "]", ")" ]
[ 1930, 4 ]
[ 1940, 36 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__rxor__
(self, other )
Implementation of ^ operator when left operand is not a C{L{ParserElement}}
Implementation of ^ operator when left operand is not a C{L{ParserElement}}
def __rxor__(self, other ): """ Implementation of ^ operator when left operand is not a C{L{ParserElement}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other ^ self
[ "def", "__rxor__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "other", "^", "self" ]
[ 1942, 4 ]
[ 1952, 27 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__and__
(self, other )
Implementation of & operator - returns C{L{Each}}
Implementation of & operator - returns C{L{Each}}
def __and__(self, other ): """ Implementation of & operator - returns C{L{Each}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return Each( [ self, other ] )
[ "def", "__and__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "Each", "(", "[", "self", ",", "other", "]", ")" ]
[ 1954, 4 ]
[ 1964, 38 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__rand__
(self, other )
Implementation of & operator when left operand is not a C{L{ParserElement}}
Implementation of & operator when left operand is not a C{L{ParserElement}}
def __rand__(self, other ): """ Implementation of & operator when left operand is not a C{L{ParserElement}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other & self
[ "def", "__rand__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "other", "&", "self" ]
[ 1966, 4 ]
[ 1976, 27 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__invert__
( self )
Implementation of ~ operator - returns C{L{NotAny}}
Implementation of ~ operator - returns C{L{NotAny}}
def __invert__( self ): """ Implementation of ~ operator - returns C{L{NotAny}} """ return NotAny( self )
[ "def", "__invert__", "(", "self", ")", ":", "return", "NotAny", "(", "self", ")" ]
[ 1978, 4 ]
[ 1982, 29 ]
python
en
['en', 'ja', 'th']
False
ParserElement.__call__
(self, name=None)
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
def __call__(self, name=None): """ Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") """ if name is not None: return self.setResultsName(name) else: return self.copy()
[ "def", "__call__", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "not", "None", ":", "return", "self", ".", "setResultsName", "(", "name", ")", "else", ":", "return", "self", ".", "copy", "(", ")" ]
[ 1984, 4 ]
[ 2001, 30 ]
python
en
['en', 'ja', 'th']
False
ParserElement.suppress
( self )
Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output.
Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output.
def suppress( self ): """ Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output. """ return Suppress( self )
[ "def", "suppress", "(", "self", ")", ":", "return", "Suppress", "(", "self", ")" ]
[ 2003, 4 ]
[ 2008, 31 ]
python
en
['en', 'ja', 'th']
False
ParserElement.leaveWhitespace
( self )
Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars.
Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars.
def leaveWhitespace( self ): """ Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. """ self.skipWhitespace = False return self
[ "def", "leaveWhitespace", "(", "self", ")", ":", "self", ".", "skipWhitespace", "=", "False", "return", "self" ]
[ 2010, 4 ]
[ 2017, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.setWhitespaceChars
( self, chars )
Overrides the default whitespace chars
Overrides the default whitespace chars
def setWhitespaceChars( self, chars ): """ Overrides the default whitespace chars """ self.skipWhitespace = True self.whiteChars = chars self.copyDefaultWhiteChars = False return self
[ "def", "setWhitespaceChars", "(", "self", ",", "chars", ")", ":", "self", ".", "skipWhitespace", "=", "True", "self", ".", "whiteChars", "=", "chars", "self", ".", "copyDefaultWhiteChars", "=", "False", "return", "self" ]
[ 2019, 4 ]
[ 2026, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.parseWithTabs
( self )
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string. Must be called before C{parseString} when the input grammar contains elements that match C{<TAB>} characters.
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string. Must be called before C{parseString} when the input grammar contains elements that match C{<TAB>} characters.
def parseWithTabs( self ): """ Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string. Must be called before C{parseString} when the input grammar contains elements that match C{<TAB>} characters. """ self.keepTabs = True return self
[ "def", "parseWithTabs", "(", "self", ")", ":", "self", ".", "keepTabs", "=", "True", "return", "self" ]
[ 2028, 4 ]
[ 2035, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.ignore
( self, other )
Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. Example:: patt = OneOrMore(Word(alphas)) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] patt.ignore(cStyleComment) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. Example:: patt = OneOrMore(Word(alphas)) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] patt.ignore(cStyleComment) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
def ignore( self, other ): """ Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. Example:: patt = OneOrMore(Word(alphas)) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] patt.ignore(cStyleComment) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] """ if isinstance(other, basestring): other = Suppress(other) if isinstance( other, Suppress ): if other not in self.ignoreExprs: self.ignoreExprs.append(other) else: self.ignoreExprs.append( Suppress( other.copy() ) ) return self
[ "def", "ignore", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "Suppress", "(", "other", ")", "if", "isinstance", "(", "other", ",", "Suppress", ")", ":", "if", "other", "not", "in", "self", ".", "ignoreExprs", ":", "self", ".", "ignoreExprs", ".", "append", "(", "other", ")", "else", ":", "self", ".", "ignoreExprs", ".", "append", "(", "Suppress", "(", "other", ".", "copy", "(", ")", ")", ")", "return", "self" ]
[ 2037, 4 ]
[ 2058, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.setDebugActions
( self, startAction, successAction, exceptionAction )
Enable display of debugging messages while doing pattern matching.
Enable display of debugging messages while doing pattern matching.
def setDebugActions( self, startAction, successAction, exceptionAction ): """ Enable display of debugging messages while doing pattern matching. """ self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) self.debug = True return self
[ "def", "setDebugActions", "(", "self", ",", "startAction", ",", "successAction", ",", "exceptionAction", ")", ":", "self", ".", "debugActions", "=", "(", "startAction", "or", "_defaultStartDebugAction", ",", "successAction", "or", "_defaultSuccessDebugAction", ",", "exceptionAction", "or", "_defaultExceptionDebugAction", ")", "self", ".", "debug", "=", "True", "return", "self" ]
[ 2060, 4 ]
[ 2068, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.setDebug
( self, flag=True )
Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = wd | integer # turn on debugging for wd wd.setDebug() OneOrMore(term).parseString("abc 123 xyz 890") prints:: Match alphaword at loc 0(1,1) Matched alphaword -> ['abc'] Match alphaword at loc 3(1,4) Exception raised:Expected alphaword (at char 4), (line:1, col:5) Match alphaword at loc 7(1,8) Matched alphaword -> ['xyz'] Match alphaword at loc 11(1,12) Exception raised:Expected alphaword (at char 12), (line:1, col:13) Match alphaword at loc 15(1,16) Exception raised:Expected alphaword (at char 15), (line:1, col:16) The output shown is that produced by the default debug actions - custom debug actions can be specified using L{setDebugActions}. Prior to attempting to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"} is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, which makes debugging and exception messages easier to understand - for instance, the default name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = wd | integer # turn on debugging for wd wd.setDebug() OneOrMore(term).parseString("abc 123 xyz 890") prints:: Match alphaword at loc 0(1,1) Matched alphaword -> ['abc'] Match alphaword at loc 3(1,4) Exception raised:Expected alphaword (at char 4), (line:1, col:5) Match alphaword at loc 7(1,8) Matched alphaword -> ['xyz'] Match alphaword at loc 11(1,12) Exception raised:Expected alphaword (at char 12), (line:1, col:13) Match alphaword at loc 15(1,16) Exception raised:Expected alphaword (at char 15), (line:1, col:16) The output shown is that produced by the default debug actions - custom debug actions can be specified using L{setDebugActions}. Prior to attempting to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"} is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, which makes debugging and exception messages easier to understand - for instance, the default name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
def setDebug( self, flag=True ): """ Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = wd | integer # turn on debugging for wd wd.setDebug() OneOrMore(term).parseString("abc 123 xyz 890") prints:: Match alphaword at loc 0(1,1) Matched alphaword -> ['abc'] Match alphaword at loc 3(1,4) Exception raised:Expected alphaword (at char 4), (line:1, col:5) Match alphaword at loc 7(1,8) Matched alphaword -> ['xyz'] Match alphaword at loc 11(1,12) Exception raised:Expected alphaword (at char 12), (line:1, col:13) Match alphaword at loc 15(1,16) Exception raised:Expected alphaword (at char 15), (line:1, col:16) The output shown is that produced by the default debug actions - custom debug actions can be specified using L{setDebugActions}. Prior to attempting to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"} is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, which makes debugging and exception messages easier to understand - for instance, the default name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}. """ if flag: self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction ) else: self.debug = False return self
[ "def", "setDebug", "(", "self", ",", "flag", "=", "True", ")", ":", "if", "flag", ":", "self", ".", "setDebugActions", "(", "_defaultStartDebugAction", ",", "_defaultSuccessDebugAction", ",", "_defaultExceptionDebugAction", ")", "else", ":", "self", ".", "debug", "=", "False", "return", "self" ]
[ 2070, 4 ]
[ 2109, 19 ]
python
en
['en', 'ja', 'th']
False
ParserElement.validate
( self, validateTrace=[] )
Check defined expressions for valid structure, check for infinite recursive definitions.
Check defined expressions for valid structure, check for infinite recursive definitions.
def validate( self, validateTrace=[] ): """ Check defined expressions for valid structure, check for infinite recursive definitions. """ self.checkRecursion( [] )
[ "def", "validate", "(", "self", ",", "validateTrace", "=", "[", "]", ")", ":", "self", ".", "checkRecursion", "(", "[", "]", ")" ]
[ 2125, 4 ]
[ 2129, 33 ]
python
en
['en', 'ja', 'th']
False
ParserElement.parseFile
( self, file_or_filename, parseAll=False )
Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing.
Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing.
def parseFile( self, file_or_filename, parseAll=False ): """ Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. """ try: file_contents = file_or_filename.read() except AttributeError: with open(file_or_filename, "r") as f: file_contents = f.read() try: return self.parseString(file_contents, parseAll) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc
[ "def", "parseFile", "(", "self", ",", "file_or_filename", ",", "parseAll", "=", "False", ")", ":", "try", ":", "file_contents", "=", "file_or_filename", ".", "read", "(", ")", "except", "AttributeError", ":", "with", "open", "(", "file_or_filename", ",", "\"r\"", ")", "as", "f", ":", "file_contents", "=", "f", ".", "read", "(", ")", "try", ":", "return", "self", ".", "parseString", "(", "file_contents", ",", "parseAll", ")", "except", "ParseBaseException", "as", "exc", ":", "if", "ParserElement", ".", "verbose_stacktrace", ":", "raise", "else", ":", "# catch and re-raise exception from here, clears out pyparsing internal stack trace\r", "raise", "exc" ]
[ 2131, 4 ]
[ 2149, 25 ]
python
en
['en', 'ja', 'th']
False
ParserElement.matches
(self, testString, parseAll=True)
Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - testString - to test against this expression for a match - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests Example:: expr = Word(nums) assert expr.matches("100")
Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - testString - to test against this expression for a match - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests Example:: expr = Word(nums) assert expr.matches("100")
def matches(self, testString, parseAll=True): """ Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - testString - to test against this expression for a match - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests Example:: expr = Word(nums) assert expr.matches("100") """ try: self.parseString(_ustr(testString), parseAll=parseAll) return True except ParseBaseException: return False
[ "def", "matches", "(", "self", ",", "testString", ",", "parseAll", "=", "True", ")", ":", "try", ":", "self", ".", "parseString", "(", "_ustr", "(", "testString", ")", ",", "parseAll", "=", "parseAll", ")", "return", "True", "except", "ParseBaseException", ":", "return", "False" ]
[ 2171, 4 ]
[ 2188, 24 ]
python
en
['en', 'ja', 'th']
False
ParserElement.runTests
(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False)
Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.)
Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.)
def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False): """ Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.) """ if isinstance(tests, basestring): tests = list(map(str.strip, tests.rstrip().splitlines())) if isinstance(comment, basestring): comment = Literal(comment) allResults = [] comments = [] success = True for t in tests: if comment is not None and comment.matches(t, False) or comments and not t: comments.append(t) continue if not t: continue out = ['\n'.join(comments), t] comments = [] try: t = t.replace(r'\n','\n') result = self.parseString(t, parseAll=parseAll) out.append(result.dump(full=fullDump)) success = success and not failureTests except ParseBaseException as pe: fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else "" if '\n' in t: out.append(line(pe.loc, t)) out.append(' '*(col(pe.loc,t)-1) + '^' + fatal) else: out.append(' '*pe.loc + '^' + fatal) out.append("FAIL: " + str(pe)) success = success and failureTests result = pe except Exception as exc: out.append("FAIL-EXCEPTION: " + str(exc)) success = success and failureTests result = exc if printResults: if fullDump: out.append('') print('\n'.join(out)) allResults.append((t, result)) return success, allResults
[ "def", "runTests", "(", "self", ",", "tests", ",", "parseAll", "=", "True", ",", "comment", "=", "'#'", ",", "fullDump", "=", "True", ",", "printResults", "=", "True", ",", "failureTests", "=", "False", ")", ":", "if", "isinstance", "(", "tests", ",", "basestring", ")", ":", "tests", "=", "list", "(", "map", "(", "str", ".", "strip", ",", "tests", ".", "rstrip", "(", ")", ".", "splitlines", "(", ")", ")", ")", "if", "isinstance", "(", "comment", ",", "basestring", ")", ":", "comment", "=", "Literal", "(", "comment", ")", "allResults", "=", "[", "]", "comments", "=", "[", "]", "success", "=", "True", "for", "t", "in", "tests", ":", "if", "comment", "is", "not", "None", "and", "comment", ".", "matches", "(", "t", ",", "False", ")", "or", "comments", "and", "not", "t", ":", "comments", ".", "append", "(", "t", ")", "continue", "if", "not", "t", ":", "continue", "out", "=", "[", "'\\n'", ".", "join", "(", "comments", ")", ",", "t", "]", "comments", "=", "[", "]", "try", ":", "t", "=", "t", ".", "replace", "(", "r'\\n'", ",", "'\\n'", ")", "result", "=", "self", ".", "parseString", "(", "t", ",", "parseAll", "=", "parseAll", ")", "out", ".", "append", "(", "result", ".", "dump", "(", "full", "=", "fullDump", ")", ")", "success", "=", "success", "and", "not", "failureTests", "except", "ParseBaseException", "as", "pe", ":", "fatal", "=", "\"(FATAL)\"", "if", "isinstance", "(", "pe", ",", "ParseFatalException", ")", "else", "\"\"", "if", "'\\n'", "in", "t", ":", "out", ".", "append", "(", "line", "(", "pe", ".", "loc", ",", "t", ")", ")", "out", ".", "append", "(", "' '", "*", "(", "col", "(", "pe", ".", "loc", ",", "t", ")", "-", "1", ")", "+", "'^'", "+", "fatal", ")", "else", ":", "out", ".", "append", "(", "' '", "*", "pe", ".", "loc", "+", "'^'", "+", "fatal", ")", "out", ".", "append", "(", "\"FAIL: \"", "+", "str", "(", "pe", ")", ")", "success", "=", "success", "and", "failureTests", "result", "=", "pe", "except", "Exception", "as", "exc", ":", "out", ".", "append", "(", "\"FAIL-EXCEPTION: \"", "+", "str", "(", "exc", ")", ")", "success", "=", "success", "and", "failureTests", "result", "=", "exc", "if", "printResults", ":", "if", "fullDump", ":", "out", ".", "append", "(", "''", ")", "print", "(", "'\\n'", ".", "join", "(", "out", ")", ")", "allResults", ".", "append", "(", "(", "t", ",", "result", ")", ")", "return", "success", ",", "allResults" ]
[ 2190, 4 ]
[ 2319, 34 ]
python
en
['en', 'ja', 'th']
False