repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
wroberts/fsed
|
fsed/fsed.py
|
build_trie
|
python
|
def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries):
'''
Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`:
'''
boundaries = on_word_boundaries
if pattern_format == 'auto' or not on_word_boundaries:
tsv, boundaries = detect_pattern_format(pattern_filename, encoding,
on_word_boundaries)
if pattern_format == 'auto':
if tsv:
pattern_format = 'tsv'
else:
pattern_format = 'sed'
trie = fsed.ahocorasick.AhoCorasickTrie()
num_candidates = 0
with open_file(pattern_filename) as pattern_file:
for lineno, line in enumerate(pattern_file):
line = line.decode(encoding).rstrip('\n')
if not line.strip():
continue
# decode the line
if pattern_format == 'tsv':
fields = line.split('\t')
if len(fields) != 2:
LOGGER.warning(('skipping line {} of pattern file (not '
'in tab-separated format): {}').format(lineno, line))
continue
before, after = fields
elif pattern_format == 'sed':
before = after = None
line = line.lstrip()
if line[0] == 's':
delim = line[1]
# delim might be a regex special character;
# escape it if necessary
if delim in '.^$*+?[](){}|\\':
delim = '\\' + delim
fields = re.split(r'(?<!\\){}'.format(delim), line)
if len(fields) == 4:
before, after = fields[1], fields[2]
before = re.sub(r'(?<!\\)\\{}'.format(delim), delim, before)
after = re.sub(r'(?<!\\)\\{}'.format(delim), delim, after)
if before is None or after is None:
LOGGER.warning(('skipping line {} of pattern file (not '
'in sed format): {}').format(lineno, line))
continue
num_candidates += 1
if on_word_boundaries and before != before.strip():
LOGGER.warning(('before pattern on line {} padded whitespace; '
'this may interact strangely with the --words '
'option: {}').format(lineno, line))
before = sub_escapes(before)
after = sub_escapes(after)
if boundaries:
before = fsed.ahocorasick.boundary_transform(before, on_word_boundaries)
trie[before] = after
LOGGER.info('{} patterns loaded from {}'.format(num_candidates,
pattern_filename))
return trie, boundaries
|
Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`:
|
train
|
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L84-L148
|
[
"def boundary_transform(seq, force_edges = True):\n '''\n Wraps all word transitions with a boundary token character (\\x00).\n If desired (with ``force_edges`` set to ``True``), this inserts\n the boundary character at the beginning and end of the string.\n\n Arguments:\n - `seq`:\n - `force_edges = True`:\n '''\n gen = boundary_words(seq)\n if force_edges:\n gen = boundary_edges(gen)\n gen = remove_duplicates(gen)\n for char in gen:\n yield char\n",
"def open_file(filename, mode='rb'):\n \"\"\"\n Opens a file for access with the given mode. This function\n transparently wraps gzip and xz files as well as normal files.\n You can also open zip files using syntax like:\n\n f = utils.open_file('../semcor-parsed.zip:semcor000.txt')\n \"\"\"\n if (('r' not in mode or hasattr(filename, 'read')) and\n (('a' not in mode and 'w' not in mode) or hasattr(filename, 'write')) and\n hasattr(filename, '__iter__')):\n return filename\n elif isinstance(filename, string_type):\n if filename == '-' and 'r' in mode:\n if PY3:\n return sys.stdin.buffer\n return sys.stdin\n elif filename == '-' and ('w' in mode or 'a' in mode):\n if PY3:\n return sys.stdout.buffer\n return sys.stdout\n if filename.lower().count('.zip:'):\n assert 'r' in mode\n assert filename.count(':') == 1\n import zipfile\n zipped_file = zipfile.ZipFile(filename.split(':')[0])\n unzipped_file = zipped_file.open(filename.split(':')[1], 'r')\n zipped_file.close()\n return unzipped_file\n elif filename.lower().endswith('.gz'):\n import gzip\n return gzip.open(filename, mode)\n elif filename.lower().endswith('.xz'):\n import lzma\n tmp = lzma.LZMAFile(filename, mode)\n dir(tmp)\n return tmp\n else:\n return open(filename, mode)\n else:\n raise Exception('Unknown type for argument filename')\n",
"def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):\n '''\n Automatically detects the pattern file format, and determines\n whether the Aho-Corasick string matching should pay attention to\n word boundaries or not.\n\n Arguments:\n - `pattern_filename`:\n - `encoding`:\n - `on_word_boundaries`:\n '''\n tsv = True\n boundaries = on_word_boundaries\n with open_file(pattern_filename) as input_file:\n for line in input_file:\n line = line.decode(encoding)\n if line.count('\\t') != 1:\n tsv = False\n if '\\\\b' in line:\n boundaries = True\n if boundaries and not tsv:\n break\n return tsv, boundaries\n",
"def sub_escapes(sval):\n '''\n Process escaped characters in ``sval``.\n\n Arguments:\n - `sval`:\n '''\n sval = sval.replace('\\\\a', '\\a')\n sval = sval.replace('\\\\b', '\\x00')\n sval = sval.replace('\\\\f', '\\f')\n sval = sval.replace('\\\\n', '\\n')\n sval = sval.replace('\\\\r', '\\r')\n sval = sval.replace('\\\\t', '\\t')\n sval = sval.replace('\\\\v', '\\v')\n sval = sval.replace('\\\\\\\\', '\\\\')\n return sval\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
stream=sys.stderr, level=logging.INFO)
LOGGER = logging.getLogger(__name__)
def set_log_level(verbose, quiet):
'''
Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`:
'''
if quiet:
verbose = -1
if verbose < 0:
verbose = logging.CRITICAL
elif verbose == 0:
verbose = logging.WARNING
elif verbose == 1:
verbose = logging.INFO
elif 1 < verbose:
verbose = logging.DEBUG
LOGGER.setLevel(verbose)
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):
'''
Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word_boundaries`:
'''
tsv = True
boundaries = on_word_boundaries
with open_file(pattern_filename) as input_file:
for line in input_file:
line = line.decode(encoding)
if line.count('\t') != 1:
tsv = False
if '\\b' in line:
boundaries = True
if boundaries and not tsv:
break
return tsv, boundaries
def sub_escapes(sval):
'''
Process escaped characters in ``sval``.
Arguments:
- `sval`:
'''
sval = sval.replace('\\a', '\a')
sval = sval.replace('\\b', '\x00')
sval = sval.replace('\\f', '\f')
sval = sval.replace('\\n', '\n')
sval = sval.replace('\\r', '\r')
sval = sval.replace('\\t', '\t')
sval = sval.replace('\\v', '\v')
sval = sval.replace('\\\\', '\\')
return sval
def warn_prefix_values(trie):
'''
Prints warning messages for every node that has both a value and a
longest_prefix.
'''
for current, _parent in trie.dfs():
if current.has_value and current.longest_prefix is not None:
LOGGER.warn(('pattern {} (value {}) is a superstring of pattern '
'{} (value {}) and will never be matched').format(
current.prefix, current.value,
current.longest_prefix.prefix, current.longest_prefix.value))
def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):
'''
Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`:
'''
if boundaries:
sval = fsed.ahocorasick.boundary_transform(sval)
if slow:
sval = trie.replace(sval)
else:
sval = trie.greedy_replace(sval)
if boundaries:
sval = ''.join(fsed.ahocorasick.boundary_untransform(sval))
return sval
@click.command()
@click.argument('pattern_filename', type=click.Path(exists=True),
metavar='PATTERN_FILE')
@click.argument('input_filenames', nargs=-1,
type=click.Path(exists=True), metavar='[INPUT_FILES]')
@click.option('--pattern-format', type=click.Choice(['auto', 'tsv', 'sed']),
default='auto', show_default=True,
help='Specify the format of PATTERN_FILE')
@click.option('-o', '--output', 'output_filename', type=click.Path(),
help='Program output is written '
'to this file. Default is to write '
'to standard output.')
@click.option('-e', '--encoding', default='utf-8', show_default=True,
help='The character encoding to use')
@click.option('-w', '--words', is_flag=True,
help='Match only on word boundaries: '
'appends "\\b" to the beginning and '
'end of every pattern in PATTERN_FILE.')
@click.option('--by-line/--across-lines', default=False,
help='Process the input line by '
'line or character by character; the default is --across-lines.')
@click.option('--slow', is_flag=True,
help='Try very hard to '
'find the longest matches on the input; this is very slow, '
'and forces --by-line.')
@click.option('-v', '--verbose', default=0, count=True,
help='Turns on debugging output.')
@click.option('-q', '--quiet', is_flag=True,
help='Quiet operation, do not emit warnings.')
def main(pattern_filename, input_filenames, pattern_format,
output_filename,
encoding, words, by_line, slow, verbose, quiet):
'''
Search and replace on INPUT_FILE(s) (or standard input), with
matching on fixed strings.
'''
set_log_level(verbose, quiet)
if slow:
by_line = True
by_line = True # TODO: implement non-line-based rewriting
# load the patterns
LOGGER.info('fsed {} input {} output {}'.format(pattern_filename,
input_filenames,
output_filename))
if not input_filenames:
input_filenames = ('-',)
if not output_filename:
output_filename = '-'
# build trie machine for matching
trie, boundaries = build_trie(pattern_filename, pattern_format, encoding, words)
if not slow:
warn_prefix_values(trie)
LOGGER.info('writing to {}'.format(output_filename))
with open_file(output_filename, 'wb') as output_file:
for input_filename in input_filenames:
# search and replace
with open_file(input_filename) as input_file:
LOGGER.info('reading {}'.format(input_filename))
if by_line:
num_lines = 0
for line in input_file:
line = line.decode(encoding).rstrip('\n')
line = rewrite_str_with_trie(line, trie, boundaries, slow)
output_file.write((line + '\n').encode(encoding))
num_lines += 1
LOGGER.info('{} lines written'.format(num_lines))
else:
raise NotImplementedError
if __name__ == '__main__':
main()
|
wroberts/fsed
|
fsed/fsed.py
|
warn_prefix_values
|
python
|
def warn_prefix_values(trie):
'''
Prints warning messages for every node that has both a value and a
longest_prefix.
'''
for current, _parent in trie.dfs():
if current.has_value and current.longest_prefix is not None:
LOGGER.warn(('pattern {} (value {}) is a superstring of pattern '
'{} (value {}) and will never be matched').format(
current.prefix, current.value,
current.longest_prefix.prefix, current.longest_prefix.value))
|
Prints warning messages for every node that has both a value and a
longest_prefix.
|
train
|
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L150-L160
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
stream=sys.stderr, level=logging.INFO)
LOGGER = logging.getLogger(__name__)
def set_log_level(verbose, quiet):
'''
Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`:
'''
if quiet:
verbose = -1
if verbose < 0:
verbose = logging.CRITICAL
elif verbose == 0:
verbose = logging.WARNING
elif verbose == 1:
verbose = logging.INFO
elif 1 < verbose:
verbose = logging.DEBUG
LOGGER.setLevel(verbose)
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):
'''
Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word_boundaries`:
'''
tsv = True
boundaries = on_word_boundaries
with open_file(pattern_filename) as input_file:
for line in input_file:
line = line.decode(encoding)
if line.count('\t') != 1:
tsv = False
if '\\b' in line:
boundaries = True
if boundaries and not tsv:
break
return tsv, boundaries
def sub_escapes(sval):
'''
Process escaped characters in ``sval``.
Arguments:
- `sval`:
'''
sval = sval.replace('\\a', '\a')
sval = sval.replace('\\b', '\x00')
sval = sval.replace('\\f', '\f')
sval = sval.replace('\\n', '\n')
sval = sval.replace('\\r', '\r')
sval = sval.replace('\\t', '\t')
sval = sval.replace('\\v', '\v')
sval = sval.replace('\\\\', '\\')
return sval
def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries):
'''
Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`:
'''
boundaries = on_word_boundaries
if pattern_format == 'auto' or not on_word_boundaries:
tsv, boundaries = detect_pattern_format(pattern_filename, encoding,
on_word_boundaries)
if pattern_format == 'auto':
if tsv:
pattern_format = 'tsv'
else:
pattern_format = 'sed'
trie = fsed.ahocorasick.AhoCorasickTrie()
num_candidates = 0
with open_file(pattern_filename) as pattern_file:
for lineno, line in enumerate(pattern_file):
line = line.decode(encoding).rstrip('\n')
if not line.strip():
continue
# decode the line
if pattern_format == 'tsv':
fields = line.split('\t')
if len(fields) != 2:
LOGGER.warning(('skipping line {} of pattern file (not '
'in tab-separated format): {}').format(lineno, line))
continue
before, after = fields
elif pattern_format == 'sed':
before = after = None
line = line.lstrip()
if line[0] == 's':
delim = line[1]
# delim might be a regex special character;
# escape it if necessary
if delim in '.^$*+?[](){}|\\':
delim = '\\' + delim
fields = re.split(r'(?<!\\){}'.format(delim), line)
if len(fields) == 4:
before, after = fields[1], fields[2]
before = re.sub(r'(?<!\\)\\{}'.format(delim), delim, before)
after = re.sub(r'(?<!\\)\\{}'.format(delim), delim, after)
if before is None or after is None:
LOGGER.warning(('skipping line {} of pattern file (not '
'in sed format): {}').format(lineno, line))
continue
num_candidates += 1
if on_word_boundaries and before != before.strip():
LOGGER.warning(('before pattern on line {} padded whitespace; '
'this may interact strangely with the --words '
'option: {}').format(lineno, line))
before = sub_escapes(before)
after = sub_escapes(after)
if boundaries:
before = fsed.ahocorasick.boundary_transform(before, on_word_boundaries)
trie[before] = after
LOGGER.info('{} patterns loaded from {}'.format(num_candidates,
pattern_filename))
return trie, boundaries
def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):
'''
Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`:
'''
if boundaries:
sval = fsed.ahocorasick.boundary_transform(sval)
if slow:
sval = trie.replace(sval)
else:
sval = trie.greedy_replace(sval)
if boundaries:
sval = ''.join(fsed.ahocorasick.boundary_untransform(sval))
return sval
@click.command()
@click.argument('pattern_filename', type=click.Path(exists=True),
metavar='PATTERN_FILE')
@click.argument('input_filenames', nargs=-1,
type=click.Path(exists=True), metavar='[INPUT_FILES]')
@click.option('--pattern-format', type=click.Choice(['auto', 'tsv', 'sed']),
default='auto', show_default=True,
help='Specify the format of PATTERN_FILE')
@click.option('-o', '--output', 'output_filename', type=click.Path(),
help='Program output is written '
'to this file. Default is to write '
'to standard output.')
@click.option('-e', '--encoding', default='utf-8', show_default=True,
help='The character encoding to use')
@click.option('-w', '--words', is_flag=True,
help='Match only on word boundaries: '
'appends "\\b" to the beginning and '
'end of every pattern in PATTERN_FILE.')
@click.option('--by-line/--across-lines', default=False,
help='Process the input line by '
'line or character by character; the default is --across-lines.')
@click.option('--slow', is_flag=True,
help='Try very hard to '
'find the longest matches on the input; this is very slow, '
'and forces --by-line.')
@click.option('-v', '--verbose', default=0, count=True,
help='Turns on debugging output.')
@click.option('-q', '--quiet', is_flag=True,
help='Quiet operation, do not emit warnings.')
def main(pattern_filename, input_filenames, pattern_format,
output_filename,
encoding, words, by_line, slow, verbose, quiet):
'''
Search and replace on INPUT_FILE(s) (or standard input), with
matching on fixed strings.
'''
set_log_level(verbose, quiet)
if slow:
by_line = True
by_line = True # TODO: implement non-line-based rewriting
# load the patterns
LOGGER.info('fsed {} input {} output {}'.format(pattern_filename,
input_filenames,
output_filename))
if not input_filenames:
input_filenames = ('-',)
if not output_filename:
output_filename = '-'
# build trie machine for matching
trie, boundaries = build_trie(pattern_filename, pattern_format, encoding, words)
if not slow:
warn_prefix_values(trie)
LOGGER.info('writing to {}'.format(output_filename))
with open_file(output_filename, 'wb') as output_file:
for input_filename in input_filenames:
# search and replace
with open_file(input_filename) as input_file:
LOGGER.info('reading {}'.format(input_filename))
if by_line:
num_lines = 0
for line in input_file:
line = line.decode(encoding).rstrip('\n')
line = rewrite_str_with_trie(line, trie, boundaries, slow)
output_file.write((line + '\n').encode(encoding))
num_lines += 1
LOGGER.info('{} lines written'.format(num_lines))
else:
raise NotImplementedError
if __name__ == '__main__':
main()
|
wroberts/fsed
|
fsed/fsed.py
|
rewrite_str_with_trie
|
python
|
def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):
'''
Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`:
'''
if boundaries:
sval = fsed.ahocorasick.boundary_transform(sval)
if slow:
sval = trie.replace(sval)
else:
sval = trie.greedy_replace(sval)
if boundaries:
sval = ''.join(fsed.ahocorasick.boundary_untransform(sval))
return sval
|
Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`:
|
train
|
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L162-L180
|
[
"def boundary_transform(seq, force_edges = True):\n '''\n Wraps all word transitions with a boundary token character (\\x00).\n If desired (with ``force_edges`` set to ``True``), this inserts\n the boundary character at the beginning and end of the string.\n\n Arguments:\n - `seq`:\n - `force_edges = True`:\n '''\n gen = boundary_words(seq)\n if force_edges:\n gen = boundary_edges(gen)\n gen = remove_duplicates(gen)\n for char in gen:\n yield char\n",
"def boundary_untransform(seq):\n '''\n Removes boundary token characters from the given character\n iterable.\n\n Arguments:\n - `seq`:\n '''\n for char in seq:\n if char != '\\x00':\n yield char\n",
"def replace(self, seq):\n '''\n Performs search and replace on the given input string `seq` using\n the values stored in this trie. This method uses a O(n**2)\n chart-parsing algorithm to find the optimal way of replacing\n matches in the input.\n\n Arguments:\n - `seq`:\n '''\n # #1: seq must be stored in a container with a len() function\n seq = list(seq)\n # chart is a (n-1) X (n) table\n # chart[0] represents all matches of length (0+1) = 1\n # chart[n-1] represents all matches/rewrites of length (n-1+1) = n\n # chart[0][0] represents a match of length 1 starting at character 0\n # chart[0][n-1] represents a match of length 1 starting at character n-1\n # cells in the chart are tuples:\n # (score, list)\n # we initialise chart by filling in row 0:\n # each cell gets assigned (0, char), where char is the character at\n # the corresponding position in the input string\n chart = [ [None for _i in range(len(seq)) ] for _i in range(len(seq)) ]\n chart[0] = [(0, char) for char in seq]\n # now we fill in the chart using the results from the aho-corasick\n # string matches\n for (begin, length, value) in self.find_all(seq):\n chart[length-1][begin] = (length, value)\n # now we need to fill in the chart row by row, starting with row 1\n for row in range(1, len(chart)):\n # each row is 1 cell shorter than the last\n for col in range(len(seq) - row):\n # the entry in [row][col] is the choice with the highest score; to\n # find this, we must search the possible partitions of the cell\n #\n # things on row 2 have only one possible partition: 1 + 1\n # things on row 3 have two: 1 + 2, 2 + 1\n # things on row 4 have three: 1+3, 3+1, 2+2\n #\n # we assume that any pre-existing entry found by aho-corasick\n # in a cell is already optimal\n #print('scanning [{}][{}]'.format(row, col))\n if chart[row][col] is not None:\n continue\n # chart[1][2] is the cell of matches of length 2 starting at\n # character position 2;\n # it can only be composed of chart[0][2] + chart[0][3]\n #\n # partition_point is the length of the first of the two parts\n # of the cell\n #print('cell[{}][{}] => '.format(row, col))\n best_score = -1\n best_value = None\n for partition_point in range(row):\n # the two cells will be [partition_point][col] and\n # [row - partition_point - 2][col+partition_point+1]\n x1 = partition_point\n y1 = col\n x2 = row - partition_point - 1\n y2 = col + partition_point + 1\n #print(' [{}][{}] + [{}][{}]'.format(x1, y1, x2, y2))\n s1, v1 = chart[x1][y1]\n s2, v2 = chart[x2][y2]\n # compute the score\n score = s1 + s2\n #print(' = {} + {}'.format((s1, v1), (s2, v2)))\n #print(' = score {}'.format(score))\n if best_score < score:\n best_score = score\n best_value = v1 + v2\n chart[row][col] = (best_score, best_value)\n #print(' sets new best score with value {}'.format(\n # best_value))\n # now the optimal solution is stored at the top of the chart\n return chart[len(seq)-1][0][1]\n",
"def greedy_replace(self, seq):\n '''\n Greedily matches strings in ``seq``, and replaces them with their\n node values.\n\n Arguments:\n - `seq`: an iterable of characters to perform search-and-replace on\n '''\n if not self._suffix_links_set:\n self._set_suffix_links()\n # start at the root\n current = self.root\n buffered = ''\n outstr = ''\n for char in seq:\n while char not in current:\n if current.has_dict_suffix:\n current = current.dict_suffix\n outstr += buffered[:-current.depth]\n outstr += current.value\n buffered = ''\n current = self.root\n break\n elif current.has_suffix:\n current = current.suffix\n if current.depth:\n outstr += buffered[:-current.depth]\n buffered = buffered[-current.depth:]\n else:\n outstr += buffered\n buffered = ''\n break\n else:\n current = self.root\n outstr += buffered\n buffered = ''\n break\n if char in current:\n buffered += char\n current = current[char]\n if current.has_value:\n outstr += buffered[:-current.depth]\n outstr += current.value\n buffered = ''\n current = self.root\n else:\n assert current is self.root\n outstr += buffered + char\n buffered = ''\n if current.has_dict_suffix:\n current = current.dict_suffix\n outstr += buffered[:-current.depth]\n outstr += current.value\n else:\n outstr += buffered\n return outstr\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
stream=sys.stderr, level=logging.INFO)
LOGGER = logging.getLogger(__name__)
def set_log_level(verbose, quiet):
'''
Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`:
'''
if quiet:
verbose = -1
if verbose < 0:
verbose = logging.CRITICAL
elif verbose == 0:
verbose = logging.WARNING
elif verbose == 1:
verbose = logging.INFO
elif 1 < verbose:
verbose = logging.DEBUG
LOGGER.setLevel(verbose)
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):
'''
Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word_boundaries`:
'''
tsv = True
boundaries = on_word_boundaries
with open_file(pattern_filename) as input_file:
for line in input_file:
line = line.decode(encoding)
if line.count('\t') != 1:
tsv = False
if '\\b' in line:
boundaries = True
if boundaries and not tsv:
break
return tsv, boundaries
def sub_escapes(sval):
'''
Process escaped characters in ``sval``.
Arguments:
- `sval`:
'''
sval = sval.replace('\\a', '\a')
sval = sval.replace('\\b', '\x00')
sval = sval.replace('\\f', '\f')
sval = sval.replace('\\n', '\n')
sval = sval.replace('\\r', '\r')
sval = sval.replace('\\t', '\t')
sval = sval.replace('\\v', '\v')
sval = sval.replace('\\\\', '\\')
return sval
def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries):
'''
Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`:
'''
boundaries = on_word_boundaries
if pattern_format == 'auto' or not on_word_boundaries:
tsv, boundaries = detect_pattern_format(pattern_filename, encoding,
on_word_boundaries)
if pattern_format == 'auto':
if tsv:
pattern_format = 'tsv'
else:
pattern_format = 'sed'
trie = fsed.ahocorasick.AhoCorasickTrie()
num_candidates = 0
with open_file(pattern_filename) as pattern_file:
for lineno, line in enumerate(pattern_file):
line = line.decode(encoding).rstrip('\n')
if not line.strip():
continue
# decode the line
if pattern_format == 'tsv':
fields = line.split('\t')
if len(fields) != 2:
LOGGER.warning(('skipping line {} of pattern file (not '
'in tab-separated format): {}').format(lineno, line))
continue
before, after = fields
elif pattern_format == 'sed':
before = after = None
line = line.lstrip()
if line[0] == 's':
delim = line[1]
# delim might be a regex special character;
# escape it if necessary
if delim in '.^$*+?[](){}|\\':
delim = '\\' + delim
fields = re.split(r'(?<!\\){}'.format(delim), line)
if len(fields) == 4:
before, after = fields[1], fields[2]
before = re.sub(r'(?<!\\)\\{}'.format(delim), delim, before)
after = re.sub(r'(?<!\\)\\{}'.format(delim), delim, after)
if before is None or after is None:
LOGGER.warning(('skipping line {} of pattern file (not '
'in sed format): {}').format(lineno, line))
continue
num_candidates += 1
if on_word_boundaries and before != before.strip():
LOGGER.warning(('before pattern on line {} padded whitespace; '
'this may interact strangely with the --words '
'option: {}').format(lineno, line))
before = sub_escapes(before)
after = sub_escapes(after)
if boundaries:
before = fsed.ahocorasick.boundary_transform(before, on_word_boundaries)
trie[before] = after
LOGGER.info('{} patterns loaded from {}'.format(num_candidates,
pattern_filename))
return trie, boundaries
def warn_prefix_values(trie):
'''
Prints warning messages for every node that has both a value and a
longest_prefix.
'''
for current, _parent in trie.dfs():
if current.has_value and current.longest_prefix is not None:
LOGGER.warn(('pattern {} (value {}) is a superstring of pattern '
'{} (value {}) and will never be matched').format(
current.prefix, current.value,
current.longest_prefix.prefix, current.longest_prefix.value))
@click.command()
@click.argument('pattern_filename', type=click.Path(exists=True),
metavar='PATTERN_FILE')
@click.argument('input_filenames', nargs=-1,
type=click.Path(exists=True), metavar='[INPUT_FILES]')
@click.option('--pattern-format', type=click.Choice(['auto', 'tsv', 'sed']),
default='auto', show_default=True,
help='Specify the format of PATTERN_FILE')
@click.option('-o', '--output', 'output_filename', type=click.Path(),
help='Program output is written '
'to this file. Default is to write '
'to standard output.')
@click.option('-e', '--encoding', default='utf-8', show_default=True,
help='The character encoding to use')
@click.option('-w', '--words', is_flag=True,
help='Match only on word boundaries: '
'appends "\\b" to the beginning and '
'end of every pattern in PATTERN_FILE.')
@click.option('--by-line/--across-lines', default=False,
help='Process the input line by '
'line or character by character; the default is --across-lines.')
@click.option('--slow', is_flag=True,
help='Try very hard to '
'find the longest matches on the input; this is very slow, '
'and forces --by-line.')
@click.option('-v', '--verbose', default=0, count=True,
help='Turns on debugging output.')
@click.option('-q', '--quiet', is_flag=True,
help='Quiet operation, do not emit warnings.')
def main(pattern_filename, input_filenames, pattern_format,
output_filename,
encoding, words, by_line, slow, verbose, quiet):
'''
Search and replace on INPUT_FILE(s) (or standard input), with
matching on fixed strings.
'''
set_log_level(verbose, quiet)
if slow:
by_line = True
by_line = True # TODO: implement non-line-based rewriting
# load the patterns
LOGGER.info('fsed {} input {} output {}'.format(pattern_filename,
input_filenames,
output_filename))
if not input_filenames:
input_filenames = ('-',)
if not output_filename:
output_filename = '-'
# build trie machine for matching
trie, boundaries = build_trie(pattern_filename, pattern_format, encoding, words)
if not slow:
warn_prefix_values(trie)
LOGGER.info('writing to {}'.format(output_filename))
with open_file(output_filename, 'wb') as output_file:
for input_filename in input_filenames:
# search and replace
with open_file(input_filename) as input_file:
LOGGER.info('reading {}'.format(input_filename))
if by_line:
num_lines = 0
for line in input_file:
line = line.decode(encoding).rstrip('\n')
line = rewrite_str_with_trie(line, trie, boundaries, slow)
output_file.write((line + '\n').encode(encoding))
num_lines += 1
LOGGER.info('{} lines written'.format(num_lines))
else:
raise NotImplementedError
if __name__ == '__main__':
main()
|
wroberts/fsed
|
fsed/fsed.py
|
main
|
python
|
def main(pattern_filename, input_filenames, pattern_format,
output_filename,
encoding, words, by_line, slow, verbose, quiet):
'''
Search and replace on INPUT_FILE(s) (or standard input), with
matching on fixed strings.
'''
set_log_level(verbose, quiet)
if slow:
by_line = True
by_line = True # TODO: implement non-line-based rewriting
# load the patterns
LOGGER.info('fsed {} input {} output {}'.format(pattern_filename,
input_filenames,
output_filename))
if not input_filenames:
input_filenames = ('-',)
if not output_filename:
output_filename = '-'
# build trie machine for matching
trie, boundaries = build_trie(pattern_filename, pattern_format, encoding, words)
if not slow:
warn_prefix_values(trie)
LOGGER.info('writing to {}'.format(output_filename))
with open_file(output_filename, 'wb') as output_file:
for input_filename in input_filenames:
# search and replace
with open_file(input_filename) as input_file:
LOGGER.info('reading {}'.format(input_filename))
if by_line:
num_lines = 0
for line in input_file:
line = line.decode(encoding).rstrip('\n')
line = rewrite_str_with_trie(line, trie, boundaries, slow)
output_file.write((line + '\n').encode(encoding))
num_lines += 1
LOGGER.info('{} lines written'.format(num_lines))
else:
raise NotImplementedError
|
Search and replace on INPUT_FILE(s) (or standard input), with
matching on fixed strings.
|
train
|
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L211-L249
|
[
"def open_file(filename, mode='rb'):\n \"\"\"\n Opens a file for access with the given mode. This function\n transparently wraps gzip and xz files as well as normal files.\n You can also open zip files using syntax like:\n\n f = utils.open_file('../semcor-parsed.zip:semcor000.txt')\n \"\"\"\n if (('r' not in mode or hasattr(filename, 'read')) and\n (('a' not in mode and 'w' not in mode) or hasattr(filename, 'write')) and\n hasattr(filename, '__iter__')):\n return filename\n elif isinstance(filename, string_type):\n if filename == '-' and 'r' in mode:\n if PY3:\n return sys.stdin.buffer\n return sys.stdin\n elif filename == '-' and ('w' in mode or 'a' in mode):\n if PY3:\n return sys.stdout.buffer\n return sys.stdout\n if filename.lower().count('.zip:'):\n assert 'r' in mode\n assert filename.count(':') == 1\n import zipfile\n zipped_file = zipfile.ZipFile(filename.split(':')[0])\n unzipped_file = zipped_file.open(filename.split(':')[1], 'r')\n zipped_file.close()\n return unzipped_file\n elif filename.lower().endswith('.gz'):\n import gzip\n return gzip.open(filename, mode)\n elif filename.lower().endswith('.xz'):\n import lzma\n tmp = lzma.LZMAFile(filename, mode)\n dir(tmp)\n return tmp\n else:\n return open(filename, mode)\n else:\n raise Exception('Unknown type for argument filename')\n",
"def set_log_level(verbose, quiet):\n '''\n Ses the logging level of the script based on command line options.\n\n Arguments:\n - `verbose`:\n - `quiet`:\n '''\n if quiet:\n verbose = -1\n if verbose < 0:\n verbose = logging.CRITICAL\n elif verbose == 0:\n verbose = logging.WARNING\n elif verbose == 1:\n verbose = logging.INFO\n elif 1 < verbose:\n verbose = logging.DEBUG\n LOGGER.setLevel(verbose)\n",
"def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries):\n '''\n Constructs a finite state machine for performing string rewriting.\n\n Arguments:\n - `pattern_filename`:\n - `pattern_format`:\n - `encoding`:\n - `on_word_boundaries`:\n '''\n boundaries = on_word_boundaries\n if pattern_format == 'auto' or not on_word_boundaries:\n tsv, boundaries = detect_pattern_format(pattern_filename, encoding,\n on_word_boundaries)\n if pattern_format == 'auto':\n if tsv:\n pattern_format = 'tsv'\n else:\n pattern_format = 'sed'\n trie = fsed.ahocorasick.AhoCorasickTrie()\n num_candidates = 0\n with open_file(pattern_filename) as pattern_file:\n for lineno, line in enumerate(pattern_file):\n line = line.decode(encoding).rstrip('\\n')\n if not line.strip():\n continue\n # decode the line\n if pattern_format == 'tsv':\n fields = line.split('\\t')\n if len(fields) != 2:\n LOGGER.warning(('skipping line {} of pattern file (not '\n 'in tab-separated format): {}').format(lineno, line))\n continue\n before, after = fields\n elif pattern_format == 'sed':\n before = after = None\n line = line.lstrip()\n if line[0] == 's':\n delim = line[1]\n # delim might be a regex special character;\n # escape it if necessary\n if delim in '.^$*+?[](){}|\\\\':\n delim = '\\\\' + delim\n fields = re.split(r'(?<!\\\\){}'.format(delim), line)\n if len(fields) == 4:\n before, after = fields[1], fields[2]\n before = re.sub(r'(?<!\\\\)\\\\{}'.format(delim), delim, before)\n after = re.sub(r'(?<!\\\\)\\\\{}'.format(delim), delim, after)\n if before is None or after is None:\n LOGGER.warning(('skipping line {} of pattern file (not '\n 'in sed format): {}').format(lineno, line))\n continue\n num_candidates += 1\n if on_word_boundaries and before != before.strip():\n LOGGER.warning(('before pattern on line {} padded whitespace; '\n 'this may interact strangely with the --words '\n 'option: {}').format(lineno, line))\n before = sub_escapes(before)\n after = sub_escapes(after)\n if boundaries:\n before = fsed.ahocorasick.boundary_transform(before, on_word_boundaries)\n trie[before] = after\n LOGGER.info('{} patterns loaded from {}'.format(num_candidates,\n pattern_filename))\n return trie, boundaries\n",
"def warn_prefix_values(trie):\n '''\n Prints warning messages for every node that has both a value and a\n longest_prefix.\n '''\n for current, _parent in trie.dfs():\n if current.has_value and current.longest_prefix is not None:\n LOGGER.warn(('pattern {} (value {}) is a superstring of pattern '\n '{} (value {}) and will never be matched').format(\n current.prefix, current.value,\n current.longest_prefix.prefix, current.longest_prefix.value))\n",
"def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):\n '''\n Rewrites a string using the given trie object.\n\n Arguments:\n - `sval`:\n - `trie`:\n - `boundaries`:\n - `slow`:\n '''\n if boundaries:\n sval = fsed.ahocorasick.boundary_transform(sval)\n if slow:\n sval = trie.replace(sval)\n else:\n sval = trie.greedy_replace(sval)\n if boundaries:\n sval = ''.join(fsed.ahocorasick.boundary_untransform(sval))\n return sval\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
stream=sys.stderr, level=logging.INFO)
LOGGER = logging.getLogger(__name__)
def set_log_level(verbose, quiet):
'''
Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`:
'''
if quiet:
verbose = -1
if verbose < 0:
verbose = logging.CRITICAL
elif verbose == 0:
verbose = logging.WARNING
elif verbose == 1:
verbose = logging.INFO
elif 1 < verbose:
verbose = logging.DEBUG
LOGGER.setLevel(verbose)
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):
'''
Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word_boundaries`:
'''
tsv = True
boundaries = on_word_boundaries
with open_file(pattern_filename) as input_file:
for line in input_file:
line = line.decode(encoding)
if line.count('\t') != 1:
tsv = False
if '\\b' in line:
boundaries = True
if boundaries and not tsv:
break
return tsv, boundaries
def sub_escapes(sval):
'''
Process escaped characters in ``sval``.
Arguments:
- `sval`:
'''
sval = sval.replace('\\a', '\a')
sval = sval.replace('\\b', '\x00')
sval = sval.replace('\\f', '\f')
sval = sval.replace('\\n', '\n')
sval = sval.replace('\\r', '\r')
sval = sval.replace('\\t', '\t')
sval = sval.replace('\\v', '\v')
sval = sval.replace('\\\\', '\\')
return sval
def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries):
'''
Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`:
'''
boundaries = on_word_boundaries
if pattern_format == 'auto' or not on_word_boundaries:
tsv, boundaries = detect_pattern_format(pattern_filename, encoding,
on_word_boundaries)
if pattern_format == 'auto':
if tsv:
pattern_format = 'tsv'
else:
pattern_format = 'sed'
trie = fsed.ahocorasick.AhoCorasickTrie()
num_candidates = 0
with open_file(pattern_filename) as pattern_file:
for lineno, line in enumerate(pattern_file):
line = line.decode(encoding).rstrip('\n')
if not line.strip():
continue
# decode the line
if pattern_format == 'tsv':
fields = line.split('\t')
if len(fields) != 2:
LOGGER.warning(('skipping line {} of pattern file (not '
'in tab-separated format): {}').format(lineno, line))
continue
before, after = fields
elif pattern_format == 'sed':
before = after = None
line = line.lstrip()
if line[0] == 's':
delim = line[1]
# delim might be a regex special character;
# escape it if necessary
if delim in '.^$*+?[](){}|\\':
delim = '\\' + delim
fields = re.split(r'(?<!\\){}'.format(delim), line)
if len(fields) == 4:
before, after = fields[1], fields[2]
before = re.sub(r'(?<!\\)\\{}'.format(delim), delim, before)
after = re.sub(r'(?<!\\)\\{}'.format(delim), delim, after)
if before is None or after is None:
LOGGER.warning(('skipping line {} of pattern file (not '
'in sed format): {}').format(lineno, line))
continue
num_candidates += 1
if on_word_boundaries and before != before.strip():
LOGGER.warning(('before pattern on line {} padded whitespace; '
'this may interact strangely with the --words '
'option: {}').format(lineno, line))
before = sub_escapes(before)
after = sub_escapes(after)
if boundaries:
before = fsed.ahocorasick.boundary_transform(before, on_word_boundaries)
trie[before] = after
LOGGER.info('{} patterns loaded from {}'.format(num_candidates,
pattern_filename))
return trie, boundaries
def warn_prefix_values(trie):
'''
Prints warning messages for every node that has both a value and a
longest_prefix.
'''
for current, _parent in trie.dfs():
if current.has_value and current.longest_prefix is not None:
LOGGER.warn(('pattern {} (value {}) is a superstring of pattern '
'{} (value {}) and will never be matched').format(
current.prefix, current.value,
current.longest_prefix.prefix, current.longest_prefix.value))
def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):
'''
Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`:
'''
if boundaries:
sval = fsed.ahocorasick.boundary_transform(sval)
if slow:
sval = trie.replace(sval)
else:
sval = trie.greedy_replace(sval)
if boundaries:
sval = ''.join(fsed.ahocorasick.boundary_untransform(sval))
return sval
@click.command()
@click.argument('pattern_filename', type=click.Path(exists=True),
metavar='PATTERN_FILE')
@click.argument('input_filenames', nargs=-1,
type=click.Path(exists=True), metavar='[INPUT_FILES]')
@click.option('--pattern-format', type=click.Choice(['auto', 'tsv', 'sed']),
default='auto', show_default=True,
help='Specify the format of PATTERN_FILE')
@click.option('-o', '--output', 'output_filename', type=click.Path(),
help='Program output is written '
'to this file. Default is to write '
'to standard output.')
@click.option('-e', '--encoding', default='utf-8', show_default=True,
help='The character encoding to use')
@click.option('-w', '--words', is_flag=True,
help='Match only on word boundaries: '
'appends "\\b" to the beginning and '
'end of every pattern in PATTERN_FILE.')
@click.option('--by-line/--across-lines', default=False,
help='Process the input line by '
'line or character by character; the default is --across-lines.')
@click.option('--slow', is_flag=True,
help='Try very hard to '
'find the longest matches on the input; this is very slow, '
'and forces --by-line.')
@click.option('-v', '--verbose', default=0, count=True,
help='Turns on debugging output.')
@click.option('-q', '--quiet', is_flag=True,
help='Quiet operation, do not emit warnings.')
if __name__ == '__main__':
main()
|
rosshamish/catan-py
|
catan/game.py
|
Game.do
|
python
|
def do(self, command: undoredo.Command):
self.undo_manager.do(command)
self.notify_observers()
|
Does the command using the undo_manager's stack
:param command: Command
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L83-L89
|
[
"def notify_observers(self):\n for obs in self.observers.copy():\n obs.notify(self)\n"
] |
class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state and make changes accordingly.
e.g. self.game.observers.add(self)
A Game has state. When changing state, remember to pass the current game to the
state's constructor. This allows the state to modify the game as appropriate in
the current state.
e.g. self.set_state(states.GameStateNotInGame(self))
"""
def __init__(self, players=None, board=None, logging='on', pregame='on', use_stdout=False):
"""
Create a Game with the given options.
:param players: list(Player)
:param board: Board
:param logging: (on|off)
:param pregame: (on|off)
:param use_stdout: bool (log to stdout?)
"""
self.observers = set()
self.undo_manager = undoredo.UndoManager()
self.options = {
'pregame': pregame,
}
self.players = players or list()
self.board = board or catan.board.Board()
self.robber = catan.pieces.Piece(catan.pieces.PieceType.robber, None)
# catanlog: writing, reading
if logging == 'on':
self.catanlog = catanlog.CatanLog(use_stdout=use_stdout)
else:
self.catanlog = catanlog.NoopCatanLog()
# self.catanlog_reader = catanlog.Reader()
self.state = None # set in #set_state
self.dev_card_state = None # set in #set_dev_card_state
self._cur_player = None # set in #set_players
self.last_roll = None # set in #roll
self.last_player_to_roll = None # set in #roll
self._cur_turn = 0 # incremented in #end_turn
self.robber_tile = None # set in #move_robber
self.board.observers.add(self)
self.set_state(catan.states.GameStateNotInGame(self))
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == 'observers':
setattr(result, k, set(v))
elif k == 'state':
setattr(result, k, v)
elif k == 'undo_manager':
setattr(result, k, v)
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def undo(self):
"""
Rewind the game to the previous state.
"""
self.undo_manager.undo()
self.notify_observers()
logging.debug('undo_manager undo stack={}'.format(self.undo_manager._undo_stack))
def redo(self):
"""
Redo the latest undone command.
"""
self.undo_manager.redo()
self.notify_observers()
logging.debug('undo_manager redo stack={}'.format(self.undo_manager._redo_stack))
def copy(self):
"""
Return a deep copy of this Game object. See Game.__deepcopy__ for the copy implementation.
:return: Game
"""
return copy.deepcopy(self)
def restore(self, game):
"""
Restore this Game object to match the properties and state of the given Game object
:param game: properties to restore to the current (self) Game
"""
self.observers = game.observers
# self.undo_manager = game.undo_manager
self.options = game.options
self.players = game.players
self.board.restore(game.board)
self.robber = game.robber
self.catanlog = game.catanlog
self.state = game.state
self.state.game = self
self.dev_card_state = game.dev_card_state
self._cur_player = game._cur_player
self.last_roll = game.last_roll
self.last_player_to_roll = game.last_player_to_roll
self._cur_turn = game._cur_turn
self.robber_tile = game.robber_tile
self.notify_observers()
# def read_from_file(self, file):
# self.catanlog_reader.use_file(file)
def notify(self, observable):
self.notify_observers()
def notify_observers(self):
for obs in self.observers.copy():
obs.notify(self)
def set_state(self, game_state):
_old_state = self.state
_old_board_state = self.board.state
self.state = game_state
if game_state.is_in_game():
self.board.lock()
else:
self.board.unlock()
logging.info('Game now={}, was={}. Board now={}, was={}'.format(
type(self.state).__name__,
type(_old_state).__name__,
type(self.board.state).__name__,
type(_old_board_state).__name__
))
self.notify_observers()
def set_dev_card_state(self, dev_state):
self.dev_card_state = dev_state
self.notify_observers()
@undoredo.undoable
def start(self, players):
"""
Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds the robber on the board, sets the robber_tile appropriately
- Logs the catanlog header
:param players: players to start the game with
"""
from .boardbuilder import Opt
self.reset()
if self.board.opts.get('players') == Opt.debug:
players = Game.get_debug_players()
self.set_players(players)
if self.options.get('pregame') is None or self.options.get('pregame') == 'on':
logging.debug('Entering pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
elif self.options.get('pregame') == 'off':
logging.debug('Skipping pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStateBeginTurn(self))
terrain = list()
numbers = list()
for tile in self.board.tiles:
terrain.append(tile.terrain)
numbers.append(tile.number)
for (_, coord), piece in self.board.pieces.items():
if piece.type == catan.pieces.PieceType.robber:
self.robber_tile = hexgrid.tile_id_from_coord(coord)
logging.debug('Found robber at coord={}, set robber_tile={}'.format(coord, self.robber_tile))
self.catanlog.log_game_start(self.players, terrain, numbers, self.board.ports)
self.notify_observers()
def end(self):
self.catanlog.log_player_wins(self.get_cur_player())
self.set_state(catan.states.GameStateNotInGame(self))
def reset(self):
self.players = list()
self.state = catan.states.GameStateNotInGame(self)
self.last_roll = None
self.last_player_to_roll = None
self._cur_player = None
self._cur_turn = 0
self.notify_observers()
def get_cur_player(self):
if self._cur_player is None:
return Player(1, 'nobody', 'nobody')
else:
return Player(self._cur_player.seat, self._cur_player.name, self._cur_player.color)
def set_cur_player(self, player):
self._cur_player = Player(player.seat, player.name, player.color)
def set_players(self, players):
self.players = list(players)
self.set_cur_player(self.players[0])
self.notify_observers()
def cur_player_has_port_type(self, port_type):
return self.player_has_port_type(self.get_cur_player(), port_type)
def player_has_port_type(self, player, port_type):
for port in self.board.ports:
if port.type == port_type and self._player_has_port(player, port):
return True
return False
def _player_has_port(self, player, port):
edge_coord = hexgrid.edge_coord_in_direction(port.tile_id, port.direction)
for node in hexgrid.nodes_touching_edge(edge_coord):
pieces = self.board.get_pieces((catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), node)
if len(pieces) < 1:
continue
elif len(pieces) > 1:
raise Exception('Probably a bug, num={} pieces found on node={}'.format(
len(pieces), node
))
assert len(pieces) == 1 # will be asserted by previous if/elif combo
piece = pieces[0]
if piece.owner == player:
return True
return False
@undoredo.undoable
def roll(self, roll):
self.catanlog.log_roll(self.get_cur_player(), roll)
self.last_roll = roll
self.last_player_to_roll = self.get_cur_player()
if int(roll) == 7:
self.set_state(catan.states.GameStateMoveRobber(self))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def move_robber(self, tile):
self.state.move_robber(tile)
@undoredo.undoable
def steal(self, victim):
if victim is None:
victim = Player(1, 'nobody', 'nobody')
self.state.steal(victim)
def stealable_players(self):
if self.robber_tile is None:
return list()
stealable = set()
for node in hexgrid.nodes_touching_tile(self.robber_tile):
pieces = self.board.get_pieces(types=(catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), coord=node)
if pieces:
logging.debug('found stealable player={}, cur={}'.format(pieces[0].owner, self.get_cur_player()))
stealable.add(pieces[0].owner)
if self.get_cur_player() in stealable:
stealable.remove(self.get_cur_player())
logging.debug('stealable players={} at robber tile={}'.format(stealable, self.robber_tile))
return stealable
@undoredo.undoable
def begin_placing(self, piece_type):
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, piece_type))
else:
self.set_state(catan.states.GameStatePlacingPiece(self, piece_type))
# @undoredo.undoable # state.place_road calls this, place_road is undoable
def buy_road(self, edge):
#self.assert_legal_road(edge)
piece = catan.pieces.Piece(catan.pieces.PieceType.road, self.get_cur_player())
self.board.place_piece(piece, edge)
self.catanlog.log_buys_road(self.get_cur_player(), hexgrid.location(hexgrid.EDGE, edge))
if self.state.is_in_pregame():
self.end_turn()
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_settlement calls this, place_settlement is undoable
def buy_settlement(self, node):
#self.assert_legal_settlement(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.settlement, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_settlement(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.road))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_city calls this, place_city is undoable
def buy_city(self, node):
#self.assert_legal_city(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.city, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_city(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def buy_dev_card(self):
self.catanlog.log_buys_dev_card(self.get_cur_player())
self.notify_observers()
@undoredo.undoable
def place_road(self, edge_coord):
self.state.place_road(edge_coord)
@undoredo.undoable
def place_settlement(self, node_coord):
self.state.place_settlement(node_coord)
@undoredo.undoable
def place_city(self, node_coord):
self.state.place_city(node_coord)
@undoredo.undoable
def trade(self, trade):
giver = trade.giver()
giving = trade.giving()
getting = trade.getting()
if hasattr(trade.getter(), 'type') and trade.getter().type in catan.board.PortType:
getter = trade.getter()
self.catanlog.log_trades_with_port(giver, giving, getter, getting)
logging.debug('trading {} to port={} to get={}'.format(giving, getter, getting))
else:
getter = trade.getter()
self.catanlog.log_trades_with_player(giver, giving, getter, getting)
logging.debug('trading {} to player={} to get={}'.format(giving, getter, getting))
self.notify_observers()
@undoredo.undoable
def play_knight(self):
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
self.set_state(catan.states.GameStateMoveRobberUsingKnight(self))
@undoredo.undoable
def play_monopoly(self, resource):
self.catanlog.log_plays_monopoly(self.get_cur_player(), resource)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_year_of_plenty(self, resource1, resource2):
self.catanlog.log_plays_year_of_plenty(self.get_cur_player(), resource1, resource2)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_road_builder(self, edge1, edge2):
self.catanlog.log_plays_road_builder(self.get_cur_player(),
hexgrid.location(hexgrid.EDGE, edge1),
hexgrid.location(hexgrid.EDGE, edge2))
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_victory_point(self):
self.catanlog.log_plays_victory_point(self.get_cur_player())
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def end_turn(self):
self.catanlog.log_ends_turn(self.get_cur_player())
self.set_cur_player(self.state.next_player())
self._cur_turn += 1
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
else:
self.set_state(catan.states.GameStateBeginTurn(self))
@classmethod
def get_debug_players(cls):
return [Player(1, 'yurick', 'green'),
Player(2, 'josh', 'blue'),
Player(3, 'zach', 'orange'),
Player(4, 'ross', 'red')]
|
rosshamish/catan-py
|
catan/game.py
|
Game.undo
|
python
|
def undo(self):
self.undo_manager.undo()
self.notify_observers()
logging.debug('undo_manager undo stack={}'.format(self.undo_manager._undo_stack))
|
Rewind the game to the previous state.
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L91-L97
|
[
"def notify_observers(self):\n for obs in self.observers.copy():\n obs.notify(self)\n"
] |
class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state and make changes accordingly.
e.g. self.game.observers.add(self)
A Game has state. When changing state, remember to pass the current game to the
state's constructor. This allows the state to modify the game as appropriate in
the current state.
e.g. self.set_state(states.GameStateNotInGame(self))
"""
def __init__(self, players=None, board=None, logging='on', pregame='on', use_stdout=False):
"""
Create a Game with the given options.
:param players: list(Player)
:param board: Board
:param logging: (on|off)
:param pregame: (on|off)
:param use_stdout: bool (log to stdout?)
"""
self.observers = set()
self.undo_manager = undoredo.UndoManager()
self.options = {
'pregame': pregame,
}
self.players = players or list()
self.board = board or catan.board.Board()
self.robber = catan.pieces.Piece(catan.pieces.PieceType.robber, None)
# catanlog: writing, reading
if logging == 'on':
self.catanlog = catanlog.CatanLog(use_stdout=use_stdout)
else:
self.catanlog = catanlog.NoopCatanLog()
# self.catanlog_reader = catanlog.Reader()
self.state = None # set in #set_state
self.dev_card_state = None # set in #set_dev_card_state
self._cur_player = None # set in #set_players
self.last_roll = None # set in #roll
self.last_player_to_roll = None # set in #roll
self._cur_turn = 0 # incremented in #end_turn
self.robber_tile = None # set in #move_robber
self.board.observers.add(self)
self.set_state(catan.states.GameStateNotInGame(self))
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == 'observers':
setattr(result, k, set(v))
elif k == 'state':
setattr(result, k, v)
elif k == 'undo_manager':
setattr(result, k, v)
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def do(self, command: undoredo.Command):
"""
Does the command using the undo_manager's stack
:param command: Command
"""
self.undo_manager.do(command)
self.notify_observers()
def redo(self):
"""
Redo the latest undone command.
"""
self.undo_manager.redo()
self.notify_observers()
logging.debug('undo_manager redo stack={}'.format(self.undo_manager._redo_stack))
def copy(self):
"""
Return a deep copy of this Game object. See Game.__deepcopy__ for the copy implementation.
:return: Game
"""
return copy.deepcopy(self)
def restore(self, game):
"""
Restore this Game object to match the properties and state of the given Game object
:param game: properties to restore to the current (self) Game
"""
self.observers = game.observers
# self.undo_manager = game.undo_manager
self.options = game.options
self.players = game.players
self.board.restore(game.board)
self.robber = game.robber
self.catanlog = game.catanlog
self.state = game.state
self.state.game = self
self.dev_card_state = game.dev_card_state
self._cur_player = game._cur_player
self.last_roll = game.last_roll
self.last_player_to_roll = game.last_player_to_roll
self._cur_turn = game._cur_turn
self.robber_tile = game.robber_tile
self.notify_observers()
# def read_from_file(self, file):
# self.catanlog_reader.use_file(file)
def notify(self, observable):
self.notify_observers()
def notify_observers(self):
for obs in self.observers.copy():
obs.notify(self)
def set_state(self, game_state):
_old_state = self.state
_old_board_state = self.board.state
self.state = game_state
if game_state.is_in_game():
self.board.lock()
else:
self.board.unlock()
logging.info('Game now={}, was={}. Board now={}, was={}'.format(
type(self.state).__name__,
type(_old_state).__name__,
type(self.board.state).__name__,
type(_old_board_state).__name__
))
self.notify_observers()
def set_dev_card_state(self, dev_state):
self.dev_card_state = dev_state
self.notify_observers()
@undoredo.undoable
def start(self, players):
"""
Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds the robber on the board, sets the robber_tile appropriately
- Logs the catanlog header
:param players: players to start the game with
"""
from .boardbuilder import Opt
self.reset()
if self.board.opts.get('players') == Opt.debug:
players = Game.get_debug_players()
self.set_players(players)
if self.options.get('pregame') is None or self.options.get('pregame') == 'on':
logging.debug('Entering pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
elif self.options.get('pregame') == 'off':
logging.debug('Skipping pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStateBeginTurn(self))
terrain = list()
numbers = list()
for tile in self.board.tiles:
terrain.append(tile.terrain)
numbers.append(tile.number)
for (_, coord), piece in self.board.pieces.items():
if piece.type == catan.pieces.PieceType.robber:
self.robber_tile = hexgrid.tile_id_from_coord(coord)
logging.debug('Found robber at coord={}, set robber_tile={}'.format(coord, self.robber_tile))
self.catanlog.log_game_start(self.players, terrain, numbers, self.board.ports)
self.notify_observers()
def end(self):
self.catanlog.log_player_wins(self.get_cur_player())
self.set_state(catan.states.GameStateNotInGame(self))
def reset(self):
self.players = list()
self.state = catan.states.GameStateNotInGame(self)
self.last_roll = None
self.last_player_to_roll = None
self._cur_player = None
self._cur_turn = 0
self.notify_observers()
def get_cur_player(self):
if self._cur_player is None:
return Player(1, 'nobody', 'nobody')
else:
return Player(self._cur_player.seat, self._cur_player.name, self._cur_player.color)
def set_cur_player(self, player):
self._cur_player = Player(player.seat, player.name, player.color)
def set_players(self, players):
self.players = list(players)
self.set_cur_player(self.players[0])
self.notify_observers()
def cur_player_has_port_type(self, port_type):
return self.player_has_port_type(self.get_cur_player(), port_type)
def player_has_port_type(self, player, port_type):
for port in self.board.ports:
if port.type == port_type and self._player_has_port(player, port):
return True
return False
def _player_has_port(self, player, port):
edge_coord = hexgrid.edge_coord_in_direction(port.tile_id, port.direction)
for node in hexgrid.nodes_touching_edge(edge_coord):
pieces = self.board.get_pieces((catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), node)
if len(pieces) < 1:
continue
elif len(pieces) > 1:
raise Exception('Probably a bug, num={} pieces found on node={}'.format(
len(pieces), node
))
assert len(pieces) == 1 # will be asserted by previous if/elif combo
piece = pieces[0]
if piece.owner == player:
return True
return False
@undoredo.undoable
def roll(self, roll):
self.catanlog.log_roll(self.get_cur_player(), roll)
self.last_roll = roll
self.last_player_to_roll = self.get_cur_player()
if int(roll) == 7:
self.set_state(catan.states.GameStateMoveRobber(self))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def move_robber(self, tile):
self.state.move_robber(tile)
@undoredo.undoable
def steal(self, victim):
if victim is None:
victim = Player(1, 'nobody', 'nobody')
self.state.steal(victim)
def stealable_players(self):
if self.robber_tile is None:
return list()
stealable = set()
for node in hexgrid.nodes_touching_tile(self.robber_tile):
pieces = self.board.get_pieces(types=(catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), coord=node)
if pieces:
logging.debug('found stealable player={}, cur={}'.format(pieces[0].owner, self.get_cur_player()))
stealable.add(pieces[0].owner)
if self.get_cur_player() in stealable:
stealable.remove(self.get_cur_player())
logging.debug('stealable players={} at robber tile={}'.format(stealable, self.robber_tile))
return stealable
@undoredo.undoable
def begin_placing(self, piece_type):
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, piece_type))
else:
self.set_state(catan.states.GameStatePlacingPiece(self, piece_type))
# @undoredo.undoable # state.place_road calls this, place_road is undoable
def buy_road(self, edge):
#self.assert_legal_road(edge)
piece = catan.pieces.Piece(catan.pieces.PieceType.road, self.get_cur_player())
self.board.place_piece(piece, edge)
self.catanlog.log_buys_road(self.get_cur_player(), hexgrid.location(hexgrid.EDGE, edge))
if self.state.is_in_pregame():
self.end_turn()
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_settlement calls this, place_settlement is undoable
def buy_settlement(self, node):
#self.assert_legal_settlement(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.settlement, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_settlement(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.road))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_city calls this, place_city is undoable
def buy_city(self, node):
#self.assert_legal_city(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.city, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_city(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def buy_dev_card(self):
self.catanlog.log_buys_dev_card(self.get_cur_player())
self.notify_observers()
@undoredo.undoable
def place_road(self, edge_coord):
self.state.place_road(edge_coord)
@undoredo.undoable
def place_settlement(self, node_coord):
self.state.place_settlement(node_coord)
@undoredo.undoable
def place_city(self, node_coord):
self.state.place_city(node_coord)
@undoredo.undoable
def trade(self, trade):
giver = trade.giver()
giving = trade.giving()
getting = trade.getting()
if hasattr(trade.getter(), 'type') and trade.getter().type in catan.board.PortType:
getter = trade.getter()
self.catanlog.log_trades_with_port(giver, giving, getter, getting)
logging.debug('trading {} to port={} to get={}'.format(giving, getter, getting))
else:
getter = trade.getter()
self.catanlog.log_trades_with_player(giver, giving, getter, getting)
logging.debug('trading {} to player={} to get={}'.format(giving, getter, getting))
self.notify_observers()
@undoredo.undoable
def play_knight(self):
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
self.set_state(catan.states.GameStateMoveRobberUsingKnight(self))
@undoredo.undoable
def play_monopoly(self, resource):
self.catanlog.log_plays_monopoly(self.get_cur_player(), resource)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_year_of_plenty(self, resource1, resource2):
self.catanlog.log_plays_year_of_plenty(self.get_cur_player(), resource1, resource2)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_road_builder(self, edge1, edge2):
self.catanlog.log_plays_road_builder(self.get_cur_player(),
hexgrid.location(hexgrid.EDGE, edge1),
hexgrid.location(hexgrid.EDGE, edge2))
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_victory_point(self):
self.catanlog.log_plays_victory_point(self.get_cur_player())
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def end_turn(self):
self.catanlog.log_ends_turn(self.get_cur_player())
self.set_cur_player(self.state.next_player())
self._cur_turn += 1
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
else:
self.set_state(catan.states.GameStateBeginTurn(self))
@classmethod
def get_debug_players(cls):
return [Player(1, 'yurick', 'green'),
Player(2, 'josh', 'blue'),
Player(3, 'zach', 'orange'),
Player(4, 'ross', 'red')]
|
rosshamish/catan-py
|
catan/game.py
|
Game.redo
|
python
|
def redo(self):
self.undo_manager.redo()
self.notify_observers()
logging.debug('undo_manager redo stack={}'.format(self.undo_manager._redo_stack))
|
Redo the latest undone command.
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L99-L105
|
[
"def notify_observers(self):\n for obs in self.observers.copy():\n obs.notify(self)\n"
] |
class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state and make changes accordingly.
e.g. self.game.observers.add(self)
A Game has state. When changing state, remember to pass the current game to the
state's constructor. This allows the state to modify the game as appropriate in
the current state.
e.g. self.set_state(states.GameStateNotInGame(self))
"""
def __init__(self, players=None, board=None, logging='on', pregame='on', use_stdout=False):
"""
Create a Game with the given options.
:param players: list(Player)
:param board: Board
:param logging: (on|off)
:param pregame: (on|off)
:param use_stdout: bool (log to stdout?)
"""
self.observers = set()
self.undo_manager = undoredo.UndoManager()
self.options = {
'pregame': pregame,
}
self.players = players or list()
self.board = board or catan.board.Board()
self.robber = catan.pieces.Piece(catan.pieces.PieceType.robber, None)
# catanlog: writing, reading
if logging == 'on':
self.catanlog = catanlog.CatanLog(use_stdout=use_stdout)
else:
self.catanlog = catanlog.NoopCatanLog()
# self.catanlog_reader = catanlog.Reader()
self.state = None # set in #set_state
self.dev_card_state = None # set in #set_dev_card_state
self._cur_player = None # set in #set_players
self.last_roll = None # set in #roll
self.last_player_to_roll = None # set in #roll
self._cur_turn = 0 # incremented in #end_turn
self.robber_tile = None # set in #move_robber
self.board.observers.add(self)
self.set_state(catan.states.GameStateNotInGame(self))
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == 'observers':
setattr(result, k, set(v))
elif k == 'state':
setattr(result, k, v)
elif k == 'undo_manager':
setattr(result, k, v)
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def do(self, command: undoredo.Command):
"""
Does the command using the undo_manager's stack
:param command: Command
"""
self.undo_manager.do(command)
self.notify_observers()
def undo(self):
"""
Rewind the game to the previous state.
"""
self.undo_manager.undo()
self.notify_observers()
logging.debug('undo_manager undo stack={}'.format(self.undo_manager._undo_stack))
def copy(self):
"""
Return a deep copy of this Game object. See Game.__deepcopy__ for the copy implementation.
:return: Game
"""
return copy.deepcopy(self)
def restore(self, game):
"""
Restore this Game object to match the properties and state of the given Game object
:param game: properties to restore to the current (self) Game
"""
self.observers = game.observers
# self.undo_manager = game.undo_manager
self.options = game.options
self.players = game.players
self.board.restore(game.board)
self.robber = game.robber
self.catanlog = game.catanlog
self.state = game.state
self.state.game = self
self.dev_card_state = game.dev_card_state
self._cur_player = game._cur_player
self.last_roll = game.last_roll
self.last_player_to_roll = game.last_player_to_roll
self._cur_turn = game._cur_turn
self.robber_tile = game.robber_tile
self.notify_observers()
# def read_from_file(self, file):
# self.catanlog_reader.use_file(file)
def notify(self, observable):
self.notify_observers()
def notify_observers(self):
for obs in self.observers.copy():
obs.notify(self)
def set_state(self, game_state):
_old_state = self.state
_old_board_state = self.board.state
self.state = game_state
if game_state.is_in_game():
self.board.lock()
else:
self.board.unlock()
logging.info('Game now={}, was={}. Board now={}, was={}'.format(
type(self.state).__name__,
type(_old_state).__name__,
type(self.board.state).__name__,
type(_old_board_state).__name__
))
self.notify_observers()
def set_dev_card_state(self, dev_state):
self.dev_card_state = dev_state
self.notify_observers()
@undoredo.undoable
def start(self, players):
"""
Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds the robber on the board, sets the robber_tile appropriately
- Logs the catanlog header
:param players: players to start the game with
"""
from .boardbuilder import Opt
self.reset()
if self.board.opts.get('players') == Opt.debug:
players = Game.get_debug_players()
self.set_players(players)
if self.options.get('pregame') is None or self.options.get('pregame') == 'on':
logging.debug('Entering pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
elif self.options.get('pregame') == 'off':
logging.debug('Skipping pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStateBeginTurn(self))
terrain = list()
numbers = list()
for tile in self.board.tiles:
terrain.append(tile.terrain)
numbers.append(tile.number)
for (_, coord), piece in self.board.pieces.items():
if piece.type == catan.pieces.PieceType.robber:
self.robber_tile = hexgrid.tile_id_from_coord(coord)
logging.debug('Found robber at coord={}, set robber_tile={}'.format(coord, self.robber_tile))
self.catanlog.log_game_start(self.players, terrain, numbers, self.board.ports)
self.notify_observers()
def end(self):
self.catanlog.log_player_wins(self.get_cur_player())
self.set_state(catan.states.GameStateNotInGame(self))
def reset(self):
self.players = list()
self.state = catan.states.GameStateNotInGame(self)
self.last_roll = None
self.last_player_to_roll = None
self._cur_player = None
self._cur_turn = 0
self.notify_observers()
def get_cur_player(self):
if self._cur_player is None:
return Player(1, 'nobody', 'nobody')
else:
return Player(self._cur_player.seat, self._cur_player.name, self._cur_player.color)
def set_cur_player(self, player):
self._cur_player = Player(player.seat, player.name, player.color)
def set_players(self, players):
self.players = list(players)
self.set_cur_player(self.players[0])
self.notify_observers()
def cur_player_has_port_type(self, port_type):
return self.player_has_port_type(self.get_cur_player(), port_type)
def player_has_port_type(self, player, port_type):
for port in self.board.ports:
if port.type == port_type and self._player_has_port(player, port):
return True
return False
def _player_has_port(self, player, port):
edge_coord = hexgrid.edge_coord_in_direction(port.tile_id, port.direction)
for node in hexgrid.nodes_touching_edge(edge_coord):
pieces = self.board.get_pieces((catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), node)
if len(pieces) < 1:
continue
elif len(pieces) > 1:
raise Exception('Probably a bug, num={} pieces found on node={}'.format(
len(pieces), node
))
assert len(pieces) == 1 # will be asserted by previous if/elif combo
piece = pieces[0]
if piece.owner == player:
return True
return False
@undoredo.undoable
def roll(self, roll):
self.catanlog.log_roll(self.get_cur_player(), roll)
self.last_roll = roll
self.last_player_to_roll = self.get_cur_player()
if int(roll) == 7:
self.set_state(catan.states.GameStateMoveRobber(self))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def move_robber(self, tile):
self.state.move_robber(tile)
@undoredo.undoable
def steal(self, victim):
if victim is None:
victim = Player(1, 'nobody', 'nobody')
self.state.steal(victim)
def stealable_players(self):
if self.robber_tile is None:
return list()
stealable = set()
for node in hexgrid.nodes_touching_tile(self.robber_tile):
pieces = self.board.get_pieces(types=(catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), coord=node)
if pieces:
logging.debug('found stealable player={}, cur={}'.format(pieces[0].owner, self.get_cur_player()))
stealable.add(pieces[0].owner)
if self.get_cur_player() in stealable:
stealable.remove(self.get_cur_player())
logging.debug('stealable players={} at robber tile={}'.format(stealable, self.robber_tile))
return stealable
@undoredo.undoable
def begin_placing(self, piece_type):
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, piece_type))
else:
self.set_state(catan.states.GameStatePlacingPiece(self, piece_type))
# @undoredo.undoable # state.place_road calls this, place_road is undoable
def buy_road(self, edge):
#self.assert_legal_road(edge)
piece = catan.pieces.Piece(catan.pieces.PieceType.road, self.get_cur_player())
self.board.place_piece(piece, edge)
self.catanlog.log_buys_road(self.get_cur_player(), hexgrid.location(hexgrid.EDGE, edge))
if self.state.is_in_pregame():
self.end_turn()
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_settlement calls this, place_settlement is undoable
def buy_settlement(self, node):
#self.assert_legal_settlement(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.settlement, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_settlement(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.road))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_city calls this, place_city is undoable
def buy_city(self, node):
#self.assert_legal_city(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.city, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_city(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def buy_dev_card(self):
self.catanlog.log_buys_dev_card(self.get_cur_player())
self.notify_observers()
@undoredo.undoable
def place_road(self, edge_coord):
self.state.place_road(edge_coord)
@undoredo.undoable
def place_settlement(self, node_coord):
self.state.place_settlement(node_coord)
@undoredo.undoable
def place_city(self, node_coord):
self.state.place_city(node_coord)
@undoredo.undoable
def trade(self, trade):
giver = trade.giver()
giving = trade.giving()
getting = trade.getting()
if hasattr(trade.getter(), 'type') and trade.getter().type in catan.board.PortType:
getter = trade.getter()
self.catanlog.log_trades_with_port(giver, giving, getter, getting)
logging.debug('trading {} to port={} to get={}'.format(giving, getter, getting))
else:
getter = trade.getter()
self.catanlog.log_trades_with_player(giver, giving, getter, getting)
logging.debug('trading {} to player={} to get={}'.format(giving, getter, getting))
self.notify_observers()
@undoredo.undoable
def play_knight(self):
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
self.set_state(catan.states.GameStateMoveRobberUsingKnight(self))
@undoredo.undoable
def play_monopoly(self, resource):
self.catanlog.log_plays_monopoly(self.get_cur_player(), resource)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_year_of_plenty(self, resource1, resource2):
self.catanlog.log_plays_year_of_plenty(self.get_cur_player(), resource1, resource2)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_road_builder(self, edge1, edge2):
self.catanlog.log_plays_road_builder(self.get_cur_player(),
hexgrid.location(hexgrid.EDGE, edge1),
hexgrid.location(hexgrid.EDGE, edge2))
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_victory_point(self):
self.catanlog.log_plays_victory_point(self.get_cur_player())
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def end_turn(self):
self.catanlog.log_ends_turn(self.get_cur_player())
self.set_cur_player(self.state.next_player())
self._cur_turn += 1
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
else:
self.set_state(catan.states.GameStateBeginTurn(self))
@classmethod
def get_debug_players(cls):
return [Player(1, 'yurick', 'green'),
Player(2, 'josh', 'blue'),
Player(3, 'zach', 'orange'),
Player(4, 'ross', 'red')]
|
rosshamish/catan-py
|
catan/game.py
|
Game.restore
|
python
|
def restore(self, game):
self.observers = game.observers
# self.undo_manager = game.undo_manager
self.options = game.options
self.players = game.players
self.board.restore(game.board)
self.robber = game.robber
self.catanlog = game.catanlog
self.state = game.state
self.state.game = self
self.dev_card_state = game.dev_card_state
self._cur_player = game._cur_player
self.last_roll = game.last_roll
self.last_player_to_roll = game.last_player_to_roll
self._cur_turn = game._cur_turn
self.robber_tile = game.robber_tile
self.notify_observers()
|
Restore this Game object to match the properties and state of the given Game object
:param game: properties to restore to the current (self) Game
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L114-L138
|
[
"def notify_observers(self):\n for obs in self.observers.copy():\n obs.notify(self)\n"
] |
class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state and make changes accordingly.
e.g. self.game.observers.add(self)
A Game has state. When changing state, remember to pass the current game to the
state's constructor. This allows the state to modify the game as appropriate in
the current state.
e.g. self.set_state(states.GameStateNotInGame(self))
"""
def __init__(self, players=None, board=None, logging='on', pregame='on', use_stdout=False):
"""
Create a Game with the given options.
:param players: list(Player)
:param board: Board
:param logging: (on|off)
:param pregame: (on|off)
:param use_stdout: bool (log to stdout?)
"""
self.observers = set()
self.undo_manager = undoredo.UndoManager()
self.options = {
'pregame': pregame,
}
self.players = players or list()
self.board = board or catan.board.Board()
self.robber = catan.pieces.Piece(catan.pieces.PieceType.robber, None)
# catanlog: writing, reading
if logging == 'on':
self.catanlog = catanlog.CatanLog(use_stdout=use_stdout)
else:
self.catanlog = catanlog.NoopCatanLog()
# self.catanlog_reader = catanlog.Reader()
self.state = None # set in #set_state
self.dev_card_state = None # set in #set_dev_card_state
self._cur_player = None # set in #set_players
self.last_roll = None # set in #roll
self.last_player_to_roll = None # set in #roll
self._cur_turn = 0 # incremented in #end_turn
self.robber_tile = None # set in #move_robber
self.board.observers.add(self)
self.set_state(catan.states.GameStateNotInGame(self))
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == 'observers':
setattr(result, k, set(v))
elif k == 'state':
setattr(result, k, v)
elif k == 'undo_manager':
setattr(result, k, v)
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def do(self, command: undoredo.Command):
"""
Does the command using the undo_manager's stack
:param command: Command
"""
self.undo_manager.do(command)
self.notify_observers()
def undo(self):
"""
Rewind the game to the previous state.
"""
self.undo_manager.undo()
self.notify_observers()
logging.debug('undo_manager undo stack={}'.format(self.undo_manager._undo_stack))
def redo(self):
"""
Redo the latest undone command.
"""
self.undo_manager.redo()
self.notify_observers()
logging.debug('undo_manager redo stack={}'.format(self.undo_manager._redo_stack))
def copy(self):
"""
Return a deep copy of this Game object. See Game.__deepcopy__ for the copy implementation.
:return: Game
"""
return copy.deepcopy(self)
# def read_from_file(self, file):
# self.catanlog_reader.use_file(file)
def notify(self, observable):
self.notify_observers()
def notify_observers(self):
for obs in self.observers.copy():
obs.notify(self)
def set_state(self, game_state):
_old_state = self.state
_old_board_state = self.board.state
self.state = game_state
if game_state.is_in_game():
self.board.lock()
else:
self.board.unlock()
logging.info('Game now={}, was={}. Board now={}, was={}'.format(
type(self.state).__name__,
type(_old_state).__name__,
type(self.board.state).__name__,
type(_old_board_state).__name__
))
self.notify_observers()
def set_dev_card_state(self, dev_state):
self.dev_card_state = dev_state
self.notify_observers()
@undoredo.undoable
def start(self, players):
"""
Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds the robber on the board, sets the robber_tile appropriately
- Logs the catanlog header
:param players: players to start the game with
"""
from .boardbuilder import Opt
self.reset()
if self.board.opts.get('players') == Opt.debug:
players = Game.get_debug_players()
self.set_players(players)
if self.options.get('pregame') is None or self.options.get('pregame') == 'on':
logging.debug('Entering pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
elif self.options.get('pregame') == 'off':
logging.debug('Skipping pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStateBeginTurn(self))
terrain = list()
numbers = list()
for tile in self.board.tiles:
terrain.append(tile.terrain)
numbers.append(tile.number)
for (_, coord), piece in self.board.pieces.items():
if piece.type == catan.pieces.PieceType.robber:
self.robber_tile = hexgrid.tile_id_from_coord(coord)
logging.debug('Found robber at coord={}, set robber_tile={}'.format(coord, self.robber_tile))
self.catanlog.log_game_start(self.players, terrain, numbers, self.board.ports)
self.notify_observers()
def end(self):
self.catanlog.log_player_wins(self.get_cur_player())
self.set_state(catan.states.GameStateNotInGame(self))
def reset(self):
self.players = list()
self.state = catan.states.GameStateNotInGame(self)
self.last_roll = None
self.last_player_to_roll = None
self._cur_player = None
self._cur_turn = 0
self.notify_observers()
def get_cur_player(self):
if self._cur_player is None:
return Player(1, 'nobody', 'nobody')
else:
return Player(self._cur_player.seat, self._cur_player.name, self._cur_player.color)
def set_cur_player(self, player):
self._cur_player = Player(player.seat, player.name, player.color)
def set_players(self, players):
self.players = list(players)
self.set_cur_player(self.players[0])
self.notify_observers()
def cur_player_has_port_type(self, port_type):
return self.player_has_port_type(self.get_cur_player(), port_type)
def player_has_port_type(self, player, port_type):
for port in self.board.ports:
if port.type == port_type and self._player_has_port(player, port):
return True
return False
def _player_has_port(self, player, port):
edge_coord = hexgrid.edge_coord_in_direction(port.tile_id, port.direction)
for node in hexgrid.nodes_touching_edge(edge_coord):
pieces = self.board.get_pieces((catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), node)
if len(pieces) < 1:
continue
elif len(pieces) > 1:
raise Exception('Probably a bug, num={} pieces found on node={}'.format(
len(pieces), node
))
assert len(pieces) == 1 # will be asserted by previous if/elif combo
piece = pieces[0]
if piece.owner == player:
return True
return False
@undoredo.undoable
def roll(self, roll):
self.catanlog.log_roll(self.get_cur_player(), roll)
self.last_roll = roll
self.last_player_to_roll = self.get_cur_player()
if int(roll) == 7:
self.set_state(catan.states.GameStateMoveRobber(self))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def move_robber(self, tile):
self.state.move_robber(tile)
@undoredo.undoable
def steal(self, victim):
if victim is None:
victim = Player(1, 'nobody', 'nobody')
self.state.steal(victim)
def stealable_players(self):
if self.robber_tile is None:
return list()
stealable = set()
for node in hexgrid.nodes_touching_tile(self.robber_tile):
pieces = self.board.get_pieces(types=(catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), coord=node)
if pieces:
logging.debug('found stealable player={}, cur={}'.format(pieces[0].owner, self.get_cur_player()))
stealable.add(pieces[0].owner)
if self.get_cur_player() in stealable:
stealable.remove(self.get_cur_player())
logging.debug('stealable players={} at robber tile={}'.format(stealable, self.robber_tile))
return stealable
@undoredo.undoable
def begin_placing(self, piece_type):
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, piece_type))
else:
self.set_state(catan.states.GameStatePlacingPiece(self, piece_type))
# @undoredo.undoable # state.place_road calls this, place_road is undoable
def buy_road(self, edge):
#self.assert_legal_road(edge)
piece = catan.pieces.Piece(catan.pieces.PieceType.road, self.get_cur_player())
self.board.place_piece(piece, edge)
self.catanlog.log_buys_road(self.get_cur_player(), hexgrid.location(hexgrid.EDGE, edge))
if self.state.is_in_pregame():
self.end_turn()
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_settlement calls this, place_settlement is undoable
def buy_settlement(self, node):
#self.assert_legal_settlement(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.settlement, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_settlement(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.road))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_city calls this, place_city is undoable
def buy_city(self, node):
#self.assert_legal_city(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.city, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_city(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def buy_dev_card(self):
self.catanlog.log_buys_dev_card(self.get_cur_player())
self.notify_observers()
@undoredo.undoable
def place_road(self, edge_coord):
self.state.place_road(edge_coord)
@undoredo.undoable
def place_settlement(self, node_coord):
self.state.place_settlement(node_coord)
@undoredo.undoable
def place_city(self, node_coord):
self.state.place_city(node_coord)
@undoredo.undoable
def trade(self, trade):
giver = trade.giver()
giving = trade.giving()
getting = trade.getting()
if hasattr(trade.getter(), 'type') and trade.getter().type in catan.board.PortType:
getter = trade.getter()
self.catanlog.log_trades_with_port(giver, giving, getter, getting)
logging.debug('trading {} to port={} to get={}'.format(giving, getter, getting))
else:
getter = trade.getter()
self.catanlog.log_trades_with_player(giver, giving, getter, getting)
logging.debug('trading {} to player={} to get={}'.format(giving, getter, getting))
self.notify_observers()
@undoredo.undoable
def play_knight(self):
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
self.set_state(catan.states.GameStateMoveRobberUsingKnight(self))
@undoredo.undoable
def play_monopoly(self, resource):
self.catanlog.log_plays_monopoly(self.get_cur_player(), resource)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_year_of_plenty(self, resource1, resource2):
self.catanlog.log_plays_year_of_plenty(self.get_cur_player(), resource1, resource2)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_road_builder(self, edge1, edge2):
self.catanlog.log_plays_road_builder(self.get_cur_player(),
hexgrid.location(hexgrid.EDGE, edge1),
hexgrid.location(hexgrid.EDGE, edge2))
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_victory_point(self):
self.catanlog.log_plays_victory_point(self.get_cur_player())
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def end_turn(self):
self.catanlog.log_ends_turn(self.get_cur_player())
self.set_cur_player(self.state.next_player())
self._cur_turn += 1
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
else:
self.set_state(catan.states.GameStateBeginTurn(self))
@classmethod
def get_debug_players(cls):
return [Player(1, 'yurick', 'green'),
Player(2, 'josh', 'blue'),
Player(3, 'zach', 'orange'),
Player(4, 'ross', 'red')]
|
rosshamish/catan-py
|
catan/game.py
|
Game.start
|
python
|
def start(self, players):
from .boardbuilder import Opt
self.reset()
if self.board.opts.get('players') == Opt.debug:
players = Game.get_debug_players()
self.set_players(players)
if self.options.get('pregame') is None or self.options.get('pregame') == 'on':
logging.debug('Entering pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
elif self.options.get('pregame') == 'off':
logging.debug('Skipping pregame, game options={}'.format(self.options))
self.set_state(catan.states.GameStateBeginTurn(self))
terrain = list()
numbers = list()
for tile in self.board.tiles:
terrain.append(tile.terrain)
numbers.append(tile.number)
for (_, coord), piece in self.board.pieces.items():
if piece.type == catan.pieces.PieceType.robber:
self.robber_tile = hexgrid.tile_id_from_coord(coord)
logging.debug('Found robber at coord={}, set robber_tile={}'.format(coord, self.robber_tile))
self.catanlog.log_game_start(self.players, terrain, numbers, self.board.ports)
self.notify_observers()
|
Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds the robber on the board, sets the robber_tile appropriately
- Logs the catanlog header
:param players: players to start the game with
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L171-L209
|
[
"def reset(self):\n self.players = list()\n self.state = catan.states.GameStateNotInGame(self)\n\n self.last_roll = None\n self.last_player_to_roll = None\n self._cur_player = None\n self._cur_turn = 0\n\n self.notify_observers()\n",
"def set_players(self, players):\n self.players = list(players)\n self.set_cur_player(self.players[0])\n self.notify_observers()\n",
"def get_debug_players(cls):\n return [Player(1, 'yurick', 'green'),\n Player(2, 'josh', 'blue'),\n Player(3, 'zach', 'orange'),\n Player(4, 'ross', 'red')]\n"
] |
class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state and make changes accordingly.
e.g. self.game.observers.add(self)
A Game has state. When changing state, remember to pass the current game to the
state's constructor. This allows the state to modify the game as appropriate in
the current state.
e.g. self.set_state(states.GameStateNotInGame(self))
"""
def __init__(self, players=None, board=None, logging='on', pregame='on', use_stdout=False):
"""
Create a Game with the given options.
:param players: list(Player)
:param board: Board
:param logging: (on|off)
:param pregame: (on|off)
:param use_stdout: bool (log to stdout?)
"""
self.observers = set()
self.undo_manager = undoredo.UndoManager()
self.options = {
'pregame': pregame,
}
self.players = players or list()
self.board = board or catan.board.Board()
self.robber = catan.pieces.Piece(catan.pieces.PieceType.robber, None)
# catanlog: writing, reading
if logging == 'on':
self.catanlog = catanlog.CatanLog(use_stdout=use_stdout)
else:
self.catanlog = catanlog.NoopCatanLog()
# self.catanlog_reader = catanlog.Reader()
self.state = None # set in #set_state
self.dev_card_state = None # set in #set_dev_card_state
self._cur_player = None # set in #set_players
self.last_roll = None # set in #roll
self.last_player_to_roll = None # set in #roll
self._cur_turn = 0 # incremented in #end_turn
self.robber_tile = None # set in #move_robber
self.board.observers.add(self)
self.set_state(catan.states.GameStateNotInGame(self))
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == 'observers':
setattr(result, k, set(v))
elif k == 'state':
setattr(result, k, v)
elif k == 'undo_manager':
setattr(result, k, v)
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def do(self, command: undoredo.Command):
"""
Does the command using the undo_manager's stack
:param command: Command
"""
self.undo_manager.do(command)
self.notify_observers()
def undo(self):
"""
Rewind the game to the previous state.
"""
self.undo_manager.undo()
self.notify_observers()
logging.debug('undo_manager undo stack={}'.format(self.undo_manager._undo_stack))
def redo(self):
"""
Redo the latest undone command.
"""
self.undo_manager.redo()
self.notify_observers()
logging.debug('undo_manager redo stack={}'.format(self.undo_manager._redo_stack))
def copy(self):
"""
Return a deep copy of this Game object. See Game.__deepcopy__ for the copy implementation.
:return: Game
"""
return copy.deepcopy(self)
def restore(self, game):
"""
Restore this Game object to match the properties and state of the given Game object
:param game: properties to restore to the current (self) Game
"""
self.observers = game.observers
# self.undo_manager = game.undo_manager
self.options = game.options
self.players = game.players
self.board.restore(game.board)
self.robber = game.robber
self.catanlog = game.catanlog
self.state = game.state
self.state.game = self
self.dev_card_state = game.dev_card_state
self._cur_player = game._cur_player
self.last_roll = game.last_roll
self.last_player_to_roll = game.last_player_to_roll
self._cur_turn = game._cur_turn
self.robber_tile = game.robber_tile
self.notify_observers()
# def read_from_file(self, file):
# self.catanlog_reader.use_file(file)
def notify(self, observable):
self.notify_observers()
def notify_observers(self):
for obs in self.observers.copy():
obs.notify(self)
def set_state(self, game_state):
_old_state = self.state
_old_board_state = self.board.state
self.state = game_state
if game_state.is_in_game():
self.board.lock()
else:
self.board.unlock()
logging.info('Game now={}, was={}. Board now={}, was={}'.format(
type(self.state).__name__,
type(_old_state).__name__,
type(self.board.state).__name__,
type(_old_board_state).__name__
))
self.notify_observers()
def set_dev_card_state(self, dev_state):
self.dev_card_state = dev_state
self.notify_observers()
@undoredo.undoable
def end(self):
self.catanlog.log_player_wins(self.get_cur_player())
self.set_state(catan.states.GameStateNotInGame(self))
def reset(self):
self.players = list()
self.state = catan.states.GameStateNotInGame(self)
self.last_roll = None
self.last_player_to_roll = None
self._cur_player = None
self._cur_turn = 0
self.notify_observers()
def get_cur_player(self):
if self._cur_player is None:
return Player(1, 'nobody', 'nobody')
else:
return Player(self._cur_player.seat, self._cur_player.name, self._cur_player.color)
def set_cur_player(self, player):
self._cur_player = Player(player.seat, player.name, player.color)
def set_players(self, players):
self.players = list(players)
self.set_cur_player(self.players[0])
self.notify_observers()
def cur_player_has_port_type(self, port_type):
return self.player_has_port_type(self.get_cur_player(), port_type)
def player_has_port_type(self, player, port_type):
for port in self.board.ports:
if port.type == port_type and self._player_has_port(player, port):
return True
return False
def _player_has_port(self, player, port):
edge_coord = hexgrid.edge_coord_in_direction(port.tile_id, port.direction)
for node in hexgrid.nodes_touching_edge(edge_coord):
pieces = self.board.get_pieces((catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), node)
if len(pieces) < 1:
continue
elif len(pieces) > 1:
raise Exception('Probably a bug, num={} pieces found on node={}'.format(
len(pieces), node
))
assert len(pieces) == 1 # will be asserted by previous if/elif combo
piece = pieces[0]
if piece.owner == player:
return True
return False
@undoredo.undoable
def roll(self, roll):
self.catanlog.log_roll(self.get_cur_player(), roll)
self.last_roll = roll
self.last_player_to_roll = self.get_cur_player()
if int(roll) == 7:
self.set_state(catan.states.GameStateMoveRobber(self))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def move_robber(self, tile):
self.state.move_robber(tile)
@undoredo.undoable
def steal(self, victim):
if victim is None:
victim = Player(1, 'nobody', 'nobody')
self.state.steal(victim)
def stealable_players(self):
if self.robber_tile is None:
return list()
stealable = set()
for node in hexgrid.nodes_touching_tile(self.robber_tile):
pieces = self.board.get_pieces(types=(catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), coord=node)
if pieces:
logging.debug('found stealable player={}, cur={}'.format(pieces[0].owner, self.get_cur_player()))
stealable.add(pieces[0].owner)
if self.get_cur_player() in stealable:
stealable.remove(self.get_cur_player())
logging.debug('stealable players={} at robber tile={}'.format(stealable, self.robber_tile))
return stealable
@undoredo.undoable
def begin_placing(self, piece_type):
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, piece_type))
else:
self.set_state(catan.states.GameStatePlacingPiece(self, piece_type))
# @undoredo.undoable # state.place_road calls this, place_road is undoable
def buy_road(self, edge):
#self.assert_legal_road(edge)
piece = catan.pieces.Piece(catan.pieces.PieceType.road, self.get_cur_player())
self.board.place_piece(piece, edge)
self.catanlog.log_buys_road(self.get_cur_player(), hexgrid.location(hexgrid.EDGE, edge))
if self.state.is_in_pregame():
self.end_turn()
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_settlement calls this, place_settlement is undoable
def buy_settlement(self, node):
#self.assert_legal_settlement(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.settlement, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_settlement(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.road))
else:
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
# @undoredo.undoable # state.place_city calls this, place_city is undoable
def buy_city(self, node):
#self.assert_legal_city(node)
piece = catan.pieces.Piece(catan.pieces.PieceType.city, self.get_cur_player())
self.board.place_piece(piece, node)
self.catanlog.log_buys_city(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node))
self.set_state(catan.states.GameStateDuringTurnAfterRoll(self))
@undoredo.undoable
def buy_dev_card(self):
self.catanlog.log_buys_dev_card(self.get_cur_player())
self.notify_observers()
@undoredo.undoable
def place_road(self, edge_coord):
self.state.place_road(edge_coord)
@undoredo.undoable
def place_settlement(self, node_coord):
self.state.place_settlement(node_coord)
@undoredo.undoable
def place_city(self, node_coord):
self.state.place_city(node_coord)
@undoredo.undoable
def trade(self, trade):
giver = trade.giver()
giving = trade.giving()
getting = trade.getting()
if hasattr(trade.getter(), 'type') and trade.getter().type in catan.board.PortType:
getter = trade.getter()
self.catanlog.log_trades_with_port(giver, giving, getter, getting)
logging.debug('trading {} to port={} to get={}'.format(giving, getter, getting))
else:
getter = trade.getter()
self.catanlog.log_trades_with_player(giver, giving, getter, getting)
logging.debug('trading {} to player={} to get={}'.format(giving, getter, getting))
self.notify_observers()
@undoredo.undoable
def play_knight(self):
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
self.set_state(catan.states.GameStateMoveRobberUsingKnight(self))
@undoredo.undoable
def play_monopoly(self, resource):
self.catanlog.log_plays_monopoly(self.get_cur_player(), resource)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_year_of_plenty(self, resource1, resource2):
self.catanlog.log_plays_year_of_plenty(self.get_cur_player(), resource1, resource2)
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_road_builder(self, edge1, edge2):
self.catanlog.log_plays_road_builder(self.get_cur_player(),
hexgrid.location(hexgrid.EDGE, edge1),
hexgrid.location(hexgrid.EDGE, edge2))
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def play_victory_point(self):
self.catanlog.log_plays_victory_point(self.get_cur_player())
self.set_dev_card_state(catan.states.DevCardPlayedState(self))
@undoredo.undoable
def end_turn(self):
self.catanlog.log_ends_turn(self.get_cur_player())
self.set_cur_player(self.state.next_player())
self._cur_turn += 1
self.set_dev_card_state(catan.states.DevCardNotPlayedState(self))
if self.state.is_in_pregame():
self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement))
else:
self.set_state(catan.states.GameStateBeginTurn(self))
@classmethod
def get_debug_players(cls):
return [Player(1, 'yurick', 'green'),
Player(2, 'josh', 'blue'),
Player(3, 'zach', 'orange'),
Player(4, 'ross', 'red')]
|
rosshamish/catan-py
|
catan/board.py
|
Board.restore
|
python
|
def restore(self, board):
self.tiles = board.tiles
self.ports = board.ports
self.state = board.state
self.state.board = self
self.pieces = board.pieces
self.opts = board.opts
self.observers = board.observers
self.notify_observers()
|
Restore this Board object to match the properties and state of the given Board object
:param board: properties to restore to the current (self) Board
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/board.py#L62-L77
|
[
"def notify_observers(self):\n for obs in self.observers:\n obs.notify(self)\n"
] |
class Board(object):
"""
class Board represents a catan board. It has tiles, ports, and pieces.
A Board has pieces, which is a dictionary mapping (hexgrid.TYPE, coord) -> Piece.
Use #place_piece, #move_piece, and #remove_piece to manage pieces on the board.
Use #get_pieces to get all the pieces at a particular coordinate of the allowed types.
"""
def __init__(self, board=None, terrain=None, numbers=None, ports=None, pieces=None, players=None):
"""
Create a new board. Creation will be delegated to module boardbuilder.
:param terrain: terrain option, boardbuilder.Opt
:param numbers: numbers option, boardbuilder.Opt
:param ports: ports option, boardbuilder.Opt
:param pieces: pieces option, boardbuilder.Opt
:param players: players option, boardbuilder.Opt
"""
self.tiles = list()
self.ports = list()
self.state = states.BoardState(self)
self.pieces = dict()
self.opts = dict()
if board is not None:
self.opts['board'] = board
if terrain is not None:
self.opts['terrain'] = terrain
if numbers is not None:
self.opts['numbers'] = numbers
if ports is not None:
self.opts['ports'] = ports
if pieces is not None:
self.opts['pieces'] = pieces
if players is not None:
self.opts['players'] = players
self.reset()
self.observers = set()
def __deepcopy__(self, memo):
cls = self.__class__
result = object.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == 'observers':
setattr(result, k, set(v))
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def notify_observers(self):
for obs in self.observers:
obs.notify(self)
def lock(self):
self.state = states.BoardStateLocked(self)
for port in self.ports.copy():
if port.type == PortType.none:
self.ports.remove(port)
self.notify_observers()
def unlock(self):
self.state = states.BoardStateModifiable(self)
def reset(self, board=None, terrain=None, numbers=None, ports=None, pieces=None, players=None):
opts = self.opts.copy()
if board is not None:
opts['board'] = board
if terrain is not None:
opts['terrain'] = terrain
if numbers is not None:
opts['numbers'] = numbers
if ports is not None:
opts['ports'] = ports
if pieces is not None:
opts['pieces'] = pieces
if players is not None:
opts['players'] = players
boardbuilder.reset(self, opts=opts)
def can_place_piece(self, piece, coord):
if piece.type == PieceType.road:
logging.warning('"Can place road" not yet implemented')
return True
elif piece.type == PieceType.settlement:
logging.warning('"Can place settlement" not yet implemented')
return True
elif piece.type == PieceType.city:
logging.warning('"Can place city" not yet implemented')
return True
elif piece.type == PieceType.robber:
logging.warning('"Can place robber" not yet implemented')
return True
else:
logging.debug('Can\'t place piece={} on coord={}'.format(
piece.value, hex(coord)
))
return self.pieces.get(coord) is None
def place_piece(self, piece, coord):
if not self.can_place_piece(piece, coord):
logging.critical('ILLEGAL: Attempted to place piece={} on coord={}'.format(
piece.value, hex(coord)
))
logging.debug('Placed piece={} on coord={}'.format(
piece, hex(coord)
))
hex_type = self._piece_type_to_hex_type(piece.type)
self.pieces[(hex_type, coord)] = piece
def move_piece(self, piece, from_coord, to_coord):
from_index = (self._piece_type_to_hex_type(piece.type), from_coord)
if from_index not in self.pieces:
logging.warning('Attempted to move piece={} which was NOT on the board'.format(from_index))
return
self.place_piece(piece, to_coord)
self.remove_piece(piece, from_coord)
def remove_piece(self, piece, coord):
index = (self._piece_type_to_hex_type(piece.type), coord)
try:
self.pieces.pop(index)
logging.debug('Removed piece={}'.format(index))
except ValueError:
logging.critical('Attempted to remove piece={} which was NOT on the board'.format(index))
def get_pieces(self, types=tuple(), coord=None):
if coord is None:
logging.critical('Attempted to get_piece with coord={}'.format(coord))
return Piece(None, None)
indexes = set((self._piece_type_to_hex_type(t), coord) for t in types)
pieces = [self.pieces[idx] for idx in indexes if idx in self.pieces]
if len(pieces) == 0:
#logging.warning('Found zero pieces at {}'.format(indexes))
pass
elif len(pieces) == 1:
logging.debug('Found one piece at {}: {}'.format(indexes, pieces[0]))
elif len(pieces) > 1:
logging.debug('Found {} pieces at {}: {}'.format(len(pieces), indexes, coord, pieces))
return pieces
def get_port_at(self, tile_id, direction):
"""
If no port is found, a new none port is made and added to self.ports.
Returns the port.
:param tile_id:
:param direction:
:return: Port
"""
for port in self.ports:
if port.tile_id == tile_id and port.direction == direction:
return port
port = Port(tile_id, direction, PortType.none)
self.ports.append(port)
return port
def _piece_type_to_hex_type(self, piece_type):
if piece_type in (PieceType.road, ):
return hexgrid.EDGE
elif piece_type in (PieceType.settlement, PieceType.city):
return hexgrid.NODE
elif piece_type in (PieceType.robber, ):
return hexgrid.TILE
else:
logging.critical('piece type={} has no corresponding hex type. Returning None'.format(piece_type))
return None
def cycle_hex_type(self, tile_id):
if self.state.modifiable():
tile = self.tiles[tile_id - 1]
next_idx = (list(Terrain).index(tile.terrain) + 1) % len(Terrain)
next_terrain = list(Terrain)[next_idx]
tile.terrain = next_terrain
else:
logging.debug('Attempted to cycle terrain on tile={} on a locked board'.format(tile_id))
self.notify_observers()
def cycle_hex_number(self, tile_id):
if self.state.modifiable():
tile = self.tiles[tile_id - 1]
next_idx = (list(HexNumber).index(tile.number) + 1) % len(HexNumber)
next_hex_number = list(HexNumber)[next_idx]
tile.number = next_hex_number
else:
logging.debug('Attempted to cycle number on tile={} on a locked board'.format(tile_id))
self.notify_observers()
def cycle_port_type(self, tile_id, direction):
if self.state.modifiable():
port = self.get_port_at(tile_id, direction)
port.type = PortType.next_ui(port.type)
else:
logging.debug('Attempted to cycle port on coord=({},{}) on a locked board'.format(tile_id, direction))
self.notify_observers()
def rotate_ports(self):
"""
Rotates the ports 90 degrees. Useful when using the default port setup but the spectator is watching
at a "rotated" angle from "true north".
"""
for port in self.ports:
port.tile_id = ((port.tile_id + 1) % len(hexgrid.coastal_tile_ids())) + 1
port.direction = hexgrid.rotate_direction(hexgrid.EDGE, port.direction, ccw=True)
self.notify_observers()
def set_terrain(self, terrain):
self.tiles = [Tile(tile.tile_id, t, tile.number) for t, tile in zip(terrain, self.tiles)]
def set_numbers(self, numbers):
self.tiles = [Tile(tile.tile_id, tile.terrain, n) for n, tile in zip(numbers, self.tiles)]
def set_ports(self, ports):
self.ports = ports
|
rosshamish/catan-py
|
catan/board.py
|
Board.get_port_at
|
python
|
def get_port_at(self, tile_id, direction):
for port in self.ports:
if port.tile_id == tile_id and port.direction == direction:
return port
port = Port(tile_id, direction, PortType.none)
self.ports.append(port)
return port
|
If no port is found, a new none port is made and added to self.ports.
Returns the port.
:param tile_id:
:param direction:
:return: Port
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/board.py#L170-L185
| null |
class Board(object):
"""
class Board represents a catan board. It has tiles, ports, and pieces.
A Board has pieces, which is a dictionary mapping (hexgrid.TYPE, coord) -> Piece.
Use #place_piece, #move_piece, and #remove_piece to manage pieces on the board.
Use #get_pieces to get all the pieces at a particular coordinate of the allowed types.
"""
def __init__(self, board=None, terrain=None, numbers=None, ports=None, pieces=None, players=None):
"""
Create a new board. Creation will be delegated to module boardbuilder.
:param terrain: terrain option, boardbuilder.Opt
:param numbers: numbers option, boardbuilder.Opt
:param ports: ports option, boardbuilder.Opt
:param pieces: pieces option, boardbuilder.Opt
:param players: players option, boardbuilder.Opt
"""
self.tiles = list()
self.ports = list()
self.state = states.BoardState(self)
self.pieces = dict()
self.opts = dict()
if board is not None:
self.opts['board'] = board
if terrain is not None:
self.opts['terrain'] = terrain
if numbers is not None:
self.opts['numbers'] = numbers
if ports is not None:
self.opts['ports'] = ports
if pieces is not None:
self.opts['pieces'] = pieces
if players is not None:
self.opts['players'] = players
self.reset()
self.observers = set()
def __deepcopy__(self, memo):
cls = self.__class__
result = object.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == 'observers':
setattr(result, k, set(v))
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def restore(self, board):
"""
Restore this Board object to match the properties and state of the given Board object
:param board: properties to restore to the current (self) Board
"""
self.tiles = board.tiles
self.ports = board.ports
self.state = board.state
self.state.board = self
self.pieces = board.pieces
self.opts = board.opts
self.observers = board.observers
self.notify_observers()
def notify_observers(self):
for obs in self.observers:
obs.notify(self)
def lock(self):
self.state = states.BoardStateLocked(self)
for port in self.ports.copy():
if port.type == PortType.none:
self.ports.remove(port)
self.notify_observers()
def unlock(self):
self.state = states.BoardStateModifiable(self)
def reset(self, board=None, terrain=None, numbers=None, ports=None, pieces=None, players=None):
opts = self.opts.copy()
if board is not None:
opts['board'] = board
if terrain is not None:
opts['terrain'] = terrain
if numbers is not None:
opts['numbers'] = numbers
if ports is not None:
opts['ports'] = ports
if pieces is not None:
opts['pieces'] = pieces
if players is not None:
opts['players'] = players
boardbuilder.reset(self, opts=opts)
def can_place_piece(self, piece, coord):
if piece.type == PieceType.road:
logging.warning('"Can place road" not yet implemented')
return True
elif piece.type == PieceType.settlement:
logging.warning('"Can place settlement" not yet implemented')
return True
elif piece.type == PieceType.city:
logging.warning('"Can place city" not yet implemented')
return True
elif piece.type == PieceType.robber:
logging.warning('"Can place robber" not yet implemented')
return True
else:
logging.debug('Can\'t place piece={} on coord={}'.format(
piece.value, hex(coord)
))
return self.pieces.get(coord) is None
def place_piece(self, piece, coord):
if not self.can_place_piece(piece, coord):
logging.critical('ILLEGAL: Attempted to place piece={} on coord={}'.format(
piece.value, hex(coord)
))
logging.debug('Placed piece={} on coord={}'.format(
piece, hex(coord)
))
hex_type = self._piece_type_to_hex_type(piece.type)
self.pieces[(hex_type, coord)] = piece
def move_piece(self, piece, from_coord, to_coord):
from_index = (self._piece_type_to_hex_type(piece.type), from_coord)
if from_index not in self.pieces:
logging.warning('Attempted to move piece={} which was NOT on the board'.format(from_index))
return
self.place_piece(piece, to_coord)
self.remove_piece(piece, from_coord)
def remove_piece(self, piece, coord):
index = (self._piece_type_to_hex_type(piece.type), coord)
try:
self.pieces.pop(index)
logging.debug('Removed piece={}'.format(index))
except ValueError:
logging.critical('Attempted to remove piece={} which was NOT on the board'.format(index))
def get_pieces(self, types=tuple(), coord=None):
if coord is None:
logging.critical('Attempted to get_piece with coord={}'.format(coord))
return Piece(None, None)
indexes = set((self._piece_type_to_hex_type(t), coord) for t in types)
pieces = [self.pieces[idx] for idx in indexes if idx in self.pieces]
if len(pieces) == 0:
#logging.warning('Found zero pieces at {}'.format(indexes))
pass
elif len(pieces) == 1:
logging.debug('Found one piece at {}: {}'.format(indexes, pieces[0]))
elif len(pieces) > 1:
logging.debug('Found {} pieces at {}: {}'.format(len(pieces), indexes, coord, pieces))
return pieces
def _piece_type_to_hex_type(self, piece_type):
if piece_type in (PieceType.road, ):
return hexgrid.EDGE
elif piece_type in (PieceType.settlement, PieceType.city):
return hexgrid.NODE
elif piece_type in (PieceType.robber, ):
return hexgrid.TILE
else:
logging.critical('piece type={} has no corresponding hex type. Returning None'.format(piece_type))
return None
def cycle_hex_type(self, tile_id):
if self.state.modifiable():
tile = self.tiles[tile_id - 1]
next_idx = (list(Terrain).index(tile.terrain) + 1) % len(Terrain)
next_terrain = list(Terrain)[next_idx]
tile.terrain = next_terrain
else:
logging.debug('Attempted to cycle terrain on tile={} on a locked board'.format(tile_id))
self.notify_observers()
def cycle_hex_number(self, tile_id):
if self.state.modifiable():
tile = self.tiles[tile_id - 1]
next_idx = (list(HexNumber).index(tile.number) + 1) % len(HexNumber)
next_hex_number = list(HexNumber)[next_idx]
tile.number = next_hex_number
else:
logging.debug('Attempted to cycle number on tile={} on a locked board'.format(tile_id))
self.notify_observers()
def cycle_port_type(self, tile_id, direction):
if self.state.modifiable():
port = self.get_port_at(tile_id, direction)
port.type = PortType.next_ui(port.type)
else:
logging.debug('Attempted to cycle port on coord=({},{}) on a locked board'.format(tile_id, direction))
self.notify_observers()
def rotate_ports(self):
"""
Rotates the ports 90 degrees. Useful when using the default port setup but the spectator is watching
at a "rotated" angle from "true north".
"""
for port in self.ports:
port.tile_id = ((port.tile_id + 1) % len(hexgrid.coastal_tile_ids())) + 1
port.direction = hexgrid.rotate_direction(hexgrid.EDGE, port.direction, ccw=True)
self.notify_observers()
def set_terrain(self, terrain):
self.tiles = [Tile(tile.tile_id, t, tile.number) for t, tile in zip(terrain, self.tiles)]
def set_numbers(self, numbers):
self.tiles = [Tile(tile.tile_id, tile.terrain, n) for n, tile in zip(numbers, self.tiles)]
def set_ports(self, ports):
self.ports = ports
|
rosshamish/catan-py
|
catan/board.py
|
Board.rotate_ports
|
python
|
def rotate_ports(self):
for port in self.ports:
port.tile_id = ((port.tile_id + 1) % len(hexgrid.coastal_tile_ids())) + 1
port.direction = hexgrid.rotate_direction(hexgrid.EDGE, port.direction, ccw=True)
self.notify_observers()
|
Rotates the ports 90 degrees. Useful when using the default port setup but the spectator is watching
at a "rotated" angle from "true north".
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/board.py#L226-L234
|
[
"def notify_observers(self):\n for obs in self.observers:\n obs.notify(self)\n"
] |
class Board(object):
"""
class Board represents a catan board. It has tiles, ports, and pieces.
A Board has pieces, which is a dictionary mapping (hexgrid.TYPE, coord) -> Piece.
Use #place_piece, #move_piece, and #remove_piece to manage pieces on the board.
Use #get_pieces to get all the pieces at a particular coordinate of the allowed types.
"""
def __init__(self, board=None, terrain=None, numbers=None, ports=None, pieces=None, players=None):
"""
Create a new board. Creation will be delegated to module boardbuilder.
:param terrain: terrain option, boardbuilder.Opt
:param numbers: numbers option, boardbuilder.Opt
:param ports: ports option, boardbuilder.Opt
:param pieces: pieces option, boardbuilder.Opt
:param players: players option, boardbuilder.Opt
"""
self.tiles = list()
self.ports = list()
self.state = states.BoardState(self)
self.pieces = dict()
self.opts = dict()
if board is not None:
self.opts['board'] = board
if terrain is not None:
self.opts['terrain'] = terrain
if numbers is not None:
self.opts['numbers'] = numbers
if ports is not None:
self.opts['ports'] = ports
if pieces is not None:
self.opts['pieces'] = pieces
if players is not None:
self.opts['players'] = players
self.reset()
self.observers = set()
def __deepcopy__(self, memo):
cls = self.__class__
result = object.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == 'observers':
setattr(result, k, set(v))
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def restore(self, board):
"""
Restore this Board object to match the properties and state of the given Board object
:param board: properties to restore to the current (self) Board
"""
self.tiles = board.tiles
self.ports = board.ports
self.state = board.state
self.state.board = self
self.pieces = board.pieces
self.opts = board.opts
self.observers = board.observers
self.notify_observers()
def notify_observers(self):
for obs in self.observers:
obs.notify(self)
def lock(self):
self.state = states.BoardStateLocked(self)
for port in self.ports.copy():
if port.type == PortType.none:
self.ports.remove(port)
self.notify_observers()
def unlock(self):
self.state = states.BoardStateModifiable(self)
def reset(self, board=None, terrain=None, numbers=None, ports=None, pieces=None, players=None):
opts = self.opts.copy()
if board is not None:
opts['board'] = board
if terrain is not None:
opts['terrain'] = terrain
if numbers is not None:
opts['numbers'] = numbers
if ports is not None:
opts['ports'] = ports
if pieces is not None:
opts['pieces'] = pieces
if players is not None:
opts['players'] = players
boardbuilder.reset(self, opts=opts)
def can_place_piece(self, piece, coord):
if piece.type == PieceType.road:
logging.warning('"Can place road" not yet implemented')
return True
elif piece.type == PieceType.settlement:
logging.warning('"Can place settlement" not yet implemented')
return True
elif piece.type == PieceType.city:
logging.warning('"Can place city" not yet implemented')
return True
elif piece.type == PieceType.robber:
logging.warning('"Can place robber" not yet implemented')
return True
else:
logging.debug('Can\'t place piece={} on coord={}'.format(
piece.value, hex(coord)
))
return self.pieces.get(coord) is None
def place_piece(self, piece, coord):
if not self.can_place_piece(piece, coord):
logging.critical('ILLEGAL: Attempted to place piece={} on coord={}'.format(
piece.value, hex(coord)
))
logging.debug('Placed piece={} on coord={}'.format(
piece, hex(coord)
))
hex_type = self._piece_type_to_hex_type(piece.type)
self.pieces[(hex_type, coord)] = piece
def move_piece(self, piece, from_coord, to_coord):
from_index = (self._piece_type_to_hex_type(piece.type), from_coord)
if from_index not in self.pieces:
logging.warning('Attempted to move piece={} which was NOT on the board'.format(from_index))
return
self.place_piece(piece, to_coord)
self.remove_piece(piece, from_coord)
def remove_piece(self, piece, coord):
index = (self._piece_type_to_hex_type(piece.type), coord)
try:
self.pieces.pop(index)
logging.debug('Removed piece={}'.format(index))
except ValueError:
logging.critical('Attempted to remove piece={} which was NOT on the board'.format(index))
def get_pieces(self, types=tuple(), coord=None):
if coord is None:
logging.critical('Attempted to get_piece with coord={}'.format(coord))
return Piece(None, None)
indexes = set((self._piece_type_to_hex_type(t), coord) for t in types)
pieces = [self.pieces[idx] for idx in indexes if idx in self.pieces]
if len(pieces) == 0:
#logging.warning('Found zero pieces at {}'.format(indexes))
pass
elif len(pieces) == 1:
logging.debug('Found one piece at {}: {}'.format(indexes, pieces[0]))
elif len(pieces) > 1:
logging.debug('Found {} pieces at {}: {}'.format(len(pieces), indexes, coord, pieces))
return pieces
def get_port_at(self, tile_id, direction):
"""
If no port is found, a new none port is made and added to self.ports.
Returns the port.
:param tile_id:
:param direction:
:return: Port
"""
for port in self.ports:
if port.tile_id == tile_id and port.direction == direction:
return port
port = Port(tile_id, direction, PortType.none)
self.ports.append(port)
return port
def _piece_type_to_hex_type(self, piece_type):
if piece_type in (PieceType.road, ):
return hexgrid.EDGE
elif piece_type in (PieceType.settlement, PieceType.city):
return hexgrid.NODE
elif piece_type in (PieceType.robber, ):
return hexgrid.TILE
else:
logging.critical('piece type={} has no corresponding hex type. Returning None'.format(piece_type))
return None
def cycle_hex_type(self, tile_id):
if self.state.modifiable():
tile = self.tiles[tile_id - 1]
next_idx = (list(Terrain).index(tile.terrain) + 1) % len(Terrain)
next_terrain = list(Terrain)[next_idx]
tile.terrain = next_terrain
else:
logging.debug('Attempted to cycle terrain on tile={} on a locked board'.format(tile_id))
self.notify_observers()
def cycle_hex_number(self, tile_id):
if self.state.modifiable():
tile = self.tiles[tile_id - 1]
next_idx = (list(HexNumber).index(tile.number) + 1) % len(HexNumber)
next_hex_number = list(HexNumber)[next_idx]
tile.number = next_hex_number
else:
logging.debug('Attempted to cycle number on tile={} on a locked board'.format(tile_id))
self.notify_observers()
def cycle_port_type(self, tile_id, direction):
if self.state.modifiable():
port = self.get_port_at(tile_id, direction)
port.type = PortType.next_ui(port.type)
else:
logging.debug('Attempted to cycle port on coord=({},{}) on a locked board'.format(tile_id, direction))
self.notify_observers()
def set_terrain(self, terrain):
self.tiles = [Tile(tile.tile_id, t, tile.number) for t, tile in zip(terrain, self.tiles)]
def set_numbers(self, numbers):
self.tiles = [Tile(tile.tile_id, tile.terrain, n) for n, tile in zip(numbers, self.tiles)]
def set_ports(self, ports):
self.ports = ports
|
rosshamish/catan-py
|
catan/trading.py
|
CatanTrade.give
|
python
|
def give(self, terrain, num=1):
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._give.append(terrain)
|
Add a certain number of resources to the trade from giver->getter
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L26-L35
| null |
class CatanTrade(object):
"""
class CatanTrade provides a mutable trade object for catan
The trade relationship is one-to-one, and supports any number of
each of the resources going in both directions.
Usually, the current player is the giver, and the other entity the getter.
Think of it as: the current player gives resources, and gets some in return.
Use give() and get() to add resources to the trade.
Resources cannot be removed from the trade. If you want this functionality,
delete the trade and build a new one instead.
"""
def __init__(self, giver=None, getter=None):
self._give = list()
self._get = list()
self._giver = giver
self._getter = getter
def get(self, terrain, num=1):
"""
Add a certain number of resources to the trade from getter->giver
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
"""
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._get.append(terrain)
def giver(self):
return self._giver
def getter(self):
return self._getter
def giving(self):
"""
Returns tuples corresponding to the number and type of each
resource in the trade from giver->getter
:return: eg [(2, Terrain.wood), (1, Terrain.brick)]
"""
logging.debug('give={}'.format(self._give))
c = Counter(self._give.copy())
return [(n, t) for t, n in c.items()]
def getting(self):
"""
Returns tuples corresponding to the number and type of each
resource in the trade from getter->giver
:return: eg [(2, Terrain.wood), (1, Terrain.brick)]
"""
c = Counter(self._get.copy())
return [(n, t) for t, n in c.items()]
def num_giving(self):
return len(self._give)
def num_getting(self):
return len(self._get)
def set_giver(self, giver):
self._giver = giver
def set_getter(self, getter):
self._getter = getter
|
rosshamish/catan-py
|
catan/trading.py
|
CatanTrade.get
|
python
|
def get(self, terrain, num=1):
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._get.append(terrain)
|
Add a certain number of resources to the trade from getter->giver
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L37-L46
| null |
class CatanTrade(object):
"""
class CatanTrade provides a mutable trade object for catan
The trade relationship is one-to-one, and supports any number of
each of the resources going in both directions.
Usually, the current player is the giver, and the other entity the getter.
Think of it as: the current player gives resources, and gets some in return.
Use give() and get() to add resources to the trade.
Resources cannot be removed from the trade. If you want this functionality,
delete the trade and build a new one instead.
"""
def __init__(self, giver=None, getter=None):
self._give = list()
self._get = list()
self._giver = giver
self._getter = getter
def give(self, terrain, num=1):
"""
Add a certain number of resources to the trade from giver->getter
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
"""
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._give.append(terrain)
def giver(self):
return self._giver
def getter(self):
return self._getter
def giving(self):
"""
Returns tuples corresponding to the number and type of each
resource in the trade from giver->getter
:return: eg [(2, Terrain.wood), (1, Terrain.brick)]
"""
logging.debug('give={}'.format(self._give))
c = Counter(self._give.copy())
return [(n, t) for t, n in c.items()]
def getting(self):
"""
Returns tuples corresponding to the number and type of each
resource in the trade from getter->giver
:return: eg [(2, Terrain.wood), (1, Terrain.brick)]
"""
c = Counter(self._get.copy())
return [(n, t) for t, n in c.items()]
def num_giving(self):
return len(self._give)
def num_getting(self):
return len(self._get)
def set_giver(self, giver):
self._giver = giver
def set_getter(self, getter):
self._getter = getter
|
rosshamish/catan-py
|
catan/trading.py
|
CatanTrade.giving
|
python
|
def giving(self):
logging.debug('give={}'.format(self._give))
c = Counter(self._give.copy())
return [(n, t) for t, n in c.items()]
|
Returns tuples corresponding to the number and type of each
resource in the trade from giver->getter
:return: eg [(2, Terrain.wood), (1, Terrain.brick)]
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L54-L63
| null |
class CatanTrade(object):
"""
class CatanTrade provides a mutable trade object for catan
The trade relationship is one-to-one, and supports any number of
each of the resources going in both directions.
Usually, the current player is the giver, and the other entity the getter.
Think of it as: the current player gives resources, and gets some in return.
Use give() and get() to add resources to the trade.
Resources cannot be removed from the trade. If you want this functionality,
delete the trade and build a new one instead.
"""
def __init__(self, giver=None, getter=None):
self._give = list()
self._get = list()
self._giver = giver
self._getter = getter
def give(self, terrain, num=1):
"""
Add a certain number of resources to the trade from giver->getter
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
"""
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._give.append(terrain)
def get(self, terrain, num=1):
"""
Add a certain number of resources to the trade from getter->giver
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
"""
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._get.append(terrain)
def giver(self):
return self._giver
def getter(self):
return self._getter
def getting(self):
"""
Returns tuples corresponding to the number and type of each
resource in the trade from getter->giver
:return: eg [(2, Terrain.wood), (1, Terrain.brick)]
"""
c = Counter(self._get.copy())
return [(n, t) for t, n in c.items()]
def num_giving(self):
return len(self._give)
def num_getting(self):
return len(self._get)
def set_giver(self, giver):
self._giver = giver
def set_getter(self, getter):
self._getter = getter
|
rosshamish/catan-py
|
catan/trading.py
|
CatanTrade.getting
|
python
|
def getting(self):
c = Counter(self._get.copy())
return [(n, t) for t, n in c.items()]
|
Returns tuples corresponding to the number and type of each
resource in the trade from getter->giver
:return: eg [(2, Terrain.wood), (1, Terrain.brick)]
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L65-L73
| null |
class CatanTrade(object):
"""
class CatanTrade provides a mutable trade object for catan
The trade relationship is one-to-one, and supports any number of
each of the resources going in both directions.
Usually, the current player is the giver, and the other entity the getter.
Think of it as: the current player gives resources, and gets some in return.
Use give() and get() to add resources to the trade.
Resources cannot be removed from the trade. If you want this functionality,
delete the trade and build a new one instead.
"""
def __init__(self, giver=None, getter=None):
self._give = list()
self._get = list()
self._giver = giver
self._getter = getter
def give(self, terrain, num=1):
"""
Add a certain number of resources to the trade from giver->getter
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
"""
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._give.append(terrain)
def get(self, terrain, num=1):
"""
Add a certain number of resources to the trade from getter->giver
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
"""
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._get.append(terrain)
def giver(self):
return self._giver
def getter(self):
return self._getter
def giving(self):
"""
Returns tuples corresponding to the number and type of each
resource in the trade from giver->getter
:return: eg [(2, Terrain.wood), (1, Terrain.brick)]
"""
logging.debug('give={}'.format(self._give))
c = Counter(self._give.copy())
return [(n, t) for t, n in c.items()]
def num_giving(self):
return len(self._give)
def num_getting(self):
return len(self._get)
def set_giver(self, giver):
self._giver = giver
def set_getter(self, getter):
self._getter = getter
|
rosshamish/catan-py
|
catan/boardbuilder.py
|
get_opts
|
python
|
def get_opts(opts):
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.preset,
'ports': Opt.preset,
'pieces': Opt.preset,
'players': Opt.preset,
}
_opts = defaults.copy()
if opts is None:
opts = dict()
try:
for key, val in opts.copy().items():
if key == 'board':
# board is a string, not a regular opt, and gets special handling
# in _read_tiles_from_string
continue
opts[key] = Opt(val)
_opts.update(opts)
except Exception:
raise ValueError('Invalid options={}'.format(opts))
logging.debug('used defaults=\n{}\n on opts=\n{}\nreturned total opts=\n{}'.format(
pprint.pformat(defaults),
pprint.pformat(opts),
pprint.pformat(_opts)))
return _opts
|
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L40-L72
| null |
"""
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts to convert a dictionary mapping str->str to a dictionary
mapping str->Opts. #get_opts will also apply the default option values
for each option not supplied.
Use #build to build a new board with the passed options.
Use #modify to modify an existing board instead of building a new one.
This will reset the board. #reset is an alias.
"""
from enum import Enum
import logging
import pprint
import random
import hexgrid
import catan.game
import catan.states
import catan.board
import catan.pieces
class Opt(Enum):
empty = 'empty'
random = 'random'
preset = 'preset'
debug = 'debug'
def __repr__(self):
return 'opt:{}'.format(self.value)
def build(opts=None):
"""
Build a new board using the given options.
:param opts: dictionary mapping str->Opt
:return: the new board, Board
"""
board = catan.board.Board()
modify(board, opts)
return board
def reset(board, opts=None):
"""
Alias for #modify. Resets an existing board.
"""
modify(board, opts)
return None
def modify(board, opts=None):
"""
Reset an existing board using the given options.
:param board: the board to reset
:param opts: dictionary mapping str->Opt
:return: None
"""
opts = get_opts(opts)
if opts['board'] is not None:
board.tiles = _read_tiles_from_string(opts['board'])
else:
board.tiles = _generate_tiles(opts['terrain'], opts['numbers'])
board.ports = _get_ports(opts['ports'])
board.state = catan.states.BoardStateModifiable(board)
board.pieces = _get_pieces(board.tiles, board.ports, opts['players'], opts['pieces'])
return None
def _get_tiles(board=None, terrain=None, numbers=None):
"""
Generate a list of tiles using the given terrain and numbers options.
terrain options supported:
- Opt.empty -> all tiles are desert
- Opt.random -> tiles are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
numbers options supported:
- Opt.empty -> no tiles have numbers
- Opt.random -> numbers are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
:param terrain_opts: Opt
:param numbers_opts: Opt
:return: list(Tile)
"""
if board is not None:
# we have a board given, ignore the terrain and numbers opts and log warnings
# if they were supplied
tiles = _read_tiles_from_string(board)
else:
# we are being asked to generate a board
tiles = _generate_tiles(terrain, numbers)
return tiles
def _read_tiles_from_string(board_str):
terrain = [catan.board.Terrain.from_short_form(char) for char in board_str.split(' ')
if char in ('w', 'b', 'h', 's', 'o', 'd')]
numbers = [catan.board.HexNumber.from_digit_or_none(num) for num in board_str.split(' ')
if num in ('2','3','4','5','6','8','9','10','11','12','None')]
logging.info('terrain:{}, numbers:{}'.format(terrain, numbers))
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _generate_tiles(terrain_opts, numbers_opts):
terrain = None
numbers = None
if terrain_opts == Opt.empty:
terrain = ([catan.board.Terrain.desert] * catan.board.NUM_TILES)
elif terrain_opts in (Opt.random, Opt.debug):
terrain = ([catan.board.Terrain.desert] +
[catan.board.Terrain.brick] * 3 +
[catan.board.Terrain.ore] * 3 +
[catan.board.Terrain.wood] * 4 +
[catan.board.Terrain.sheep] * 4 +
[catan.board.Terrain.wheat] * 4)
random.shuffle(terrain)
elif terrain_opts == Opt.preset:
terrain = ([catan.board.Terrain.wood,
catan.board.Terrain.wheat,
catan.board.Terrain.ore,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.brick,
catan.board.Terrain.sheep,
catan.board.Terrain.wheat,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.brick,
catan.board.Terrain.desert,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.brick])
if numbers_opts == Opt.empty:
numbers = ([catan.board.HexNumber.none] * catan.board.NUM_TILES)
elif numbers_opts in (Opt.random, Opt.debug):
numbers = ([catan.board.HexNumber.two] +
[catan.board.HexNumber.three]*2 + [catan.board.HexNumber.four]*2 +
[catan.board.HexNumber.five]*2 + [catan.board.HexNumber.six]*2 +
[catan.board.HexNumber.eight]*2 + [catan.board.HexNumber.nine]*2 +
[catan.board.HexNumber.ten]*2 + [catan.board.HexNumber.eleven]*2 +
[catan.board.HexNumber.twelve])
random.shuffle(numbers)
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
elif numbers_opts == Opt.preset:
numbers = ([catan.board.HexNumber.five,
catan.board.HexNumber.two,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.twelve,
catan.board.HexNumber.eleven,
catan.board.HexNumber.four,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.four,
catan.board.HexNumber.five,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eleven])
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
assert len(numbers) == catan.board.NUM_TILES
assert len(terrain) == catan.board.NUM_TILES
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _get_ports(port_opts):
"""
Generate a list of ports using the given options.
port options supported:
- Opt.empty ->
- Opt.random ->
- Opt.preset -> ports are in default locations
- Opt.debug -> alias for Opt.preset
:param port_opts: Opt
:return: list(Port)
"""
if port_opts in [Opt.preset, Opt.debug]:
_preset_ports = [(1, 'NW', catan.board.PortType.any3),
(2, 'W', catan.board.PortType.wood),
(4, 'W', catan.board.PortType.brick),
(5, 'SW', catan.board.PortType.any3),
(6, 'SE', catan.board.PortType.any3),
(8, 'SE', catan.board.PortType.sheep),
(9, 'E', catan.board.PortType.any3),
(10, 'NE', catan.board.PortType.ore),
(12, 'NE', catan.board.PortType.wheat)]
return [catan.board.Port(tile, dir, port_type)
for tile, dir, port_type in _preset_ports]
elif port_opts in [Opt.empty, Opt.random]:
logging.warning('{} option not yet implemented'.format(port_opts))
return []
def _get_pieces(tiles, ports, players_opts, pieces_opts):
"""
Generate a dictionary of pieces using the given options.
pieces options supported:
- Opt.empty -> no locations have pieces
- Opt.random ->
- Opt.preset -> robber is placed on the first desert found
- Opt.debug -> a variety of pieces are placed around the board
:param tiles: list of tiles from _generate_tiles
:param ports: list of ports from _generate_ports
:param players_opts: Opt
:param pieces_opts: Opt
:return: dictionary mapping (hexgrid.TYPE, coord:int) -> Piece
"""
if pieces_opts == Opt.empty:
return dict()
elif pieces_opts == Opt.debug:
players = catan.game.Game.get_debug_players()
return {
(hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]),
(hexgrid.EDGE, 0x22): catan.pieces.Piece(catan.pieces.PieceType.road, players[0]),
(hexgrid.NODE, 0x67): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[1]),
(hexgrid.EDGE, 0x98): catan.pieces.Piece(catan.pieces.PieceType.road, players[1]),
(hexgrid.NODE, 0x87): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[2]),
(hexgrid.EDGE, 0x89): catan.pieces.Piece(catan.pieces.PieceType.road, players[2]),
(hexgrid.EDGE, 0xA9): catan.pieces.Piece(catan.pieces.PieceType.road, players[3]),
(hexgrid.TILE, 0x77): catan.pieces.Piece(catan.pieces.PieceType.robber, None),
}
elif pieces_opts in (Opt.preset, ):
deserts = filter(lambda tile: tile.terrain == catan.board.Terrain.desert, tiles)
coord = hexgrid.tile_id_to_coord(list(deserts)[0].tile_id)
return {
(hexgrid.TILE, coord): catan.pieces.Piece(catan.pieces.PieceType.robber, None)
}
elif pieces_opts in (Opt.random, ):
logging.warning('{} option not yet implemented'.format(pieces_opts))
def _check_red_placement(tiles):
"""
Returns True if no red numbers are on adjacent tiles.
Returns False if any red numbers are on adjacent tiles.
Not yet implemented.
"""
logging.warning('"Check red placement" not yet implemented')
|
rosshamish/catan-py
|
catan/boardbuilder.py
|
build
|
python
|
def build(opts=None):
board = catan.board.Board()
modify(board, opts)
return board
|
Build a new board using the given options.
:param opts: dictionary mapping str->Opt
:return: the new board, Board
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L75-L83
|
[
"def modify(board, opts=None):\n \"\"\"\n Reset an existing board using the given options.\n :param board: the board to reset\n :param opts: dictionary mapping str->Opt\n :return: None\n \"\"\"\n opts = get_opts(opts)\n if opts['board'] is not None:\n board.tiles = _read_tiles_from_string(opts['board'])\n else:\n board.tiles = _generate_tiles(opts['terrain'], opts['numbers'])\n board.ports = _get_ports(opts['ports'])\n board.state = catan.states.BoardStateModifiable(board)\n board.pieces = _get_pieces(board.tiles, board.ports, opts['players'], opts['pieces'])\n return None\n"
] |
"""
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts to convert a dictionary mapping str->str to a dictionary
mapping str->Opts. #get_opts will also apply the default option values
for each option not supplied.
Use #build to build a new board with the passed options.
Use #modify to modify an existing board instead of building a new one.
This will reset the board. #reset is an alias.
"""
from enum import Enum
import logging
import pprint
import random
import hexgrid
import catan.game
import catan.states
import catan.board
import catan.pieces
class Opt(Enum):
empty = 'empty'
random = 'random'
preset = 'preset'
debug = 'debug'
def __repr__(self):
return 'opt:{}'.format(self.value)
def get_opts(opts):
"""
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
"""
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.preset,
'ports': Opt.preset,
'pieces': Opt.preset,
'players': Opt.preset,
}
_opts = defaults.copy()
if opts is None:
opts = dict()
try:
for key, val in opts.copy().items():
if key == 'board':
# board is a string, not a regular opt, and gets special handling
# in _read_tiles_from_string
continue
opts[key] = Opt(val)
_opts.update(opts)
except Exception:
raise ValueError('Invalid options={}'.format(opts))
logging.debug('used defaults=\n{}\n on opts=\n{}\nreturned total opts=\n{}'.format(
pprint.pformat(defaults),
pprint.pformat(opts),
pprint.pformat(_opts)))
return _opts
def reset(board, opts=None):
"""
Alias for #modify. Resets an existing board.
"""
modify(board, opts)
return None
def modify(board, opts=None):
"""
Reset an existing board using the given options.
:param board: the board to reset
:param opts: dictionary mapping str->Opt
:return: None
"""
opts = get_opts(opts)
if opts['board'] is not None:
board.tiles = _read_tiles_from_string(opts['board'])
else:
board.tiles = _generate_tiles(opts['terrain'], opts['numbers'])
board.ports = _get_ports(opts['ports'])
board.state = catan.states.BoardStateModifiable(board)
board.pieces = _get_pieces(board.tiles, board.ports, opts['players'], opts['pieces'])
return None
def _get_tiles(board=None, terrain=None, numbers=None):
"""
Generate a list of tiles using the given terrain and numbers options.
terrain options supported:
- Opt.empty -> all tiles are desert
- Opt.random -> tiles are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
numbers options supported:
- Opt.empty -> no tiles have numbers
- Opt.random -> numbers are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
:param terrain_opts: Opt
:param numbers_opts: Opt
:return: list(Tile)
"""
if board is not None:
# we have a board given, ignore the terrain and numbers opts and log warnings
# if they were supplied
tiles = _read_tiles_from_string(board)
else:
# we are being asked to generate a board
tiles = _generate_tiles(terrain, numbers)
return tiles
def _read_tiles_from_string(board_str):
terrain = [catan.board.Terrain.from_short_form(char) for char in board_str.split(' ')
if char in ('w', 'b', 'h', 's', 'o', 'd')]
numbers = [catan.board.HexNumber.from_digit_or_none(num) for num in board_str.split(' ')
if num in ('2','3','4','5','6','8','9','10','11','12','None')]
logging.info('terrain:{}, numbers:{}'.format(terrain, numbers))
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _generate_tiles(terrain_opts, numbers_opts):
terrain = None
numbers = None
if terrain_opts == Opt.empty:
terrain = ([catan.board.Terrain.desert] * catan.board.NUM_TILES)
elif terrain_opts in (Opt.random, Opt.debug):
terrain = ([catan.board.Terrain.desert] +
[catan.board.Terrain.brick] * 3 +
[catan.board.Terrain.ore] * 3 +
[catan.board.Terrain.wood] * 4 +
[catan.board.Terrain.sheep] * 4 +
[catan.board.Terrain.wheat] * 4)
random.shuffle(terrain)
elif terrain_opts == Opt.preset:
terrain = ([catan.board.Terrain.wood,
catan.board.Terrain.wheat,
catan.board.Terrain.ore,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.brick,
catan.board.Terrain.sheep,
catan.board.Terrain.wheat,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.brick,
catan.board.Terrain.desert,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.brick])
if numbers_opts == Opt.empty:
numbers = ([catan.board.HexNumber.none] * catan.board.NUM_TILES)
elif numbers_opts in (Opt.random, Opt.debug):
numbers = ([catan.board.HexNumber.two] +
[catan.board.HexNumber.three]*2 + [catan.board.HexNumber.four]*2 +
[catan.board.HexNumber.five]*2 + [catan.board.HexNumber.six]*2 +
[catan.board.HexNumber.eight]*2 + [catan.board.HexNumber.nine]*2 +
[catan.board.HexNumber.ten]*2 + [catan.board.HexNumber.eleven]*2 +
[catan.board.HexNumber.twelve])
random.shuffle(numbers)
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
elif numbers_opts == Opt.preset:
numbers = ([catan.board.HexNumber.five,
catan.board.HexNumber.two,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.twelve,
catan.board.HexNumber.eleven,
catan.board.HexNumber.four,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.four,
catan.board.HexNumber.five,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eleven])
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
assert len(numbers) == catan.board.NUM_TILES
assert len(terrain) == catan.board.NUM_TILES
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _get_ports(port_opts):
"""
Generate a list of ports using the given options.
port options supported:
- Opt.empty ->
- Opt.random ->
- Opt.preset -> ports are in default locations
- Opt.debug -> alias for Opt.preset
:param port_opts: Opt
:return: list(Port)
"""
if port_opts in [Opt.preset, Opt.debug]:
_preset_ports = [(1, 'NW', catan.board.PortType.any3),
(2, 'W', catan.board.PortType.wood),
(4, 'W', catan.board.PortType.brick),
(5, 'SW', catan.board.PortType.any3),
(6, 'SE', catan.board.PortType.any3),
(8, 'SE', catan.board.PortType.sheep),
(9, 'E', catan.board.PortType.any3),
(10, 'NE', catan.board.PortType.ore),
(12, 'NE', catan.board.PortType.wheat)]
return [catan.board.Port(tile, dir, port_type)
for tile, dir, port_type in _preset_ports]
elif port_opts in [Opt.empty, Opt.random]:
logging.warning('{} option not yet implemented'.format(port_opts))
return []
def _get_pieces(tiles, ports, players_opts, pieces_opts):
"""
Generate a dictionary of pieces using the given options.
pieces options supported:
- Opt.empty -> no locations have pieces
- Opt.random ->
- Opt.preset -> robber is placed on the first desert found
- Opt.debug -> a variety of pieces are placed around the board
:param tiles: list of tiles from _generate_tiles
:param ports: list of ports from _generate_ports
:param players_opts: Opt
:param pieces_opts: Opt
:return: dictionary mapping (hexgrid.TYPE, coord:int) -> Piece
"""
if pieces_opts == Opt.empty:
return dict()
elif pieces_opts == Opt.debug:
players = catan.game.Game.get_debug_players()
return {
(hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]),
(hexgrid.EDGE, 0x22): catan.pieces.Piece(catan.pieces.PieceType.road, players[0]),
(hexgrid.NODE, 0x67): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[1]),
(hexgrid.EDGE, 0x98): catan.pieces.Piece(catan.pieces.PieceType.road, players[1]),
(hexgrid.NODE, 0x87): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[2]),
(hexgrid.EDGE, 0x89): catan.pieces.Piece(catan.pieces.PieceType.road, players[2]),
(hexgrid.EDGE, 0xA9): catan.pieces.Piece(catan.pieces.PieceType.road, players[3]),
(hexgrid.TILE, 0x77): catan.pieces.Piece(catan.pieces.PieceType.robber, None),
}
elif pieces_opts in (Opt.preset, ):
deserts = filter(lambda tile: tile.terrain == catan.board.Terrain.desert, tiles)
coord = hexgrid.tile_id_to_coord(list(deserts)[0].tile_id)
return {
(hexgrid.TILE, coord): catan.pieces.Piece(catan.pieces.PieceType.robber, None)
}
elif pieces_opts in (Opt.random, ):
logging.warning('{} option not yet implemented'.format(pieces_opts))
def _check_red_placement(tiles):
"""
Returns True if no red numbers are on adjacent tiles.
Returns False if any red numbers are on adjacent tiles.
Not yet implemented.
"""
logging.warning('"Check red placement" not yet implemented')
|
rosshamish/catan-py
|
catan/boardbuilder.py
|
modify
|
python
|
def modify(board, opts=None):
opts = get_opts(opts)
if opts['board'] is not None:
board.tiles = _read_tiles_from_string(opts['board'])
else:
board.tiles = _generate_tiles(opts['terrain'], opts['numbers'])
board.ports = _get_ports(opts['ports'])
board.state = catan.states.BoardStateModifiable(board)
board.pieces = _get_pieces(board.tiles, board.ports, opts['players'], opts['pieces'])
return None
|
Reset an existing board using the given options.
:param board: the board to reset
:param opts: dictionary mapping str->Opt
:return: None
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L94-L109
|
[
"def get_opts(opts):\n \"\"\"\n Validate options and apply defaults for options not supplied.\n\n :param opts: dictionary mapping str->str.\n :return: dictionary mapping str->Opt. All possible keys are present.\n \"\"\"\n defaults = {\n 'board': None,\n 'terrain': Opt.random,\n 'numbers': Opt.preset,\n 'ports': Opt.preset,\n 'pieces': Opt.preset,\n 'players': Opt.preset,\n }\n _opts = defaults.copy()\n if opts is None:\n opts = dict()\n try:\n for key, val in opts.copy().items():\n if key == 'board':\n # board is a string, not a regular opt, and gets special handling\n # in _read_tiles_from_string\n continue\n opts[key] = Opt(val)\n _opts.update(opts)\n except Exception:\n raise ValueError('Invalid options={}'.format(opts))\n logging.debug('used defaults=\\n{}\\n on opts=\\n{}\\nreturned total opts=\\n{}'.format(\n pprint.pformat(defaults),\n pprint.pformat(opts),\n pprint.pformat(_opts)))\n return _opts\n",
"def _read_tiles_from_string(board_str):\n terrain = [catan.board.Terrain.from_short_form(char) for char in board_str.split(' ')\n if char in ('w', 'b', 'h', 's', 'o', 'd')]\n numbers = [catan.board.HexNumber.from_digit_or_none(num) for num in board_str.split(' ')\n if num in ('2','3','4','5','6','8','9','10','11','12','None')]\n logging.info('terrain:{}, numbers:{}'.format(terrain, numbers))\n tile_data = list(zip(terrain, numbers))\n tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]\n\n return tiles\n",
"def _generate_tiles(terrain_opts, numbers_opts):\n terrain = None\n numbers = None\n\n if terrain_opts == Opt.empty:\n terrain = ([catan.board.Terrain.desert] * catan.board.NUM_TILES)\n elif terrain_opts in (Opt.random, Opt.debug):\n terrain = ([catan.board.Terrain.desert] +\n [catan.board.Terrain.brick] * 3 +\n [catan.board.Terrain.ore] * 3 +\n [catan.board.Terrain.wood] * 4 +\n [catan.board.Terrain.sheep] * 4 +\n [catan.board.Terrain.wheat] * 4)\n random.shuffle(terrain)\n elif terrain_opts == Opt.preset:\n terrain = ([catan.board.Terrain.wood,\n catan.board.Terrain.wheat,\n catan.board.Terrain.ore,\n catan.board.Terrain.wheat,\n catan.board.Terrain.sheep,\n catan.board.Terrain.brick,\n catan.board.Terrain.sheep,\n catan.board.Terrain.wheat,\n catan.board.Terrain.wood,\n catan.board.Terrain.ore,\n catan.board.Terrain.brick,\n catan.board.Terrain.desert,\n catan.board.Terrain.wheat,\n catan.board.Terrain.sheep,\n catan.board.Terrain.wood,\n catan.board.Terrain.ore,\n catan.board.Terrain.sheep,\n catan.board.Terrain.wood,\n catan.board.Terrain.brick])\n\n if numbers_opts == Opt.empty:\n numbers = ([catan.board.HexNumber.none] * catan.board.NUM_TILES)\n elif numbers_opts in (Opt.random, Opt.debug):\n numbers = ([catan.board.HexNumber.two] +\n [catan.board.HexNumber.three]*2 + [catan.board.HexNumber.four]*2 +\n [catan.board.HexNumber.five]*2 + [catan.board.HexNumber.six]*2 +\n [catan.board.HexNumber.eight]*2 + [catan.board.HexNumber.nine]*2 +\n [catan.board.HexNumber.ten]*2 + [catan.board.HexNumber.eleven]*2 +\n [catan.board.HexNumber.twelve])\n random.shuffle(numbers)\n numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)\n elif numbers_opts == Opt.preset:\n numbers = ([catan.board.HexNumber.five,\n catan.board.HexNumber.two,\n catan.board.HexNumber.six,\n catan.board.HexNumber.three,\n catan.board.HexNumber.eight,\n catan.board.HexNumber.ten,\n catan.board.HexNumber.nine,\n catan.board.HexNumber.twelve,\n catan.board.HexNumber.eleven,\n catan.board.HexNumber.four,\n catan.board.HexNumber.eight,\n catan.board.HexNumber.ten,\n catan.board.HexNumber.nine,\n catan.board.HexNumber.four,\n catan.board.HexNumber.five,\n catan.board.HexNumber.six,\n catan.board.HexNumber.three,\n catan.board.HexNumber.eleven])\n numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)\n\n assert len(numbers) == catan.board.NUM_TILES\n assert len(terrain) == catan.board.NUM_TILES\n\n tile_data = list(zip(terrain, numbers))\n tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]\n\n return tiles\n",
"def _get_ports(port_opts):\n \"\"\"\n Generate a list of ports using the given options.\n\n port options supported:\n - Opt.empty ->\n - Opt.random ->\n - Opt.preset -> ports are in default locations\n - Opt.debug -> alias for Opt.preset\n\n :param port_opts: Opt\n :return: list(Port)\n \"\"\"\n if port_opts in [Opt.preset, Opt.debug]:\n _preset_ports = [(1, 'NW', catan.board.PortType.any3),\n (2, 'W', catan.board.PortType.wood),\n (4, 'W', catan.board.PortType.brick),\n (5, 'SW', catan.board.PortType.any3),\n (6, 'SE', catan.board.PortType.any3),\n (8, 'SE', catan.board.PortType.sheep),\n (9, 'E', catan.board.PortType.any3),\n (10, 'NE', catan.board.PortType.ore),\n (12, 'NE', catan.board.PortType.wheat)]\n return [catan.board.Port(tile, dir, port_type)\n for tile, dir, port_type in _preset_ports]\n elif port_opts in [Opt.empty, Opt.random]:\n logging.warning('{} option not yet implemented'.format(port_opts))\n return []\n",
"def _get_pieces(tiles, ports, players_opts, pieces_opts):\n \"\"\"\n Generate a dictionary of pieces using the given options.\n\n pieces options supported:\n - Opt.empty -> no locations have pieces\n - Opt.random ->\n - Opt.preset -> robber is placed on the first desert found\n - Opt.debug -> a variety of pieces are placed around the board\n\n :param tiles: list of tiles from _generate_tiles\n :param ports: list of ports from _generate_ports\n :param players_opts: Opt\n :param pieces_opts: Opt\n :return: dictionary mapping (hexgrid.TYPE, coord:int) -> Piece\n \"\"\"\n if pieces_opts == Opt.empty:\n return dict()\n elif pieces_opts == Opt.debug:\n players = catan.game.Game.get_debug_players()\n return {\n (hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]),\n (hexgrid.EDGE, 0x22): catan.pieces.Piece(catan.pieces.PieceType.road, players[0]),\n (hexgrid.NODE, 0x67): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[1]),\n (hexgrid.EDGE, 0x98): catan.pieces.Piece(catan.pieces.PieceType.road, players[1]),\n (hexgrid.NODE, 0x87): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[2]),\n (hexgrid.EDGE, 0x89): catan.pieces.Piece(catan.pieces.PieceType.road, players[2]),\n (hexgrid.EDGE, 0xA9): catan.pieces.Piece(catan.pieces.PieceType.road, players[3]),\n (hexgrid.TILE, 0x77): catan.pieces.Piece(catan.pieces.PieceType.robber, None),\n }\n elif pieces_opts in (Opt.preset, ):\n deserts = filter(lambda tile: tile.terrain == catan.board.Terrain.desert, tiles)\n coord = hexgrid.tile_id_to_coord(list(deserts)[0].tile_id)\n return {\n (hexgrid.TILE, coord): catan.pieces.Piece(catan.pieces.PieceType.robber, None)\n }\n elif pieces_opts in (Opt.random, ):\n logging.warning('{} option not yet implemented'.format(pieces_opts))\n"
] |
"""
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts to convert a dictionary mapping str->str to a dictionary
mapping str->Opts. #get_opts will also apply the default option values
for each option not supplied.
Use #build to build a new board with the passed options.
Use #modify to modify an existing board instead of building a new one.
This will reset the board. #reset is an alias.
"""
from enum import Enum
import logging
import pprint
import random
import hexgrid
import catan.game
import catan.states
import catan.board
import catan.pieces
class Opt(Enum):
empty = 'empty'
random = 'random'
preset = 'preset'
debug = 'debug'
def __repr__(self):
return 'opt:{}'.format(self.value)
def get_opts(opts):
"""
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
"""
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.preset,
'ports': Opt.preset,
'pieces': Opt.preset,
'players': Opt.preset,
}
_opts = defaults.copy()
if opts is None:
opts = dict()
try:
for key, val in opts.copy().items():
if key == 'board':
# board is a string, not a regular opt, and gets special handling
# in _read_tiles_from_string
continue
opts[key] = Opt(val)
_opts.update(opts)
except Exception:
raise ValueError('Invalid options={}'.format(opts))
logging.debug('used defaults=\n{}\n on opts=\n{}\nreturned total opts=\n{}'.format(
pprint.pformat(defaults),
pprint.pformat(opts),
pprint.pformat(_opts)))
return _opts
def build(opts=None):
"""
Build a new board using the given options.
:param opts: dictionary mapping str->Opt
:return: the new board, Board
"""
board = catan.board.Board()
modify(board, opts)
return board
def reset(board, opts=None):
"""
Alias for #modify. Resets an existing board.
"""
modify(board, opts)
return None
def _get_tiles(board=None, terrain=None, numbers=None):
"""
Generate a list of tiles using the given terrain and numbers options.
terrain options supported:
- Opt.empty -> all tiles are desert
- Opt.random -> tiles are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
numbers options supported:
- Opt.empty -> no tiles have numbers
- Opt.random -> numbers are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
:param terrain_opts: Opt
:param numbers_opts: Opt
:return: list(Tile)
"""
if board is not None:
# we have a board given, ignore the terrain and numbers opts and log warnings
# if they were supplied
tiles = _read_tiles_from_string(board)
else:
# we are being asked to generate a board
tiles = _generate_tiles(terrain, numbers)
return tiles
def _read_tiles_from_string(board_str):
terrain = [catan.board.Terrain.from_short_form(char) for char in board_str.split(' ')
if char in ('w', 'b', 'h', 's', 'o', 'd')]
numbers = [catan.board.HexNumber.from_digit_or_none(num) for num in board_str.split(' ')
if num in ('2','3','4','5','6','8','9','10','11','12','None')]
logging.info('terrain:{}, numbers:{}'.format(terrain, numbers))
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _generate_tiles(terrain_opts, numbers_opts):
terrain = None
numbers = None
if terrain_opts == Opt.empty:
terrain = ([catan.board.Terrain.desert] * catan.board.NUM_TILES)
elif terrain_opts in (Opt.random, Opt.debug):
terrain = ([catan.board.Terrain.desert] +
[catan.board.Terrain.brick] * 3 +
[catan.board.Terrain.ore] * 3 +
[catan.board.Terrain.wood] * 4 +
[catan.board.Terrain.sheep] * 4 +
[catan.board.Terrain.wheat] * 4)
random.shuffle(terrain)
elif terrain_opts == Opt.preset:
terrain = ([catan.board.Terrain.wood,
catan.board.Terrain.wheat,
catan.board.Terrain.ore,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.brick,
catan.board.Terrain.sheep,
catan.board.Terrain.wheat,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.brick,
catan.board.Terrain.desert,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.brick])
if numbers_opts == Opt.empty:
numbers = ([catan.board.HexNumber.none] * catan.board.NUM_TILES)
elif numbers_opts in (Opt.random, Opt.debug):
numbers = ([catan.board.HexNumber.two] +
[catan.board.HexNumber.three]*2 + [catan.board.HexNumber.four]*2 +
[catan.board.HexNumber.five]*2 + [catan.board.HexNumber.six]*2 +
[catan.board.HexNumber.eight]*2 + [catan.board.HexNumber.nine]*2 +
[catan.board.HexNumber.ten]*2 + [catan.board.HexNumber.eleven]*2 +
[catan.board.HexNumber.twelve])
random.shuffle(numbers)
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
elif numbers_opts == Opt.preset:
numbers = ([catan.board.HexNumber.five,
catan.board.HexNumber.two,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.twelve,
catan.board.HexNumber.eleven,
catan.board.HexNumber.four,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.four,
catan.board.HexNumber.five,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eleven])
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
assert len(numbers) == catan.board.NUM_TILES
assert len(terrain) == catan.board.NUM_TILES
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _get_ports(port_opts):
"""
Generate a list of ports using the given options.
port options supported:
- Opt.empty ->
- Opt.random ->
- Opt.preset -> ports are in default locations
- Opt.debug -> alias for Opt.preset
:param port_opts: Opt
:return: list(Port)
"""
if port_opts in [Opt.preset, Opt.debug]:
_preset_ports = [(1, 'NW', catan.board.PortType.any3),
(2, 'W', catan.board.PortType.wood),
(4, 'W', catan.board.PortType.brick),
(5, 'SW', catan.board.PortType.any3),
(6, 'SE', catan.board.PortType.any3),
(8, 'SE', catan.board.PortType.sheep),
(9, 'E', catan.board.PortType.any3),
(10, 'NE', catan.board.PortType.ore),
(12, 'NE', catan.board.PortType.wheat)]
return [catan.board.Port(tile, dir, port_type)
for tile, dir, port_type in _preset_ports]
elif port_opts in [Opt.empty, Opt.random]:
logging.warning('{} option not yet implemented'.format(port_opts))
return []
def _get_pieces(tiles, ports, players_opts, pieces_opts):
"""
Generate a dictionary of pieces using the given options.
pieces options supported:
- Opt.empty -> no locations have pieces
- Opt.random ->
- Opt.preset -> robber is placed on the first desert found
- Opt.debug -> a variety of pieces are placed around the board
:param tiles: list of tiles from _generate_tiles
:param ports: list of ports from _generate_ports
:param players_opts: Opt
:param pieces_opts: Opt
:return: dictionary mapping (hexgrid.TYPE, coord:int) -> Piece
"""
if pieces_opts == Opt.empty:
return dict()
elif pieces_opts == Opt.debug:
players = catan.game.Game.get_debug_players()
return {
(hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]),
(hexgrid.EDGE, 0x22): catan.pieces.Piece(catan.pieces.PieceType.road, players[0]),
(hexgrid.NODE, 0x67): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[1]),
(hexgrid.EDGE, 0x98): catan.pieces.Piece(catan.pieces.PieceType.road, players[1]),
(hexgrid.NODE, 0x87): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[2]),
(hexgrid.EDGE, 0x89): catan.pieces.Piece(catan.pieces.PieceType.road, players[2]),
(hexgrid.EDGE, 0xA9): catan.pieces.Piece(catan.pieces.PieceType.road, players[3]),
(hexgrid.TILE, 0x77): catan.pieces.Piece(catan.pieces.PieceType.robber, None),
}
elif pieces_opts in (Opt.preset, ):
deserts = filter(lambda tile: tile.terrain == catan.board.Terrain.desert, tiles)
coord = hexgrid.tile_id_to_coord(list(deserts)[0].tile_id)
return {
(hexgrid.TILE, coord): catan.pieces.Piece(catan.pieces.PieceType.robber, None)
}
elif pieces_opts in (Opt.random, ):
logging.warning('{} option not yet implemented'.format(pieces_opts))
def _check_red_placement(tiles):
"""
Returns True if no red numbers are on adjacent tiles.
Returns False if any red numbers are on adjacent tiles.
Not yet implemented.
"""
logging.warning('"Check red placement" not yet implemented')
|
rosshamish/catan-py
|
catan/boardbuilder.py
|
_get_tiles
|
python
|
def _get_tiles(board=None, terrain=None, numbers=None):
if board is not None:
# we have a board given, ignore the terrain and numbers opts and log warnings
# if they were supplied
tiles = _read_tiles_from_string(board)
else:
# we are being asked to generate a board
tiles = _generate_tiles(terrain, numbers)
return tiles
|
Generate a list of tiles using the given terrain and numbers options.
terrain options supported:
- Opt.empty -> all tiles are desert
- Opt.random -> tiles are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
numbers options supported:
- Opt.empty -> no tiles have numbers
- Opt.random -> numbers are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
:param terrain_opts: Opt
:param numbers_opts: Opt
:return: list(Tile)
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L112-L140
| null |
"""
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts to convert a dictionary mapping str->str to a dictionary
mapping str->Opts. #get_opts will also apply the default option values
for each option not supplied.
Use #build to build a new board with the passed options.
Use #modify to modify an existing board instead of building a new one.
This will reset the board. #reset is an alias.
"""
from enum import Enum
import logging
import pprint
import random
import hexgrid
import catan.game
import catan.states
import catan.board
import catan.pieces
class Opt(Enum):
empty = 'empty'
random = 'random'
preset = 'preset'
debug = 'debug'
def __repr__(self):
return 'opt:{}'.format(self.value)
def get_opts(opts):
"""
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
"""
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.preset,
'ports': Opt.preset,
'pieces': Opt.preset,
'players': Opt.preset,
}
_opts = defaults.copy()
if opts is None:
opts = dict()
try:
for key, val in opts.copy().items():
if key == 'board':
# board is a string, not a regular opt, and gets special handling
# in _read_tiles_from_string
continue
opts[key] = Opt(val)
_opts.update(opts)
except Exception:
raise ValueError('Invalid options={}'.format(opts))
logging.debug('used defaults=\n{}\n on opts=\n{}\nreturned total opts=\n{}'.format(
pprint.pformat(defaults),
pprint.pformat(opts),
pprint.pformat(_opts)))
return _opts
def build(opts=None):
"""
Build a new board using the given options.
:param opts: dictionary mapping str->Opt
:return: the new board, Board
"""
board = catan.board.Board()
modify(board, opts)
return board
def reset(board, opts=None):
"""
Alias for #modify. Resets an existing board.
"""
modify(board, opts)
return None
def modify(board, opts=None):
"""
Reset an existing board using the given options.
:param board: the board to reset
:param opts: dictionary mapping str->Opt
:return: None
"""
opts = get_opts(opts)
if opts['board'] is not None:
board.tiles = _read_tiles_from_string(opts['board'])
else:
board.tiles = _generate_tiles(opts['terrain'], opts['numbers'])
board.ports = _get_ports(opts['ports'])
board.state = catan.states.BoardStateModifiable(board)
board.pieces = _get_pieces(board.tiles, board.ports, opts['players'], opts['pieces'])
return None
def _read_tiles_from_string(board_str):
terrain = [catan.board.Terrain.from_short_form(char) for char in board_str.split(' ')
if char in ('w', 'b', 'h', 's', 'o', 'd')]
numbers = [catan.board.HexNumber.from_digit_or_none(num) for num in board_str.split(' ')
if num in ('2','3','4','5','6','8','9','10','11','12','None')]
logging.info('terrain:{}, numbers:{}'.format(terrain, numbers))
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _generate_tiles(terrain_opts, numbers_opts):
terrain = None
numbers = None
if terrain_opts == Opt.empty:
terrain = ([catan.board.Terrain.desert] * catan.board.NUM_TILES)
elif terrain_opts in (Opt.random, Opt.debug):
terrain = ([catan.board.Terrain.desert] +
[catan.board.Terrain.brick] * 3 +
[catan.board.Terrain.ore] * 3 +
[catan.board.Terrain.wood] * 4 +
[catan.board.Terrain.sheep] * 4 +
[catan.board.Terrain.wheat] * 4)
random.shuffle(terrain)
elif terrain_opts == Opt.preset:
terrain = ([catan.board.Terrain.wood,
catan.board.Terrain.wheat,
catan.board.Terrain.ore,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.brick,
catan.board.Terrain.sheep,
catan.board.Terrain.wheat,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.brick,
catan.board.Terrain.desert,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.brick])
if numbers_opts == Opt.empty:
numbers = ([catan.board.HexNumber.none] * catan.board.NUM_TILES)
elif numbers_opts in (Opt.random, Opt.debug):
numbers = ([catan.board.HexNumber.two] +
[catan.board.HexNumber.three]*2 + [catan.board.HexNumber.four]*2 +
[catan.board.HexNumber.five]*2 + [catan.board.HexNumber.six]*2 +
[catan.board.HexNumber.eight]*2 + [catan.board.HexNumber.nine]*2 +
[catan.board.HexNumber.ten]*2 + [catan.board.HexNumber.eleven]*2 +
[catan.board.HexNumber.twelve])
random.shuffle(numbers)
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
elif numbers_opts == Opt.preset:
numbers = ([catan.board.HexNumber.five,
catan.board.HexNumber.two,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.twelve,
catan.board.HexNumber.eleven,
catan.board.HexNumber.four,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.four,
catan.board.HexNumber.five,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eleven])
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
assert len(numbers) == catan.board.NUM_TILES
assert len(terrain) == catan.board.NUM_TILES
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _get_ports(port_opts):
"""
Generate a list of ports using the given options.
port options supported:
- Opt.empty ->
- Opt.random ->
- Opt.preset -> ports are in default locations
- Opt.debug -> alias for Opt.preset
:param port_opts: Opt
:return: list(Port)
"""
if port_opts in [Opt.preset, Opt.debug]:
_preset_ports = [(1, 'NW', catan.board.PortType.any3),
(2, 'W', catan.board.PortType.wood),
(4, 'W', catan.board.PortType.brick),
(5, 'SW', catan.board.PortType.any3),
(6, 'SE', catan.board.PortType.any3),
(8, 'SE', catan.board.PortType.sheep),
(9, 'E', catan.board.PortType.any3),
(10, 'NE', catan.board.PortType.ore),
(12, 'NE', catan.board.PortType.wheat)]
return [catan.board.Port(tile, dir, port_type)
for tile, dir, port_type in _preset_ports]
elif port_opts in [Opt.empty, Opt.random]:
logging.warning('{} option not yet implemented'.format(port_opts))
return []
def _get_pieces(tiles, ports, players_opts, pieces_opts):
"""
Generate a dictionary of pieces using the given options.
pieces options supported:
- Opt.empty -> no locations have pieces
- Opt.random ->
- Opt.preset -> robber is placed on the first desert found
- Opt.debug -> a variety of pieces are placed around the board
:param tiles: list of tiles from _generate_tiles
:param ports: list of ports from _generate_ports
:param players_opts: Opt
:param pieces_opts: Opt
:return: dictionary mapping (hexgrid.TYPE, coord:int) -> Piece
"""
if pieces_opts == Opt.empty:
return dict()
elif pieces_opts == Opt.debug:
players = catan.game.Game.get_debug_players()
return {
(hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]),
(hexgrid.EDGE, 0x22): catan.pieces.Piece(catan.pieces.PieceType.road, players[0]),
(hexgrid.NODE, 0x67): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[1]),
(hexgrid.EDGE, 0x98): catan.pieces.Piece(catan.pieces.PieceType.road, players[1]),
(hexgrid.NODE, 0x87): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[2]),
(hexgrid.EDGE, 0x89): catan.pieces.Piece(catan.pieces.PieceType.road, players[2]),
(hexgrid.EDGE, 0xA9): catan.pieces.Piece(catan.pieces.PieceType.road, players[3]),
(hexgrid.TILE, 0x77): catan.pieces.Piece(catan.pieces.PieceType.robber, None),
}
elif pieces_opts in (Opt.preset, ):
deserts = filter(lambda tile: tile.terrain == catan.board.Terrain.desert, tiles)
coord = hexgrid.tile_id_to_coord(list(deserts)[0].tile_id)
return {
(hexgrid.TILE, coord): catan.pieces.Piece(catan.pieces.PieceType.robber, None)
}
elif pieces_opts in (Opt.random, ):
logging.warning('{} option not yet implemented'.format(pieces_opts))
def _check_red_placement(tiles):
"""
Returns True if no red numbers are on adjacent tiles.
Returns False if any red numbers are on adjacent tiles.
Not yet implemented.
"""
logging.warning('"Check red placement" not yet implemented')
|
rosshamish/catan-py
|
catan/boardbuilder.py
|
_get_ports
|
python
|
def _get_ports(port_opts):
if port_opts in [Opt.preset, Opt.debug]:
_preset_ports = [(1, 'NW', catan.board.PortType.any3),
(2, 'W', catan.board.PortType.wood),
(4, 'W', catan.board.PortType.brick),
(5, 'SW', catan.board.PortType.any3),
(6, 'SE', catan.board.PortType.any3),
(8, 'SE', catan.board.PortType.sheep),
(9, 'E', catan.board.PortType.any3),
(10, 'NE', catan.board.PortType.ore),
(12, 'NE', catan.board.PortType.wheat)]
return [catan.board.Port(tile, dir, port_type)
for tile, dir, port_type in _preset_ports]
elif port_opts in [Opt.empty, Opt.random]:
logging.warning('{} option not yet implemented'.format(port_opts))
return []
|
Generate a list of ports using the given options.
port options supported:
- Opt.empty ->
- Opt.random ->
- Opt.preset -> ports are in default locations
- Opt.debug -> alias for Opt.preset
:param port_opts: Opt
:return: list(Port)
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L231-L258
| null |
"""
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts to convert a dictionary mapping str->str to a dictionary
mapping str->Opts. #get_opts will also apply the default option values
for each option not supplied.
Use #build to build a new board with the passed options.
Use #modify to modify an existing board instead of building a new one.
This will reset the board. #reset is an alias.
"""
from enum import Enum
import logging
import pprint
import random
import hexgrid
import catan.game
import catan.states
import catan.board
import catan.pieces
class Opt(Enum):
empty = 'empty'
random = 'random'
preset = 'preset'
debug = 'debug'
def __repr__(self):
return 'opt:{}'.format(self.value)
def get_opts(opts):
"""
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
"""
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.preset,
'ports': Opt.preset,
'pieces': Opt.preset,
'players': Opt.preset,
}
_opts = defaults.copy()
if opts is None:
opts = dict()
try:
for key, val in opts.copy().items():
if key == 'board':
# board is a string, not a regular opt, and gets special handling
# in _read_tiles_from_string
continue
opts[key] = Opt(val)
_opts.update(opts)
except Exception:
raise ValueError('Invalid options={}'.format(opts))
logging.debug('used defaults=\n{}\n on opts=\n{}\nreturned total opts=\n{}'.format(
pprint.pformat(defaults),
pprint.pformat(opts),
pprint.pformat(_opts)))
return _opts
def build(opts=None):
"""
Build a new board using the given options.
:param opts: dictionary mapping str->Opt
:return: the new board, Board
"""
board = catan.board.Board()
modify(board, opts)
return board
def reset(board, opts=None):
"""
Alias for #modify. Resets an existing board.
"""
modify(board, opts)
return None
def modify(board, opts=None):
"""
Reset an existing board using the given options.
:param board: the board to reset
:param opts: dictionary mapping str->Opt
:return: None
"""
opts = get_opts(opts)
if opts['board'] is not None:
board.tiles = _read_tiles_from_string(opts['board'])
else:
board.tiles = _generate_tiles(opts['terrain'], opts['numbers'])
board.ports = _get_ports(opts['ports'])
board.state = catan.states.BoardStateModifiable(board)
board.pieces = _get_pieces(board.tiles, board.ports, opts['players'], opts['pieces'])
return None
def _get_tiles(board=None, terrain=None, numbers=None):
"""
Generate a list of tiles using the given terrain and numbers options.
terrain options supported:
- Opt.empty -> all tiles are desert
- Opt.random -> tiles are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
numbers options supported:
- Opt.empty -> no tiles have numbers
- Opt.random -> numbers are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
:param terrain_opts: Opt
:param numbers_opts: Opt
:return: list(Tile)
"""
if board is not None:
# we have a board given, ignore the terrain and numbers opts and log warnings
# if they were supplied
tiles = _read_tiles_from_string(board)
else:
# we are being asked to generate a board
tiles = _generate_tiles(terrain, numbers)
return tiles
def _read_tiles_from_string(board_str):
terrain = [catan.board.Terrain.from_short_form(char) for char in board_str.split(' ')
if char in ('w', 'b', 'h', 's', 'o', 'd')]
numbers = [catan.board.HexNumber.from_digit_or_none(num) for num in board_str.split(' ')
if num in ('2','3','4','5','6','8','9','10','11','12','None')]
logging.info('terrain:{}, numbers:{}'.format(terrain, numbers))
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _generate_tiles(terrain_opts, numbers_opts):
terrain = None
numbers = None
if terrain_opts == Opt.empty:
terrain = ([catan.board.Terrain.desert] * catan.board.NUM_TILES)
elif terrain_opts in (Opt.random, Opt.debug):
terrain = ([catan.board.Terrain.desert] +
[catan.board.Terrain.brick] * 3 +
[catan.board.Terrain.ore] * 3 +
[catan.board.Terrain.wood] * 4 +
[catan.board.Terrain.sheep] * 4 +
[catan.board.Terrain.wheat] * 4)
random.shuffle(terrain)
elif terrain_opts == Opt.preset:
terrain = ([catan.board.Terrain.wood,
catan.board.Terrain.wheat,
catan.board.Terrain.ore,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.brick,
catan.board.Terrain.sheep,
catan.board.Terrain.wheat,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.brick,
catan.board.Terrain.desert,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.brick])
if numbers_opts == Opt.empty:
numbers = ([catan.board.HexNumber.none] * catan.board.NUM_TILES)
elif numbers_opts in (Opt.random, Opt.debug):
numbers = ([catan.board.HexNumber.two] +
[catan.board.HexNumber.three]*2 + [catan.board.HexNumber.four]*2 +
[catan.board.HexNumber.five]*2 + [catan.board.HexNumber.six]*2 +
[catan.board.HexNumber.eight]*2 + [catan.board.HexNumber.nine]*2 +
[catan.board.HexNumber.ten]*2 + [catan.board.HexNumber.eleven]*2 +
[catan.board.HexNumber.twelve])
random.shuffle(numbers)
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
elif numbers_opts == Opt.preset:
numbers = ([catan.board.HexNumber.five,
catan.board.HexNumber.two,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.twelve,
catan.board.HexNumber.eleven,
catan.board.HexNumber.four,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.four,
catan.board.HexNumber.five,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eleven])
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
assert len(numbers) == catan.board.NUM_TILES
assert len(terrain) == catan.board.NUM_TILES
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _get_pieces(tiles, ports, players_opts, pieces_opts):
"""
Generate a dictionary of pieces using the given options.
pieces options supported:
- Opt.empty -> no locations have pieces
- Opt.random ->
- Opt.preset -> robber is placed on the first desert found
- Opt.debug -> a variety of pieces are placed around the board
:param tiles: list of tiles from _generate_tiles
:param ports: list of ports from _generate_ports
:param players_opts: Opt
:param pieces_opts: Opt
:return: dictionary mapping (hexgrid.TYPE, coord:int) -> Piece
"""
if pieces_opts == Opt.empty:
return dict()
elif pieces_opts == Opt.debug:
players = catan.game.Game.get_debug_players()
return {
(hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]),
(hexgrid.EDGE, 0x22): catan.pieces.Piece(catan.pieces.PieceType.road, players[0]),
(hexgrid.NODE, 0x67): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[1]),
(hexgrid.EDGE, 0x98): catan.pieces.Piece(catan.pieces.PieceType.road, players[1]),
(hexgrid.NODE, 0x87): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[2]),
(hexgrid.EDGE, 0x89): catan.pieces.Piece(catan.pieces.PieceType.road, players[2]),
(hexgrid.EDGE, 0xA9): catan.pieces.Piece(catan.pieces.PieceType.road, players[3]),
(hexgrid.TILE, 0x77): catan.pieces.Piece(catan.pieces.PieceType.robber, None),
}
elif pieces_opts in (Opt.preset, ):
deserts = filter(lambda tile: tile.terrain == catan.board.Terrain.desert, tiles)
coord = hexgrid.tile_id_to_coord(list(deserts)[0].tile_id)
return {
(hexgrid.TILE, coord): catan.pieces.Piece(catan.pieces.PieceType.robber, None)
}
elif pieces_opts in (Opt.random, ):
logging.warning('{} option not yet implemented'.format(pieces_opts))
def _check_red_placement(tiles):
"""
Returns True if no red numbers are on adjacent tiles.
Returns False if any red numbers are on adjacent tiles.
Not yet implemented.
"""
logging.warning('"Check red placement" not yet implemented')
|
rosshamish/catan-py
|
catan/boardbuilder.py
|
_get_pieces
|
python
|
def _get_pieces(tiles, ports, players_opts, pieces_opts):
if pieces_opts == Opt.empty:
return dict()
elif pieces_opts == Opt.debug:
players = catan.game.Game.get_debug_players()
return {
(hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]),
(hexgrid.EDGE, 0x22): catan.pieces.Piece(catan.pieces.PieceType.road, players[0]),
(hexgrid.NODE, 0x67): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[1]),
(hexgrid.EDGE, 0x98): catan.pieces.Piece(catan.pieces.PieceType.road, players[1]),
(hexgrid.NODE, 0x87): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[2]),
(hexgrid.EDGE, 0x89): catan.pieces.Piece(catan.pieces.PieceType.road, players[2]),
(hexgrid.EDGE, 0xA9): catan.pieces.Piece(catan.pieces.PieceType.road, players[3]),
(hexgrid.TILE, 0x77): catan.pieces.Piece(catan.pieces.PieceType.robber, None),
}
elif pieces_opts in (Opt.preset, ):
deserts = filter(lambda tile: tile.terrain == catan.board.Terrain.desert, tiles)
coord = hexgrid.tile_id_to_coord(list(deserts)[0].tile_id)
return {
(hexgrid.TILE, coord): catan.pieces.Piece(catan.pieces.PieceType.robber, None)
}
elif pieces_opts in (Opt.random, ):
logging.warning('{} option not yet implemented'.format(pieces_opts))
|
Generate a dictionary of pieces using the given options.
pieces options supported:
- Opt.empty -> no locations have pieces
- Opt.random ->
- Opt.preset -> robber is placed on the first desert found
- Opt.debug -> a variety of pieces are placed around the board
:param tiles: list of tiles from _generate_tiles
:param ports: list of ports from _generate_ports
:param players_opts: Opt
:param pieces_opts: Opt
:return: dictionary mapping (hexgrid.TYPE, coord:int) -> Piece
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L261-L298
|
[
"def get_debug_players(cls):\n return [Player(1, 'yurick', 'green'),\n Player(2, 'josh', 'blue'),\n Player(3, 'zach', 'orange'),\n Player(4, 'ross', 'red')]\n"
] |
"""
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts to convert a dictionary mapping str->str to a dictionary
mapping str->Opts. #get_opts will also apply the default option values
for each option not supplied.
Use #build to build a new board with the passed options.
Use #modify to modify an existing board instead of building a new one.
This will reset the board. #reset is an alias.
"""
from enum import Enum
import logging
import pprint
import random
import hexgrid
import catan.game
import catan.states
import catan.board
import catan.pieces
class Opt(Enum):
empty = 'empty'
random = 'random'
preset = 'preset'
debug = 'debug'
def __repr__(self):
return 'opt:{}'.format(self.value)
def get_opts(opts):
"""
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
"""
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.preset,
'ports': Opt.preset,
'pieces': Opt.preset,
'players': Opt.preset,
}
_opts = defaults.copy()
if opts is None:
opts = dict()
try:
for key, val in opts.copy().items():
if key == 'board':
# board is a string, not a regular opt, and gets special handling
# in _read_tiles_from_string
continue
opts[key] = Opt(val)
_opts.update(opts)
except Exception:
raise ValueError('Invalid options={}'.format(opts))
logging.debug('used defaults=\n{}\n on opts=\n{}\nreturned total opts=\n{}'.format(
pprint.pformat(defaults),
pprint.pformat(opts),
pprint.pformat(_opts)))
return _opts
def build(opts=None):
"""
Build a new board using the given options.
:param opts: dictionary mapping str->Opt
:return: the new board, Board
"""
board = catan.board.Board()
modify(board, opts)
return board
def reset(board, opts=None):
"""
Alias for #modify. Resets an existing board.
"""
modify(board, opts)
return None
def modify(board, opts=None):
"""
Reset an existing board using the given options.
:param board: the board to reset
:param opts: dictionary mapping str->Opt
:return: None
"""
opts = get_opts(opts)
if opts['board'] is not None:
board.tiles = _read_tiles_from_string(opts['board'])
else:
board.tiles = _generate_tiles(opts['terrain'], opts['numbers'])
board.ports = _get_ports(opts['ports'])
board.state = catan.states.BoardStateModifiable(board)
board.pieces = _get_pieces(board.tiles, board.ports, opts['players'], opts['pieces'])
return None
def _get_tiles(board=None, terrain=None, numbers=None):
"""
Generate a list of tiles using the given terrain and numbers options.
terrain options supported:
- Opt.empty -> all tiles are desert
- Opt.random -> tiles are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
numbers options supported:
- Opt.empty -> no tiles have numbers
- Opt.random -> numbers are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
:param terrain_opts: Opt
:param numbers_opts: Opt
:return: list(Tile)
"""
if board is not None:
# we have a board given, ignore the terrain and numbers opts and log warnings
# if they were supplied
tiles = _read_tiles_from_string(board)
else:
# we are being asked to generate a board
tiles = _generate_tiles(terrain, numbers)
return tiles
def _read_tiles_from_string(board_str):
terrain = [catan.board.Terrain.from_short_form(char) for char in board_str.split(' ')
if char in ('w', 'b', 'h', 's', 'o', 'd')]
numbers = [catan.board.HexNumber.from_digit_or_none(num) for num in board_str.split(' ')
if num in ('2','3','4','5','6','8','9','10','11','12','None')]
logging.info('terrain:{}, numbers:{}'.format(terrain, numbers))
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _generate_tiles(terrain_opts, numbers_opts):
terrain = None
numbers = None
if terrain_opts == Opt.empty:
terrain = ([catan.board.Terrain.desert] * catan.board.NUM_TILES)
elif terrain_opts in (Opt.random, Opt.debug):
terrain = ([catan.board.Terrain.desert] +
[catan.board.Terrain.brick] * 3 +
[catan.board.Terrain.ore] * 3 +
[catan.board.Terrain.wood] * 4 +
[catan.board.Terrain.sheep] * 4 +
[catan.board.Terrain.wheat] * 4)
random.shuffle(terrain)
elif terrain_opts == Opt.preset:
terrain = ([catan.board.Terrain.wood,
catan.board.Terrain.wheat,
catan.board.Terrain.ore,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.brick,
catan.board.Terrain.sheep,
catan.board.Terrain.wheat,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.brick,
catan.board.Terrain.desert,
catan.board.Terrain.wheat,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.ore,
catan.board.Terrain.sheep,
catan.board.Terrain.wood,
catan.board.Terrain.brick])
if numbers_opts == Opt.empty:
numbers = ([catan.board.HexNumber.none] * catan.board.NUM_TILES)
elif numbers_opts in (Opt.random, Opt.debug):
numbers = ([catan.board.HexNumber.two] +
[catan.board.HexNumber.three]*2 + [catan.board.HexNumber.four]*2 +
[catan.board.HexNumber.five]*2 + [catan.board.HexNumber.six]*2 +
[catan.board.HexNumber.eight]*2 + [catan.board.HexNumber.nine]*2 +
[catan.board.HexNumber.ten]*2 + [catan.board.HexNumber.eleven]*2 +
[catan.board.HexNumber.twelve])
random.shuffle(numbers)
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
elif numbers_opts == Opt.preset:
numbers = ([catan.board.HexNumber.five,
catan.board.HexNumber.two,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.twelve,
catan.board.HexNumber.eleven,
catan.board.HexNumber.four,
catan.board.HexNumber.eight,
catan.board.HexNumber.ten,
catan.board.HexNumber.nine,
catan.board.HexNumber.four,
catan.board.HexNumber.five,
catan.board.HexNumber.six,
catan.board.HexNumber.three,
catan.board.HexNumber.eleven])
numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none)
assert len(numbers) == catan.board.NUM_TILES
assert len(terrain) == catan.board.NUM_TILES
tile_data = list(zip(terrain, numbers))
tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)]
return tiles
def _get_ports(port_opts):
"""
Generate a list of ports using the given options.
port options supported:
- Opt.empty ->
- Opt.random ->
- Opt.preset -> ports are in default locations
- Opt.debug -> alias for Opt.preset
:param port_opts: Opt
:return: list(Port)
"""
if port_opts in [Opt.preset, Opt.debug]:
_preset_ports = [(1, 'NW', catan.board.PortType.any3),
(2, 'W', catan.board.PortType.wood),
(4, 'W', catan.board.PortType.brick),
(5, 'SW', catan.board.PortType.any3),
(6, 'SE', catan.board.PortType.any3),
(8, 'SE', catan.board.PortType.sheep),
(9, 'E', catan.board.PortType.any3),
(10, 'NE', catan.board.PortType.ore),
(12, 'NE', catan.board.PortType.wheat)]
return [catan.board.Port(tile, dir, port_type)
for tile, dir, port_type in _preset_ports]
elif port_opts in [Opt.empty, Opt.random]:
logging.warning('{} option not yet implemented'.format(port_opts))
return []
def _check_red_placement(tiles):
"""
Returns True if no red numbers are on adjacent tiles.
Returns False if any red numbers are on adjacent tiles.
Not yet implemented.
"""
logging.warning('"Check red placement" not yet implemented')
|
rosshamish/catan-py
|
catan/states.py
|
GameStateInGame.next_player
|
python
|
def next_player(self):
logging.warning('turn={}, players={}'.format(
self.game._cur_turn,
self.game.players
))
return self.game.players[(self.game._cur_turn + 1) % len(self.game.players)]
|
Returns the player whose turn it will be next.
Uses regular seat-wise clockwise rotation.
Compare to GameStatePreGame's implementation, which uses snake draft.
:return Player
|
train
|
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/states.py#L184-L198
| null |
class GameStateInGame(GameState):
"""
All IN-GAME states inherit from this state.
In game is defined as taking turns, rolling dice, placing pieces, etc.
In game starts on 'Start Game', and ends on 'End Game'
this state implements:
is_in_game()
this state provides:
is_in_pregame()
next_player()
begin_turn()
has_rolled()
can_roll()
can_move_robber()
can_steal()
can_buy_road()
can_buy_settlement()
can_buy_city()
can_buy_dev_card()
can_trade()
can_play_knight()
can_play_monopoly()
can_play_road_builder()
can_play_victory_point()
sub-states must implement:
can_end_turn()
"""
def is_in_game(self):
return True
def is_in_pregame(self):
"""
See GameStatePreGame for details.
:return: Boolean
"""
return False
def begin_turn(self):
"""
Begins the turn for the current player.
All that is required is to set the game's state.
Compare to GameStatePreGame's implementation, which uses GameStatePreGamePlaceSettlement
:return None
"""
self.game.set_state(GameStateBeginTurn(self.game))
def has_rolled(self):
"""
Whether the current player has rolled or not.
:return Boolean
"""
return self.game.last_player_to_roll == self.game.get_cur_player()
def can_roll(self):
"""
Whether the current player can roll or not.
A player can roll only if they have not yet rolled.
:return Boolean
"""
return not self.has_rolled()
def can_move_robber(self):
"""
Whether the current player can move the robber or not.
:return Boolean
"""
return False
def can_steal(self):
"""
Whether the current player can steal or not.
:return Boolean
"""
return False
def can_buy_road(self):
"""
Whether the current player can buy a road or not.
:return Boolean
"""
return self.has_rolled()
def can_buy_settlement(self):
"""
Whether the current player can buy a settlement or not.
:return Boolean
"""
return self.has_rolled()
def can_buy_city(self):
"""
Whether the current player can buy a city or not.
:return Boolean
"""
return self.has_rolled()
def can_place_road(self):
"""
Whether the current player can place a road or not.
:return Boolean
"""
return False
def can_place_settlement(self):
"""
Whether the current player can place a settlement or not.
:return Boolean
"""
return False
def can_place_city(self):
"""
Whether the current player can place a city or not.
:return Boolean
"""
return False
def can_buy_dev_card(self):
"""
Whether the current player can buy a dev card or not.
:return Boolean
"""
return self.has_rolled()
def can_trade(self):
"""
Whether the current player can trade or not.
:return Boolean
"""
return self.has_rolled()
def can_play_knight(self):
"""
Whether the current player can play a knight dev card or not.
:return Boolean
"""
return self.game.dev_card_state.can_play_dev_card()
def can_play_monopoly(self):
"""
Whether the current player can play a monopoly dev card or not.
:return Boolean
"""
return self.has_rolled() and self.game.dev_card_state.can_play_dev_card()
def can_play_year_of_plenty(self):
"""
Whether the current player can play a year of plenty dev card or not.
:return Boolean
"""
return self.has_rolled() and self.game.dev_card_state.can_play_dev_card()
def can_play_road_builder(self):
"""
Whether the current player can play a road builder dev card or not.
:return Boolean
"""
return self.has_rolled() and self.game.dev_card_state.can_play_dev_card()
def can_play_victory_point(self):
"""
Whether the current player can play a victory point dev card or not.
:return Boolean
"""
return True
def can_end_turn(self):
"""
Whether the current player can end their turn or not.
:return Boolean
"""
raise NotImplemented()
|
cnschema/cdata
|
cdata/wikify.py
|
wikidata_get
|
python
|
def wikidata_get(identifier):
url = 'https://www.wikidata.org/wiki/Special:EntityData/{}.json'.format(identifier)
#logging.info(url)
return json.loads(requests.get(url).content)
|
https://www.wikidata.org/wiki/Special:EntityData/P248.json
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/wikify.py#L51-L57
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# wikification apis
import os
import sys
import json
import logging
import datetime
import logging
import time
import urllib
import re
import requests
from misc import main_subtask
from core import *
def task_compare(args):
queries = [
"autodealer",
"birthplace",
u"居里夫人",
u"爱因斯坦",
]
for query in queries:
args ={"query": query}
logging.info(u"-----{}------".format(query))
task_wikipedia_test(args)
task_wikidata_test(args)
def task_wikipedia_test(args):
ret = wikipedia_search(args["query"])
logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
# ret = wikipedia_search_slow(query)
# logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
def task_wikidata_test(args):
ret = wikidata_search(args["query"])
logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
if ret["itemList"]:
nodeid = ret["itemList"][0]["identifier"]
ret = wikidata_get(nodeid)
logging.info(json.dumps(ret["entities"][nodeid]["labels"]["zh"]["value"], ensure_ascii=False, sort_keys=True, indent=4))
def wikidata_search(query, lang="zh", output_lang="en", searchtype="item", max_result=1):
"""
wikification: search wikipedia pages for the given query
https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentities
result format
{
searchinfo: - {
search: "birthday"
},
search: - [
- {
repository: "",
id: "P3150",
concepturi: "http://www.wikidata.org/entity/P3150",
url: "//www.wikidata.org/wiki/Property:P3150",
title: "Property:P3150",
pageid: 28754653,
datatype: "wikibase-item",
label: "birthday",
description: "item for day and month on which the subject was born. Used when full "date of birth" (P569) isn't known.",
match: - {
type: "label",
language: "en",
text: "birthday"
}
}
"""
query = any2unicode(query)
params = {
"action":"wbsearchentities",
"search": query,
"format":"json",
"language":lang,
"uselang":output_lang,
"type":searchtype
}
urlBase = "https://www.wikidata.org/w/api.php?"
url = urlBase + urllib.urlencode(any2utf8(params))
#logging.info(url)
r = requests.get(url)
results = json.loads(r.content).get("search",[])
#logging.info(items)
property_list = [
{"name":"name", "alternateName":["label"]},
{"name":"url", "alternateName":["concepturi"]},
{"name":"identifier", "alternateName":["id"]},
{"name":"description"},
]
items = []
ret = {"query": query, "itemList":items}
for result in results[0:max_result]:
#logging.info(result)
item = json_dict_copy(result, property_list)
items.append(item)
return ret
def wikipedia_search_slow(query, lang="en", max_result=1):
import wikipedia
#wikification
query = any2unicode(query)
items = []
ret = {"query":query, "itemList":items}
wikipedia.set_lang(lang)
wikiterm = wikipedia.search(query)
#logging.info(wikiterm)
for idx, term in enumerate(wikiterm[0:max_result]):
wikipage = wikipedia.page(term)
item = {
"name": wikipage.title,
"description": wikipedia.summary(term, sentences=1),
"url": wikipage.url,
}
items.append(item)
return ret
def wikipedia_search(query, lang="en", max_result=1):
"""
https://www.mediawiki.org/wiki/API:Opensearch
"""
query = any2unicode(query)
params = {
"action":"opensearch",
"search": query,
"format":"json",
#"formatversion":2,
#"namespace":0,
"suggest":"true",
"limit": 10
}
urlBase = "https://{}.wikipedia.org/w/api.php?".format(lang)
url = urlBase + urllib.urlencode(any2utf8(params))
#logging.info(url)
r = requests.get(url)
jsonData = json.loads(r.content)
#logging.info(jsonData)
items = []
ret = {"query":query, "itemList":items}
for idx, label in enumerate(jsonData[1][0:max_result]):
description = jsonData[2][idx]
url = jsonData[3][idx]
item = {
"name": label,
"description":description,
"url": url,
}
items.append(item)
return ret
if __name__ == "__main__":
logging.basicConfig(format='[%(levelname)s][%(asctime)s][%(module)s][%(funcName)s][%(lineno)s] %(message)s', level=logging.INFO)
logging.getLogger("requests").setLevel(logging.WARNING)
optional_params = {
'--query': 'query'
}
main_subtask(__name__, optional_params=optional_params)
"""
python cdata/wikify.py task_wikipedia_test --query="birth place"
python cdata/wikify.py task_wikidata_test --query="birth place"
python cdata/wikify.py task_wikidata_test --query="birthplace"
python cdata/wikify.py task_wikidata_test --query=居里夫人
python cdata/wikify.py task_compare
"""
|
cnschema/cdata
|
cdata/wikify.py
|
wikidata_search
|
python
|
def wikidata_search(query, lang="zh", output_lang="en", searchtype="item", max_result=1):
query = any2unicode(query)
params = {
"action":"wbsearchentities",
"search": query,
"format":"json",
"language":lang,
"uselang":output_lang,
"type":searchtype
}
urlBase = "https://www.wikidata.org/w/api.php?"
url = urlBase + urllib.urlencode(any2utf8(params))
#logging.info(url)
r = requests.get(url)
results = json.loads(r.content).get("search",[])
#logging.info(items)
property_list = [
{"name":"name", "alternateName":["label"]},
{"name":"url", "alternateName":["concepturi"]},
{"name":"identifier", "alternateName":["id"]},
{"name":"description"},
]
items = []
ret = {"query": query, "itemList":items}
for result in results[0:max_result]:
#logging.info(result)
item = json_dict_copy(result, property_list)
items.append(item)
return ret
|
wikification: search wikipedia pages for the given query
https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentities
result format
{
searchinfo: - {
search: "birthday"
},
search: - [
- {
repository: "",
id: "P3150",
concepturi: "http://www.wikidata.org/entity/P3150",
url: "//www.wikidata.org/wiki/Property:P3150",
title: "Property:P3150",
pageid: 28754653,
datatype: "wikibase-item",
label: "birthday",
description: "item for day and month on which the subject was born. Used when full "date of birth" (P569) isn't known.",
match: - {
type: "label",
language: "en",
text: "birthday"
}
}
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/wikify.py#L59-L115
|
[
"def json_dict_copy(json_object, property_list, defaultValue=None):\n \"\"\"\n property_list = [\n { \"name\":\"name\", \"alternateName\": [\"name\",\"title\"]},\n { \"name\":\"birthDate\", \"alternateName\": [\"dob\",\"dateOfBirth\"] },\n { \"name\":\"description\" }\n ]\n \"\"\"\n ret = {}\n for prop in property_list:\n p_name = prop[\"name\"]\n for alias in prop.get(\"alternateName\", []):\n if json_object.get(alias) is not None:\n ret[p_name] = json_object.get(alias)\n break\n if not p_name in ret:\n if p_name in json_object:\n ret[p_name] = json_object[p_name]\n elif defaultValue is not None:\n ret[p_name] = defaultValue\n\n return ret\n",
"def any2utf8(data):\n \"\"\"\n rewrite json object values (unicode) into utf-8 encoded string\n \"\"\"\n if isinstance(data, dict):\n ret = {}\n for k, v in data.items():\n k = any2utf8(k)\n ret[k] = any2utf8(v)\n return ret\n elif isinstance(data, list):\n return [any2utf8(x) for x in data]\n elif isinstance(data, unicode):\n return data.encode(\"utf-8\")\n elif type(data) in [str, basestring]:\n return data\n elif type(data) in [int, float]:\n return data\n else:\n logging.error(\"unexpected {} {}\".format(type(data), data))\n return data\n",
"def any2unicode(data):\n \"\"\"\n rewrite json object values (assum utf-8) into unicode\n \"\"\"\n if isinstance(data, dict):\n ret = {}\n for k, v in data.items():\n k = any2unicode(k)\n ret[k] = any2unicode(v)\n return ret\n elif isinstance(data, list):\n return [any2unicode(x) for x in data]\n elif isinstance(data, unicode):\n return data\n elif type(data) in [str, basestring]:\n return data.decode(\"utf-8\")\n elif type(data) in [int, float]:\n return data\n else:\n logging.error(\"unexpected {} {}\".format(type(data), data))\n return data\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# wikification apis
import os
import sys
import json
import logging
import datetime
import logging
import time
import urllib
import re
import requests
from misc import main_subtask
from core import *
def task_compare(args):
queries = [
"autodealer",
"birthplace",
u"居里夫人",
u"爱因斯坦",
]
for query in queries:
args ={"query": query}
logging.info(u"-----{}------".format(query))
task_wikipedia_test(args)
task_wikidata_test(args)
def task_wikipedia_test(args):
ret = wikipedia_search(args["query"])
logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
# ret = wikipedia_search_slow(query)
# logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
def task_wikidata_test(args):
ret = wikidata_search(args["query"])
logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
if ret["itemList"]:
nodeid = ret["itemList"][0]["identifier"]
ret = wikidata_get(nodeid)
logging.info(json.dumps(ret["entities"][nodeid]["labels"]["zh"]["value"], ensure_ascii=False, sort_keys=True, indent=4))
def wikidata_get(identifier):
"""
https://www.wikidata.org/wiki/Special:EntityData/P248.json
"""
url = 'https://www.wikidata.org/wiki/Special:EntityData/{}.json'.format(identifier)
#logging.info(url)
return json.loads(requests.get(url).content)
def wikipedia_search_slow(query, lang="en", max_result=1):
import wikipedia
#wikification
query = any2unicode(query)
items = []
ret = {"query":query, "itemList":items}
wikipedia.set_lang(lang)
wikiterm = wikipedia.search(query)
#logging.info(wikiterm)
for idx, term in enumerate(wikiterm[0:max_result]):
wikipage = wikipedia.page(term)
item = {
"name": wikipage.title,
"description": wikipedia.summary(term, sentences=1),
"url": wikipage.url,
}
items.append(item)
return ret
def wikipedia_search(query, lang="en", max_result=1):
"""
https://www.mediawiki.org/wiki/API:Opensearch
"""
query = any2unicode(query)
params = {
"action":"opensearch",
"search": query,
"format":"json",
#"formatversion":2,
#"namespace":0,
"suggest":"true",
"limit": 10
}
urlBase = "https://{}.wikipedia.org/w/api.php?".format(lang)
url = urlBase + urllib.urlencode(any2utf8(params))
#logging.info(url)
r = requests.get(url)
jsonData = json.loads(r.content)
#logging.info(jsonData)
items = []
ret = {"query":query, "itemList":items}
for idx, label in enumerate(jsonData[1][0:max_result]):
description = jsonData[2][idx]
url = jsonData[3][idx]
item = {
"name": label,
"description":description,
"url": url,
}
items.append(item)
return ret
if __name__ == "__main__":
logging.basicConfig(format='[%(levelname)s][%(asctime)s][%(module)s][%(funcName)s][%(lineno)s] %(message)s', level=logging.INFO)
logging.getLogger("requests").setLevel(logging.WARNING)
optional_params = {
'--query': 'query'
}
main_subtask(__name__, optional_params=optional_params)
"""
python cdata/wikify.py task_wikipedia_test --query="birth place"
python cdata/wikify.py task_wikidata_test --query="birth place"
python cdata/wikify.py task_wikidata_test --query="birthplace"
python cdata/wikify.py task_wikidata_test --query=居里夫人
python cdata/wikify.py task_compare
"""
|
cnschema/cdata
|
cdata/wikify.py
|
wikipedia_search
|
python
|
def wikipedia_search(query, lang="en", max_result=1):
query = any2unicode(query)
params = {
"action":"opensearch",
"search": query,
"format":"json",
#"formatversion":2,
#"namespace":0,
"suggest":"true",
"limit": 10
}
urlBase = "https://{}.wikipedia.org/w/api.php?".format(lang)
url = urlBase + urllib.urlencode(any2utf8(params))
#logging.info(url)
r = requests.get(url)
jsonData = json.loads(r.content)
#logging.info(jsonData)
items = []
ret = {"query":query, "itemList":items}
for idx, label in enumerate(jsonData[1][0:max_result]):
description = jsonData[2][idx]
url = jsonData[3][idx]
item = {
"name": label,
"description":description,
"url": url,
}
items.append(item)
return ret
|
https://www.mediawiki.org/wiki/API:Opensearch
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/wikify.py#L137-L171
|
[
"def any2utf8(data):\n \"\"\"\n rewrite json object values (unicode) into utf-8 encoded string\n \"\"\"\n if isinstance(data, dict):\n ret = {}\n for k, v in data.items():\n k = any2utf8(k)\n ret[k] = any2utf8(v)\n return ret\n elif isinstance(data, list):\n return [any2utf8(x) for x in data]\n elif isinstance(data, unicode):\n return data.encode(\"utf-8\")\n elif type(data) in [str, basestring]:\n return data\n elif type(data) in [int, float]:\n return data\n else:\n logging.error(\"unexpected {} {}\".format(type(data), data))\n return data\n",
"def any2unicode(data):\n \"\"\"\n rewrite json object values (assum utf-8) into unicode\n \"\"\"\n if isinstance(data, dict):\n ret = {}\n for k, v in data.items():\n k = any2unicode(k)\n ret[k] = any2unicode(v)\n return ret\n elif isinstance(data, list):\n return [any2unicode(x) for x in data]\n elif isinstance(data, unicode):\n return data\n elif type(data) in [str, basestring]:\n return data.decode(\"utf-8\")\n elif type(data) in [int, float]:\n return data\n else:\n logging.error(\"unexpected {} {}\".format(type(data), data))\n return data\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# wikification apis
import os
import sys
import json
import logging
import datetime
import logging
import time
import urllib
import re
import requests
from misc import main_subtask
from core import *
def task_compare(args):
queries = [
"autodealer",
"birthplace",
u"居里夫人",
u"爱因斯坦",
]
for query in queries:
args ={"query": query}
logging.info(u"-----{}------".format(query))
task_wikipedia_test(args)
task_wikidata_test(args)
def task_wikipedia_test(args):
ret = wikipedia_search(args["query"])
logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
# ret = wikipedia_search_slow(query)
# logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
def task_wikidata_test(args):
ret = wikidata_search(args["query"])
logging.info(json.dumps(ret, ensure_ascii=False, sort_keys=True, indent=4))
if ret["itemList"]:
nodeid = ret["itemList"][0]["identifier"]
ret = wikidata_get(nodeid)
logging.info(json.dumps(ret["entities"][nodeid]["labels"]["zh"]["value"], ensure_ascii=False, sort_keys=True, indent=4))
def wikidata_get(identifier):
"""
https://www.wikidata.org/wiki/Special:EntityData/P248.json
"""
url = 'https://www.wikidata.org/wiki/Special:EntityData/{}.json'.format(identifier)
#logging.info(url)
return json.loads(requests.get(url).content)
def wikidata_search(query, lang="zh", output_lang="en", searchtype="item", max_result=1):
"""
wikification: search wikipedia pages for the given query
https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentities
result format
{
searchinfo: - {
search: "birthday"
},
search: - [
- {
repository: "",
id: "P3150",
concepturi: "http://www.wikidata.org/entity/P3150",
url: "//www.wikidata.org/wiki/Property:P3150",
title: "Property:P3150",
pageid: 28754653,
datatype: "wikibase-item",
label: "birthday",
description: "item for day and month on which the subject was born. Used when full "date of birth" (P569) isn't known.",
match: - {
type: "label",
language: "en",
text: "birthday"
}
}
"""
query = any2unicode(query)
params = {
"action":"wbsearchentities",
"search": query,
"format":"json",
"language":lang,
"uselang":output_lang,
"type":searchtype
}
urlBase = "https://www.wikidata.org/w/api.php?"
url = urlBase + urllib.urlencode(any2utf8(params))
#logging.info(url)
r = requests.get(url)
results = json.loads(r.content).get("search",[])
#logging.info(items)
property_list = [
{"name":"name", "alternateName":["label"]},
{"name":"url", "alternateName":["concepturi"]},
{"name":"identifier", "alternateName":["id"]},
{"name":"description"},
]
items = []
ret = {"query": query, "itemList":items}
for result in results[0:max_result]:
#logging.info(result)
item = json_dict_copy(result, property_list)
items.append(item)
return ret
def wikipedia_search_slow(query, lang="en", max_result=1):
import wikipedia
#wikification
query = any2unicode(query)
items = []
ret = {"query":query, "itemList":items}
wikipedia.set_lang(lang)
wikiterm = wikipedia.search(query)
#logging.info(wikiterm)
for idx, term in enumerate(wikiterm[0:max_result]):
wikipage = wikipedia.page(term)
item = {
"name": wikipage.title,
"description": wikipedia.summary(term, sentences=1),
"url": wikipage.url,
}
items.append(item)
return ret
if __name__ == "__main__":
logging.basicConfig(format='[%(levelname)s][%(asctime)s][%(module)s][%(funcName)s][%(lineno)s] %(message)s', level=logging.INFO)
logging.getLogger("requests").setLevel(logging.WARNING)
optional_params = {
'--query': 'query'
}
main_subtask(__name__, optional_params=optional_params)
"""
python cdata/wikify.py task_wikipedia_test --query="birth place"
python cdata/wikify.py task_wikidata_test --query="birth place"
python cdata/wikify.py task_wikidata_test --query="birthplace"
python cdata/wikify.py task_wikidata_test --query=居里夫人
python cdata/wikify.py task_compare
"""
|
cnschema/cdata
|
cdata/misc.py
|
main_subtask
|
python
|
def main_subtask(module_name, method_prefixs=["task_"], optional_params={}):
parser = argparse.ArgumentParser(description="")
parser.add_argument('method_name', help='')
for optional_param_key, optional_param_help in optional_params.items():
parser.add_argument(optional_param_key,
required=False,
help=optional_param_help)
# parser.add_argument('--reset_cache', required=False, help='')
args = parser.parse_args()
for prefix in method_prefixs:
if args.method_name.startswith(prefix):
if prefix == "test_":
# Remove all handlers associated with the root logger object.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
# Reconfigure logging again, this time with a file.
logging.basicConfig(format='[%(levelname)s][%(asctime)s][%(module)s][%(funcName)s][%(lineno)s] %(message)s', level=logging.DEBUG) # noqa
# http://stackoverflow.com/questions/17734618/dynamic-method-call-in-python-2-7-using-strings-of-method-names
the_method = getattr(sys.modules[module_name], args.method_name)
if the_method:
the_method(args=vars(args))
logging.info("done")
return
else:
break
logging.info("unsupported")
|
http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse
As of 2.7, optparse is deprecated, and will hopefully go away in the future
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/misc.py#L24-L58
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# utility stuff
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import argparse
import urlparse
import re
import collections
####################################################
def task_subtask(args):
print "called task_subtask"
if __name__ == "__main__":
logging.basicConfig(format='[%(levelname)s][%(asctime)s][%(module)s][%(funcName)s][%(lineno)s] %(message)s', level=logging.DEBUG) # noqa
logging.getLogger("requests").setLevel(logging.WARNING)
main_subtask(__name__)
"""
python misc.py task_subtask
"""
|
cnschema/cdata
|
cdata/web.py
|
url2domain
|
python
|
def url2domain(url):
parsed_uri = urlparse.urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
domain = re.sub("^.+@", "", domain)
domain = re.sub(":.+$", "", domain)
return domain
|
extract domain from url
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/web.py#L20-L27
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# utility stuff
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import urlparse
import re
|
cnschema/cdata
|
cdata/core.py
|
file2abspath
|
python
|
def file2abspath(filename, this_file=__file__):
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
|
generate absolute path for the given file and base dir
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L28-L33
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
file2json
|
python
|
def file2json(filename, encoding='utf-8'):
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
|
save a line
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L39-L44
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
file2iter
|
python
|
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
|
json stream parsing or line parsing
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L47-L65
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
json2file
|
python
|
def json2file(data, filename, encoding='utf-8'):
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
|
write json in canonical json format
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L71-L76
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
lines2file
|
python
|
def lines2file(lines, filename, encoding='utf-8'):
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
|
write json stream, write lines too
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L79-L86
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
items2file
|
python
|
def items2file(items, filename, encoding='utf-8', modifier='w'):
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
|
json array to file, canonical json format
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L89-L96
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
json_get
|
python
|
def json_get(json_object, property_path, default=None):
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
|
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L102-L115
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
json_dict_copy
|
python
|
def json_dict_copy(json_object, property_list, defaultValue=None):
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
|
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L138-L159
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
any2utf8
|
python
|
def any2utf8(data):
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
|
rewrite json object values (unicode) into utf-8 encoded string
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L175-L195
|
[
"def any2utf8(data):\n \"\"\"\n rewrite json object values (unicode) into utf-8 encoded string\n \"\"\"\n if isinstance(data, dict):\n ret = {}\n for k, v in data.items():\n k = any2utf8(k)\n ret[k] = any2utf8(v)\n return ret\n elif isinstance(data, list):\n return [any2utf8(x) for x in data]\n elif isinstance(data, unicode):\n return data.encode(\"utf-8\")\n elif type(data) in [str, basestring]:\n return data\n elif type(data) in [int, float]:\n return data\n else:\n logging.error(\"unexpected {} {}\".format(type(data), data))\n return data\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
any2sha1
|
python
|
def any2sha1(text):
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
|
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L221-L234
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
def stat_jsonld(data, key=None, counter=None):
"""
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
"""
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
cnschema/cdata
|
cdata/core.py
|
stat_jsonld
|
python
|
def stat_jsonld(data, key=None, counter=None):
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
elif isinstance(data, list):
[stat_jsonld(x, key, counter) for x in data]
if key in ["tag"]:
for x in data:
if isinstance(x, dict) and x.get("name"):
counter[u"{}_{}".format(key, x["name"])] +=1
elif type(x) in [basestring, unicode]:
counter[u"{}_{}".format(key, x)] +=1
else:
if key and key not in ["@id","@context"]:
counter["triple"] += 1
counter[u"p_{}".format(key)] +=1
return counter
|
provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L269-L300
|
[
"def stat_jsonld(data, key=None, counter=None):\n \"\"\"\n provide statistics for jsonld, right now only count triples\n see also https://json-ld.org/playground/\n note: attributes @id @context do not contribute any triple\n \"\"\"\n if counter is None:\n counter = collections.Counter()\n\n if isinstance(data, dict):\n ret = {}\n for k, v in data.items():\n stat_jsonld(v, k, counter)\n counter[u\"p_{}\".format(k)] += 0\n if key:\n counter[\"triple\"] += 1\n counter[u\"p_{}\".format(key)] +=1\n elif isinstance(data, list):\n [stat_jsonld(x, key, counter) for x in data]\n if key in [\"tag\"]:\n for x in data:\n if isinstance(x, dict) and x.get(\"name\"):\n counter[u\"{}_{}\".format(key, x[\"name\"])] +=1\n elif type(x) in [basestring, unicode]:\n counter[u\"{}_{}\".format(key, x)] +=1\n\n else:\n if key and key not in [\"@id\",\"@context\"]:\n counter[\"triple\"] += 1\n counter[u\"p_{}\".format(key)] +=1\n\n return counter\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEXTS = [os.path.basename(__file__), VERSION]
####################################
# file path
def file2abspath(filename, this_file=__file__):
"""
generate absolute path for the given file and base dir
"""
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))
####################################
# read from file
def file2json(filename, encoding='utf-8'):
"""
save a line
"""
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f)
def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
"""
json stream parsing or line parsing
"""
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line) == 0:
continue
# skip comment line
if comment_prefix and line.startswith(comment_prefix):
continue
yield line
####################################
# write to file
def json2file(data, filename, encoding='utf-8'):
"""
write json in canonical json format
"""
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
def lines2file(lines, filename, encoding='utf-8'):
"""
write json stream, write lines too
"""
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n")
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True)))
####################################
# json data access
def json_get(json_object, property_path, default=None):
"""
get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default
"""
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default)
def json_get_list(json_object, p):
v = json_object.get(p, [])
if isinstance(v, list):
return v
else:
return [v]
def json_get_first_item(json_object, p, defaultValue=''):
# return empty string if the item does not exist
v = json_object.get(p, [])
if isinstance(v, list):
if len(v) > 0:
return v[0]
else:
return defaultValue
else:
return v
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
if not p_name in ret:
if p_name in json_object:
ret[p_name] = json_object[p_name]
elif defaultValue is not None:
ret[p_name] = defaultValue
return ret
def json_append(obj, p, v):
vlist = obj.get(p, [])
if not isinstance(vlist, list):
return
if vlist:
vlist.append(v)
else:
obj[p] = [v]
####################################
# data conversion
def any2utf8(data):
"""
rewrite json object values (unicode) into utf-8 encoded string
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode("utf-8")
elif type(data) in [str, basestring]:
return data
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2unicode(data):
"""
rewrite json object values (assum utf-8) into unicode
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2unicode(k)
ret[k] = any2unicode(v)
return ret
elif isinstance(data, list):
return [any2unicode(x) for x in data]
elif isinstance(data, unicode):
return data
elif type(data) in [str, basestring]:
return data.decode("utf-8")
elif type(data) in [int, float]:
return data
else:
logging.error("unexpected {} {}".format(type(data), data))
return data
def any2sha1(text):
"""
convert a string into sha1hash. For json object/array, first convert
it into canonical json string.
"""
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest()
####################################
# file statistics
def stat(items, unique_fields, value_fields=[], printCounter=True):
counter = collections.Counter()
unique_counter = collections.defaultdict(list)
for item in items:
counter["all"] += 1
for field in unique_fields:
if item.get(field):
unique_counter[field].append(item[field])
for field in value_fields:
value = item.get(field)
if value is None:
continue
elif type(value) in [ float, int ]:
vx = "%1.0d" % value
else:
vx = value
if len(vx) > 0:
counter[u"{}_{}".format(field, value)] += 1
for field in unique_fields:
counter[u"{}_unique".format(field)] = len(set(unique_counter[field]))
counter[u"{}_nonempty".format(field)] = len(unique_counter[field])
if printCounter:
logging.info(json.dumps(counter, ensure_ascii=False,
indent=4, sort_keys=True))
return counter
|
cnschema/cdata
|
cdata/summary.py
|
summarize_entity_person
|
python
|
def summarize_entity_person(person):
ret = []
value = person.get("name")
if not value:
return False
ret.append(value)
prop = "courtesyName"
value = json_get_first_item(person, prop)
if value == u"不详":
value = ""
if value:
ret.append(u'字{}'.format(value))
value = person.get("alternateName")
if value:
#ret.append(u'别名{}'.format(value))
# Bugged
pass
prop = "artName"
value = json_get_first_item(person, prop)
if value:
ret.append(u'号{}'.format(value))
value = person.get("dynasty")
if value:
ret.append(u'{}人'.format(value))
prop = "ancestralHome"
value = json_get_first_item(person, prop)
if value:
ret.append(u'祖籍{}'.format(value))
birth_date = person.get("birthDate", "")
birth_place = person.get("birthPlace", "")
# Special case for unknown birth date
if birth_date == u"不详":
birth_date = ""
if birth_place:
ret.append(u'{}出生于{}'.format(birth_date, birth_place))
elif birth_date:
ret.append(u'{}出生'.format(birth_date))
prop = "nationality"
nationality = json_get_first_item(person, prop)
prop = "occupation"
occupation = json_get_first_item(person, prop)
if occupation:
if nationality:
ret.append(u'{}{}'.format(nationality, occupation))
else:
ret.append(u'{}'.format(occupation))
elif nationality:
ret.append(u'{}人'.format(nationality))
prop = "authorOf"
value = json_get_list(person, prop)
if value:
logging.info(value)
value = u"、".join(value)
ret.append(u'主要作品:{}'.format(value) )
prop = "accomplishment"
value = json_get_list(person, prop)
if value:
value = u"、".join(value)
if len(value) < 30:
# Colon is handled by text reading software
ret.append( u"主要成就:{}".format(value) )
ret = u",".join(ret)
# Make all commas Chinese
ret = ret.replace(u',', u',')
ret = re.sub(u",+", u",", ret) # Removes repeat commas
# Handles periods at end
ret = re.sub(ur"[。,]+$", u"", ret)
# Converts brackets to Chinese
ret = ret.replace(u'(', u'(')
ret = ret.replace(u')', u')')
# Removes brackets and all contained info
ret = re.sub(ur"([^)]*)", u"", ret)
ret = u''.join([ret, u"。"])
return ret
|
assume person entity using cnschma person vocabulary, http://cnschema.org/Person
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/summary.py#L25-L117
|
[
"def json_get_list(json_object, p):\n v = json_object.get(p, [])\n if isinstance(v, list):\n return v\n else:\n return [v]\n",
"def json_get_first_item(json_object, p, defaultValue=''):\n # return empty string if the item does not exist\n v = json_object.get(p, [])\n if isinstance(v, list):\n if len(v) > 0:\n return v[0]\n else:\n return defaultValue\n else:\n return v\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:
# summarize a paragraph or an entity into short text description
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import re
import collections
from misc import main_subtask
from core import *
from table import *
def summarize_paragraph_person(text):
pass
def task_summarize_entity_person(args):
#print "called task_test_summarize_entity_person"
person = {
"name": u"张三",
"accomplishment": u"三好学生"
}
ret = summarize_entity_person(person)
logging.info(ret)
def task_summarize_all_person(args):
path2person = file2abspath('../local/person/person.json')
result_person_list = []
for line in file2iter(path2person):
person = json.loads(line)
ret = summarize_entity_person(person)
if ret:
person["shortDescription"] = ret
result_person_list.append(person)
logging.info( "write to JSON and excel")
KEYS = [u"@type",u"artName",u"ethnicGroup",u"student",u"courtesyName",u"religion",u"cnProfessionalTitle",u"occupation",u"jobTitle",u"sibling",u"weight",u"nationality",u"birthPlace",u"height",u"alumniOf",u"keywords", u"schoolsOfbuddhism",u"image",u"parent",u"children",u"accomplishment",u"academicDegree",u"dharmaName",u"deathDate",u"academicMajor",u"nobleTitle",u"posthumousName",u"familyName",u"memberOfPoliticalParty",u"award",u"description", u"shortDescription", u"placeOfBurial",u"cnEducationalAttainment",u"alternateName",u"pseudonym",u"templeName", u"birthDate",u"gender",u"worksFor",u"name",u"dynasty",u"earName",u"ancestralHome",u"birthName",u"studentOf",u"spouse",u"nobleFamily",u"authorOf",u"@id",u"colleague",u"fieldOfWork",u"mother",u"father"]
out_path = "../local/person/"
json2excel(
result_person_list, KEYS,
os.path.join(out_path, 'person_shortDescription.xls')
)
items2file(
result_person_list,
os.path.join(out_path, 'person_shortDescription.json')
)
if __name__ == "__main__":
logging.basicConfig(format='[%(levelname)s][%(asctime)s][%(module)s][%(funcName)s][%(lineno)s] %(message)s', level=logging.DEBUG) # noqa
logging.getLogger("requests").setLevel(logging.WARNING)
main_subtask(__name__)
"""
python cdata/summary.py task_summarize_entity_person
python cdata/summary.py task_summarize_all_person
"""
|
cnschema/cdata
|
cdata/table.py
|
json2excel
|
python
|
def json2excel(items, keys, filename, page_size=60000):
wb = xlwt.Workbook()
rowindex = 0
sheetindex = 0
for item in items:
if rowindex % page_size == 0:
sheetname = "%02d" % sheetindex
ws = wb.add_sheet(sheetname)
rowindex = 0
sheetindex += 1
colindex = 0
for key in keys:
ws.write(rowindex, colindex, key)
colindex += 1
rowindex += 1
colindex = 0
for key in keys:
v = item.get(key, "")
if type(v) == list:
v = ','.join(v)
if type(v) == set:
v = ','.join(v)
ws.write(rowindex, colindex, v)
colindex += 1
rowindex += 1
logging.debug(filename)
wb.save(filename)
|
max_page_size is 65000 because we output old excel .xls format
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/table.py#L22-L53
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# table/excel data manipulation
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import re
import collections
import xlwt
import xlrd
def excel2json(filename, non_empty_col=-1, file_contents=None):
"""
http://www.lexicon.net/sjmachin/xlrd.html
non_empty_col is -1 to load all rows, when set to a none-empty value,
this function will skip rows having empty cell on that col.
"""
if file_contents:
workbook = xlrd.open_workbook(file_contents=file_contents)
else:
workbook = xlrd.open_workbook(filename)
start_row = 0
ret = collections.defaultdict(list)
fields = {}
for name in workbook.sheet_names():
sh = workbook.sheet_by_name(name)
headers = []
for col in range(len(sh.row(start_row))):
headers.append(sh.cell(start_row, col).value)
logging.info(u"sheet={} rows={} cols={}".format(
name, sh.nrows, len(headers)))
logging.info(json.dumps(headers, ensure_ascii=False))
fields[name] = headers
for row in range(start_row + 1, sh.nrows):
item = {}
rowdata = sh.row(row)
if len(rowdata) < len(headers):
msg = "skip mismatched row {}".format(
json.dumps(rowdata, ensure_ascii=False))
logging.warning(msg)
continue
for col in range(len(headers)):
value = sh.cell(row, col).value
if type(value) in [unicode, basestring]:
value = value.strip()
item[headers[col]] = value
if non_empty_col >= 0 and not item[headers[non_empty_col]]:
logging.debug("skip empty cell")
continue
ret[name].append(item)
# stat
logging.info(u"loaded {} {} (non_empty_col={})".format(
filename, len(ret[name]), non_empty_col))
return {'data': ret, 'fields': fields}
|
cnschema/cdata
|
cdata/table.py
|
excel2json
|
python
|
def excel2json(filename, non_empty_col=-1, file_contents=None):
if file_contents:
workbook = xlrd.open_workbook(file_contents=file_contents)
else:
workbook = xlrd.open_workbook(filename)
start_row = 0
ret = collections.defaultdict(list)
fields = {}
for name in workbook.sheet_names():
sh = workbook.sheet_by_name(name)
headers = []
for col in range(len(sh.row(start_row))):
headers.append(sh.cell(start_row, col).value)
logging.info(u"sheet={} rows={} cols={}".format(
name, sh.nrows, len(headers)))
logging.info(json.dumps(headers, ensure_ascii=False))
fields[name] = headers
for row in range(start_row + 1, sh.nrows):
item = {}
rowdata = sh.row(row)
if len(rowdata) < len(headers):
msg = "skip mismatched row {}".format(
json.dumps(rowdata, ensure_ascii=False))
logging.warning(msg)
continue
for col in range(len(headers)):
value = sh.cell(row, col).value
if type(value) in [unicode, basestring]:
value = value.strip()
item[headers[col]] = value
if non_empty_col >= 0 and not item[headers[non_empty_col]]:
logging.debug("skip empty cell")
continue
ret[name].append(item)
# stat
logging.info(u"loaded {} {} (non_empty_col={})".format(
filename, len(ret[name]), non_empty_col))
return {'data': ret, 'fields': fields}
|
http://www.lexicon.net/sjmachin/xlrd.html
non_empty_col is -1 to load all rows, when set to a none-empty value,
this function will skip rows having empty cell on that col.
|
train
|
https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/table.py#L56-L106
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# table/excel data manipulation
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import re
import collections
import xlwt
import xlrd
def json2excel(items, keys, filename, page_size=60000):
""" max_page_size is 65000 because we output old excel .xls format
"""
wb = xlwt.Workbook()
rowindex = 0
sheetindex = 0
for item in items:
if rowindex % page_size == 0:
sheetname = "%02d" % sheetindex
ws = wb.add_sheet(sheetname)
rowindex = 0
sheetindex += 1
colindex = 0
for key in keys:
ws.write(rowindex, colindex, key)
colindex += 1
rowindex += 1
colindex = 0
for key in keys:
v = item.get(key, "")
if type(v) == list:
v = ','.join(v)
if type(v) == set:
v = ','.join(v)
ws.write(rowindex, colindex, v)
colindex += 1
rowindex += 1
logging.debug(filename)
wb.save(filename)
|
frostming/marko
|
marko/helpers.py
|
camel_to_snake_case
|
python
|
def camel_to_snake_case(name):
pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])'
return '_'.join(map(str.lower, re.findall(pattern, name)))
|
Takes a camelCased string and converts to snake_case.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L10-L13
| null |
"""
Helper functions and data structures
"""
import re
from contextlib import contextmanager
from ._compat import string_types
def is_paired(text, open='(', close=')'):
"""Check if the text only contains:
1. blackslash escaped parentheses, or
2. parentheses paired.
"""
count = 0
escape = False
for c in text:
if escape:
escape = False
elif c == '\\':
escape = True
elif c == open:
count += 1
elif c == close:
if count == 0:
return False
count -= 1
return count == 0
def _preprocess_text(text):
return text.replace('\r\n', '\n')
class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element state."""
if not self._states:
return None
return self._states[-1]
@property
def root(self):
"""Returns the root element, which is at the bottom of self._states."""
if not self._states:
return None
return self._states[0]
def push_state(self, element):
"""Push a new state to the state stack."""
self._states.append(element)
def pop_state(self):
"""Pop the top most state."""
return self._states.pop()
@contextmanager
def under_state(self, element):
"""A context manager to enable a new state temporarily."""
self.push_state(element)
yield self
self.pop_state()
@property
def exhausted(self):
"""Indicates whether the source reaches the end."""
return self.pos >= len(self._buffer)
@property
def prefix(self):
"""The prefix of each line when parsing."""
return ''.join(s._prefix for s in self._states)
@property
def rest(self):
"""The remaining source unparsed."""
return self._buffer[self.pos:]
def _expect_re(self, regexp, pos):
if isinstance(regexp, string_types):
regexp = re.compile(regexp)
return regexp.match(self._buffer, pos)
@staticmethod
def match_prefix(prefix, line):
"""Check if the line starts with given prefix and
return the position of the end of prefix.
If the prefix is not matched, return -1.
"""
m = re.match(prefix, line.expandtabs(4))
if not m:
if re.match(prefix, line.expandtabs(4).replace('\n', ' ' * 99 + '\n')):
return len(line) - 1
return -1
pos = m.end()
if pos == 0:
return 0
for i in range(1, len(line) + 1):
if len(line[:i].expandtabs(4)) >= pos:
return i
def expect_re(self, regexp):
"""Test against the given regular expression and returns the match object.
:param regexp: the expression to be tested.
:returns: the match object.
"""
prefix_len = self.match_prefix(
self.prefix, self.next_line(require_prefix=False)
)
if prefix_len >= 0:
match = self._expect_re(regexp, self.pos + prefix_len)
self.match = match
return match
else:
return None
def next_line(self, require_prefix=True):
"""Return the next line in the source.
:param require_prefix: if False, the whole line will be returned.
otherwise, return the line with prefix stripped or None if the prefix
is not matched.
"""
if require_prefix:
m = self.expect_re(r'(?m)[^\n]*?$\n?')
else:
m = self._expect_re(r'(?m)[^\n]*$\n?', self.pos)
self.match = m
if m:
return m.group()
def consume(self):
"""Consume the body of source. ``pos`` will move forward."""
if self.match:
self.pos = self.match.end()
if self.match.group()[-1] == '\n':
self._update_prefix()
self.match = None
def anchor(self):
"""Pin the current parsing position."""
self._anchor = self.pos
def reset(self):
"""Reset the position to the last anchor."""
self.pos = self._anchor
def _update_prefix(self):
for s in self._states:
if hasattr(s, '_second_prefix'):
s._prefix = s._second_prefix
def normalize_label(label):
"""Return the normalized form of link label."""
return re.sub(r'\s+', ' ', label).strip().lower()
|
frostming/marko
|
marko/helpers.py
|
is_paired
|
python
|
def is_paired(text, open='(', close=')'):
count = 0
escape = False
for c in text:
if escape:
escape = False
elif c == '\\':
escape = True
elif c == open:
count += 1
elif c == close:
if count == 0:
return False
count -= 1
return count == 0
|
Check if the text only contains:
1. blackslash escaped parentheses, or
2. parentheses paired.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L16-L34
| null |
"""
Helper functions and data structures
"""
import re
from contextlib import contextmanager
from ._compat import string_types
def camel_to_snake_case(name):
"""Takes a camelCased string and converts to snake_case."""
pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])'
return '_'.join(map(str.lower, re.findall(pattern, name)))
def _preprocess_text(text):
return text.replace('\r\n', '\n')
class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element state."""
if not self._states:
return None
return self._states[-1]
@property
def root(self):
"""Returns the root element, which is at the bottom of self._states."""
if not self._states:
return None
return self._states[0]
def push_state(self, element):
"""Push a new state to the state stack."""
self._states.append(element)
def pop_state(self):
"""Pop the top most state."""
return self._states.pop()
@contextmanager
def under_state(self, element):
"""A context manager to enable a new state temporarily."""
self.push_state(element)
yield self
self.pop_state()
@property
def exhausted(self):
"""Indicates whether the source reaches the end."""
return self.pos >= len(self._buffer)
@property
def prefix(self):
"""The prefix of each line when parsing."""
return ''.join(s._prefix for s in self._states)
@property
def rest(self):
"""The remaining source unparsed."""
return self._buffer[self.pos:]
def _expect_re(self, regexp, pos):
if isinstance(regexp, string_types):
regexp = re.compile(regexp)
return regexp.match(self._buffer, pos)
@staticmethod
def match_prefix(prefix, line):
"""Check if the line starts with given prefix and
return the position of the end of prefix.
If the prefix is not matched, return -1.
"""
m = re.match(prefix, line.expandtabs(4))
if not m:
if re.match(prefix, line.expandtabs(4).replace('\n', ' ' * 99 + '\n')):
return len(line) - 1
return -1
pos = m.end()
if pos == 0:
return 0
for i in range(1, len(line) + 1):
if len(line[:i].expandtabs(4)) >= pos:
return i
def expect_re(self, regexp):
"""Test against the given regular expression and returns the match object.
:param regexp: the expression to be tested.
:returns: the match object.
"""
prefix_len = self.match_prefix(
self.prefix, self.next_line(require_prefix=False)
)
if prefix_len >= 0:
match = self._expect_re(regexp, self.pos + prefix_len)
self.match = match
return match
else:
return None
def next_line(self, require_prefix=True):
"""Return the next line in the source.
:param require_prefix: if False, the whole line will be returned.
otherwise, return the line with prefix stripped or None if the prefix
is not matched.
"""
if require_prefix:
m = self.expect_re(r'(?m)[^\n]*?$\n?')
else:
m = self._expect_re(r'(?m)[^\n]*$\n?', self.pos)
self.match = m
if m:
return m.group()
def consume(self):
"""Consume the body of source. ``pos`` will move forward."""
if self.match:
self.pos = self.match.end()
if self.match.group()[-1] == '\n':
self._update_prefix()
self.match = None
def anchor(self):
"""Pin the current parsing position."""
self._anchor = self.pos
def reset(self):
"""Reset the position to the last anchor."""
self.pos = self._anchor
def _update_prefix(self):
for s in self._states:
if hasattr(s, '_second_prefix'):
s._prefix = s._second_prefix
def normalize_label(label):
"""Return the normalized form of link label."""
return re.sub(r'\s+', ' ', label).strip().lower()
|
frostming/marko
|
marko/helpers.py
|
Source.match_prefix
|
python
|
def match_prefix(prefix, line):
m = re.match(prefix, line.expandtabs(4))
if not m:
if re.match(prefix, line.expandtabs(4).replace('\n', ' ' * 99 + '\n')):
return len(line) - 1
return -1
pos = m.end()
if pos == 0:
return 0
for i in range(1, len(line) + 1):
if len(line[:i].expandtabs(4)) >= pos:
return i
|
Check if the line starts with given prefix and
return the position of the end of prefix.
If the prefix is not matched, return -1.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L101-L116
| null |
class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element state."""
if not self._states:
return None
return self._states[-1]
@property
def root(self):
"""Returns the root element, which is at the bottom of self._states."""
if not self._states:
return None
return self._states[0]
def push_state(self, element):
"""Push a new state to the state stack."""
self._states.append(element)
def pop_state(self):
"""Pop the top most state."""
return self._states.pop()
@contextmanager
def under_state(self, element):
"""A context manager to enable a new state temporarily."""
self.push_state(element)
yield self
self.pop_state()
@property
def exhausted(self):
"""Indicates whether the source reaches the end."""
return self.pos >= len(self._buffer)
@property
def prefix(self):
"""The prefix of each line when parsing."""
return ''.join(s._prefix for s in self._states)
@property
def rest(self):
"""The remaining source unparsed."""
return self._buffer[self.pos:]
def _expect_re(self, regexp, pos):
if isinstance(regexp, string_types):
regexp = re.compile(regexp)
return regexp.match(self._buffer, pos)
@staticmethod
def expect_re(self, regexp):
"""Test against the given regular expression and returns the match object.
:param regexp: the expression to be tested.
:returns: the match object.
"""
prefix_len = self.match_prefix(
self.prefix, self.next_line(require_prefix=False)
)
if prefix_len >= 0:
match = self._expect_re(regexp, self.pos + prefix_len)
self.match = match
return match
else:
return None
def next_line(self, require_prefix=True):
"""Return the next line in the source.
:param require_prefix: if False, the whole line will be returned.
otherwise, return the line with prefix stripped or None if the prefix
is not matched.
"""
if require_prefix:
m = self.expect_re(r'(?m)[^\n]*?$\n?')
else:
m = self._expect_re(r'(?m)[^\n]*$\n?', self.pos)
self.match = m
if m:
return m.group()
def consume(self):
"""Consume the body of source. ``pos`` will move forward."""
if self.match:
self.pos = self.match.end()
if self.match.group()[-1] == '\n':
self._update_prefix()
self.match = None
def anchor(self):
"""Pin the current parsing position."""
self._anchor = self.pos
def reset(self):
"""Reset the position to the last anchor."""
self.pos = self._anchor
def _update_prefix(self):
for s in self._states:
if hasattr(s, '_second_prefix'):
s._prefix = s._second_prefix
|
frostming/marko
|
marko/helpers.py
|
Source.expect_re
|
python
|
def expect_re(self, regexp):
prefix_len = self.match_prefix(
self.prefix, self.next_line(require_prefix=False)
)
if prefix_len >= 0:
match = self._expect_re(regexp, self.pos + prefix_len)
self.match = match
return match
else:
return None
|
Test against the given regular expression and returns the match object.
:param regexp: the expression to be tested.
:returns: the match object.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L118-L132
|
[
"def _expect_re(self, regexp, pos):\n if isinstance(regexp, string_types):\n regexp = re.compile(regexp)\n return regexp.match(self._buffer, pos)\n",
"def match_prefix(prefix, line):\n \"\"\"Check if the line starts with given prefix and\n return the position of the end of prefix.\n If the prefix is not matched, return -1.\n \"\"\"\n m = re.match(prefix, line.expandtabs(4))\n if not m:\n if re.match(prefix, line.expandtabs(4).replace('\\n', ' ' * 99 + '\\n')):\n return len(line) - 1\n return -1\n pos = m.end()\n if pos == 0:\n return 0\n for i in range(1, len(line) + 1):\n if len(line[:i].expandtabs(4)) >= pos:\n return i\n",
"def next_line(self, require_prefix=True):\n \"\"\"Return the next line in the source.\n\n :param require_prefix: if False, the whole line will be returned.\n otherwise, return the line with prefix stripped or None if the prefix\n is not matched.\n \"\"\"\n if require_prefix:\n m = self.expect_re(r'(?m)[^\\n]*?$\\n?')\n else:\n m = self._expect_re(r'(?m)[^\\n]*$\\n?', self.pos)\n self.match = m\n if m:\n return m.group()\n"
] |
class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element state."""
if not self._states:
return None
return self._states[-1]
@property
def root(self):
"""Returns the root element, which is at the bottom of self._states."""
if not self._states:
return None
return self._states[0]
def push_state(self, element):
"""Push a new state to the state stack."""
self._states.append(element)
def pop_state(self):
"""Pop the top most state."""
return self._states.pop()
@contextmanager
def under_state(self, element):
"""A context manager to enable a new state temporarily."""
self.push_state(element)
yield self
self.pop_state()
@property
def exhausted(self):
"""Indicates whether the source reaches the end."""
return self.pos >= len(self._buffer)
@property
def prefix(self):
"""The prefix of each line when parsing."""
return ''.join(s._prefix for s in self._states)
@property
def rest(self):
"""The remaining source unparsed."""
return self._buffer[self.pos:]
def _expect_re(self, regexp, pos):
if isinstance(regexp, string_types):
regexp = re.compile(regexp)
return regexp.match(self._buffer, pos)
@staticmethod
def match_prefix(prefix, line):
"""Check if the line starts with given prefix and
return the position of the end of prefix.
If the prefix is not matched, return -1.
"""
m = re.match(prefix, line.expandtabs(4))
if not m:
if re.match(prefix, line.expandtabs(4).replace('\n', ' ' * 99 + '\n')):
return len(line) - 1
return -1
pos = m.end()
if pos == 0:
return 0
for i in range(1, len(line) + 1):
if len(line[:i].expandtabs(4)) >= pos:
return i
def next_line(self, require_prefix=True):
"""Return the next line in the source.
:param require_prefix: if False, the whole line will be returned.
otherwise, return the line with prefix stripped or None if the prefix
is not matched.
"""
if require_prefix:
m = self.expect_re(r'(?m)[^\n]*?$\n?')
else:
m = self._expect_re(r'(?m)[^\n]*$\n?', self.pos)
self.match = m
if m:
return m.group()
def consume(self):
"""Consume the body of source. ``pos`` will move forward."""
if self.match:
self.pos = self.match.end()
if self.match.group()[-1] == '\n':
self._update_prefix()
self.match = None
def anchor(self):
"""Pin the current parsing position."""
self._anchor = self.pos
def reset(self):
"""Reset the position to the last anchor."""
self.pos = self._anchor
def _update_prefix(self):
for s in self._states:
if hasattr(s, '_second_prefix'):
s._prefix = s._second_prefix
|
frostming/marko
|
marko/helpers.py
|
Source.next_line
|
python
|
def next_line(self, require_prefix=True):
if require_prefix:
m = self.expect_re(r'(?m)[^\n]*?$\n?')
else:
m = self._expect_re(r'(?m)[^\n]*$\n?', self.pos)
self.match = m
if m:
return m.group()
|
Return the next line in the source.
:param require_prefix: if False, the whole line will be returned.
otherwise, return the line with prefix stripped or None if the prefix
is not matched.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L134-L147
|
[
"def _expect_re(self, regexp, pos):\n if isinstance(regexp, string_types):\n regexp = re.compile(regexp)\n return regexp.match(self._buffer, pos)\n",
"def expect_re(self, regexp):\n \"\"\"Test against the given regular expression and returns the match object.\n\n :param regexp: the expression to be tested.\n :returns: the match object.\n \"\"\"\n prefix_len = self.match_prefix(\n self.prefix, self.next_line(require_prefix=False)\n )\n if prefix_len >= 0:\n match = self._expect_re(regexp, self.pos + prefix_len)\n self.match = match\n return match\n else:\n return None\n"
] |
class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element state."""
if not self._states:
return None
return self._states[-1]
@property
def root(self):
"""Returns the root element, which is at the bottom of self._states."""
if not self._states:
return None
return self._states[0]
def push_state(self, element):
"""Push a new state to the state stack."""
self._states.append(element)
def pop_state(self):
"""Pop the top most state."""
return self._states.pop()
@contextmanager
def under_state(self, element):
"""A context manager to enable a new state temporarily."""
self.push_state(element)
yield self
self.pop_state()
@property
def exhausted(self):
"""Indicates whether the source reaches the end."""
return self.pos >= len(self._buffer)
@property
def prefix(self):
"""The prefix of each line when parsing."""
return ''.join(s._prefix for s in self._states)
@property
def rest(self):
"""The remaining source unparsed."""
return self._buffer[self.pos:]
def _expect_re(self, regexp, pos):
if isinstance(regexp, string_types):
regexp = re.compile(regexp)
return regexp.match(self._buffer, pos)
@staticmethod
def match_prefix(prefix, line):
"""Check if the line starts with given prefix and
return the position of the end of prefix.
If the prefix is not matched, return -1.
"""
m = re.match(prefix, line.expandtabs(4))
if not m:
if re.match(prefix, line.expandtabs(4).replace('\n', ' ' * 99 + '\n')):
return len(line) - 1
return -1
pos = m.end()
if pos == 0:
return 0
for i in range(1, len(line) + 1):
if len(line[:i].expandtabs(4)) >= pos:
return i
def expect_re(self, regexp):
"""Test against the given regular expression and returns the match object.
:param regexp: the expression to be tested.
:returns: the match object.
"""
prefix_len = self.match_prefix(
self.prefix, self.next_line(require_prefix=False)
)
if prefix_len >= 0:
match = self._expect_re(regexp, self.pos + prefix_len)
self.match = match
return match
else:
return None
def consume(self):
"""Consume the body of source. ``pos`` will move forward."""
if self.match:
self.pos = self.match.end()
if self.match.group()[-1] == '\n':
self._update_prefix()
self.match = None
def anchor(self):
"""Pin the current parsing position."""
self._anchor = self.pos
def reset(self):
"""Reset the position to the last anchor."""
self.pos = self._anchor
def _update_prefix(self):
for s in self._states:
if hasattr(s, '_second_prefix'):
s._prefix = s._second_prefix
|
frostming/marko
|
marko/helpers.py
|
Source.consume
|
python
|
def consume(self):
if self.match:
self.pos = self.match.end()
if self.match.group()[-1] == '\n':
self._update_prefix()
self.match = None
|
Consume the body of source. ``pos`` will move forward.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L149-L155
| null |
class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element state."""
if not self._states:
return None
return self._states[-1]
@property
def root(self):
"""Returns the root element, which is at the bottom of self._states."""
if not self._states:
return None
return self._states[0]
def push_state(self, element):
"""Push a new state to the state stack."""
self._states.append(element)
def pop_state(self):
"""Pop the top most state."""
return self._states.pop()
@contextmanager
def under_state(self, element):
"""A context manager to enable a new state temporarily."""
self.push_state(element)
yield self
self.pop_state()
@property
def exhausted(self):
"""Indicates whether the source reaches the end."""
return self.pos >= len(self._buffer)
@property
def prefix(self):
"""The prefix of each line when parsing."""
return ''.join(s._prefix for s in self._states)
@property
def rest(self):
"""The remaining source unparsed."""
return self._buffer[self.pos:]
def _expect_re(self, regexp, pos):
if isinstance(regexp, string_types):
regexp = re.compile(regexp)
return regexp.match(self._buffer, pos)
@staticmethod
def match_prefix(prefix, line):
"""Check if the line starts with given prefix and
return the position of the end of prefix.
If the prefix is not matched, return -1.
"""
m = re.match(prefix, line.expandtabs(4))
if not m:
if re.match(prefix, line.expandtabs(4).replace('\n', ' ' * 99 + '\n')):
return len(line) - 1
return -1
pos = m.end()
if pos == 0:
return 0
for i in range(1, len(line) + 1):
if len(line[:i].expandtabs(4)) >= pos:
return i
def expect_re(self, regexp):
"""Test against the given regular expression and returns the match object.
:param regexp: the expression to be tested.
:returns: the match object.
"""
prefix_len = self.match_prefix(
self.prefix, self.next_line(require_prefix=False)
)
if prefix_len >= 0:
match = self._expect_re(regexp, self.pos + prefix_len)
self.match = match
return match
else:
return None
def next_line(self, require_prefix=True):
"""Return the next line in the source.
:param require_prefix: if False, the whole line will be returned.
otherwise, return the line with prefix stripped or None if the prefix
is not matched.
"""
if require_prefix:
m = self.expect_re(r'(?m)[^\n]*?$\n?')
else:
m = self._expect_re(r'(?m)[^\n]*$\n?', self.pos)
self.match = m
if m:
return m.group()
def anchor(self):
"""Pin the current parsing position."""
self._anchor = self.pos
def reset(self):
"""Reset the position to the last anchor."""
self.pos = self._anchor
def _update_prefix(self):
for s in self._states:
if hasattr(s, '_second_prefix'):
s._prefix = s._second_prefix
|
frostming/marko
|
marko/__init__.py
|
Markdown.render
|
python
|
def render(self, parsed):
self.renderer.root_node = parsed
with self.renderer as r:
return r.render(parsed)
|
Call ``self.renderer.render(text)``.
Override this to handle parsed result.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/__init__.py#L48-L55
| null |
class Markdown(object):
"""The main class to convert markdown documents.
Attributes:
parser: an instance of :class:`Parser`
renderer: an instance of :class:`Renderer`
:param parser: a subclass or instance of :class:`Parser`
:param renderer: a subclass or instance of :class:`Renderer`
"""
def __init__(self, parser=Parser, renderer=HTMLRenderer):
self.parser = parser if isinstance(parser, Parser) else parser()
self.renderer = renderer if isinstance(renderer, Renderer) else renderer()
def convert(self, text):
"""Parse and render the given text."""
return self.render(self.parse(text))
def __call__(self, text):
return self.convert(text)
def parse(self, text):
"""Call ``self.parser.parse(text)``.
Override this to preprocess text or handle parsed result.
"""
return self.parser.parse(text)
|
frostming/marko
|
marko/renderer.py
|
Renderer.render
|
python
|
def render(self, element):
# Store the root node to provide some context to render functions
if not self.root_node:
self.root_node = element
render_func = getattr(
self, self._cls_to_func_name(element.__class__), None)
if not render_func:
render_func = self.render_children
return render_func(element)
|
Renders the given element to string.
:param element: a element to be rendered.
:returns: the output string or any values.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/renderer.py#L37-L50
|
[
"def render_children(self, element):\n if isinstance(element, list):\n return [self.render_children(e) for e in element]\n if isinstance(element, string_types):\n return element\n rv = {k: v for k, v in element.__dict__.items() if not k.startswith('_')}\n if 'children' in rv:\n rv['children'] = self.render(rv['children'])\n rv['element'] = camel_to_snake_case(element.__class__.__name__)\n return rv\n",
"def render_children(self, element):\n \"\"\"\n Recursively renders child elements. Joins the rendered\n strings with no space in between.\n\n If newlines / spaces are needed between elements, add them\n in their respective templates, or override this function\n in the renderer subclass, so that whitespace won't seem to\n appear magically for anyone reading your program.\n\n :param element: a branch node who has children attribute.\n \"\"\"\n rendered = [self.render(child) for child in element.children]\n return ''.join(rendered)\n",
"def _cls_to_func_name(self, klass):\n from .block import parser\n element_types = itertools.chain(\n parser.block_elements.items(),\n parser.inline_elements.items()\n )\n for name, cls in element_types:\n if cls is klass:\n return 'render_' + camel_to_snake_case(name)\n\n return 'render_children'\n"
] |
class Renderer(object):
"""The base class of renderers.
A custom renderer should subclass this class and include your own render functions.
A render function should:
* be named as ``render_<element_name>``, where the ``element_name`` is the snake
case form of the element class name, the renderer will search the corresponding
function in this way.
* accept the element instance and return any output you want.
If no corresponding render function is found, renderer will fallback to call
:meth:`Renderer.render_children`.
"""
def __init__(self):
self.root_node = None
def __enter__(self):
"""Provide a context so that root_node can be reset after render."""
return self
def __exit__(self, *args):
pass
def render_children(self, element):
"""
Recursively renders child elements. Joins the rendered
strings with no space in between.
If newlines / spaces are needed between elements, add them
in their respective templates, or override this function
in the renderer subclass, so that whitespace won't seem to
appear magically for anyone reading your program.
:param element: a branch node who has children attribute.
"""
rendered = [self.render(child) for child in element.children]
return ''.join(rendered)
def _cls_to_func_name(self, klass):
from .block import parser
element_types = itertools.chain(
parser.block_elements.items(),
parser.inline_elements.items()
)
for name, cls in element_types:
if cls is klass:
return 'render_' + camel_to_snake_case(name)
return 'render_children'
|
frostming/marko
|
marko/renderer.py
|
Renderer.render_children
|
python
|
def render_children(self, element):
rendered = [self.render(child) for child in element.children]
return ''.join(rendered)
|
Recursively renders child elements. Joins the rendered
strings with no space in between.
If newlines / spaces are needed between elements, add them
in their respective templates, or override this function
in the renderer subclass, so that whitespace won't seem to
appear magically for anyone reading your program.
:param element: a branch node who has children attribute.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/renderer.py#L52-L65
| null |
class Renderer(object):
"""The base class of renderers.
A custom renderer should subclass this class and include your own render functions.
A render function should:
* be named as ``render_<element_name>``, where the ``element_name`` is the snake
case form of the element class name, the renderer will search the corresponding
function in this way.
* accept the element instance and return any output you want.
If no corresponding render function is found, renderer will fallback to call
:meth:`Renderer.render_children`.
"""
def __init__(self):
self.root_node = None
def __enter__(self):
"""Provide a context so that root_node can be reset after render."""
return self
def __exit__(self, *args):
pass
def render(self, element):
"""Renders the given element to string.
:param element: a element to be rendered.
:returns: the output string or any values.
"""
# Store the root node to provide some context to render functions
if not self.root_node:
self.root_node = element
render_func = getattr(
self, self._cls_to_func_name(element.__class__), None)
if not render_func:
render_func = self.render_children
return render_func(element)
def _cls_to_func_name(self, klass):
from .block import parser
element_types = itertools.chain(
parser.block_elements.items(),
parser.inline_elements.items()
)
for name, cls in element_types:
if cls is klass:
return 'render_' + camel_to_snake_case(name)
return 'render_children'
|
frostming/marko
|
marko/inline.py
|
InlineElement.find
|
python
|
def find(cls, text):
if isinstance(cls.pattern, string_types):
cls.pattern = re.compile(cls.pattern)
return cls.pattern.finditer(text)
|
This method should return an iterable containing matches of this element.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline.py#L39-L43
| null |
class InlineElement(object):
"""Any inline element should inherit this class"""
#: Use to denote the precedence in parsing.
priority = 5
#: element regex pattern.
pattern = None
#: whether to parse children.
parse_children = False
#: which match group to parse.
parse_group = 1
#: if True, it won't be included in parsing process but produced by
#: other elements instead.
virtual = False
def __init__(self, match):
"""Parses the matched object into an element"""
if not self.parse_children:
self.children = match.group(self.parse_group)
@classmethod
|
frostming/marko
|
marko/inline_parser.py
|
parse
|
python
|
def parse(text, elements, fallback):
# this is a raw list of elements that may contain overlaps.
tokens = []
for etype in elements:
for match in etype.find(text):
tokens.append(Token(etype, match, text, fallback))
tokens.sort()
tokens = _resolve_overlap(tokens)
return make_elements(tokens, text, fallback=fallback)
|
Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param elements: the element types to be included in parsing
:param fallback: fallback class when no other element type is matched.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L12-L26
|
[
"def _resolve_overlap(tokens):\n if not tokens:\n return tokens\n result = []\n prev = tokens[0]\n for cur in tokens[1:]:\n r = prev.relation(cur)\n if r == Token.PRECEDE:\n result.append(prev)\n prev = cur\n elif r == Token.CONTAIN:\n prev.append_child(cur)\n elif r == Token.INTERSECT and prev.etype.priority < cur.etype.priority:\n prev = cur\n result.append(prev)\n return result\n",
"def make_elements(tokens, text, start=0, end=None, fallback=None):\n \"\"\"Make elements from a list of parsed tokens.\n It will turn all unmatched holes into fallback elements.\n\n :param tokens: a list of parsed tokens.\n :param text: the original tet.\n :param start: the offset of where parsing starts. Defaults to the start of text.\n :param end: the offset of where parsing ends. Defauls to the end of text.\n :param fallback: fallback element type.\n :returns: a list of inline elements.\n \"\"\"\n result = []\n end = end or len(text)\n prev_end = start\n for token in tokens:\n if prev_end < token.start:\n result.append(fallback(text[prev_end:token.start]))\n result.append(token.as_element())\n prev_end = token.end\n if prev_end < end:\n result.append(fallback(text[prev_end:end]))\n return result\n"
] |
"""
Parse inline elements
"""
from __future__ import unicode_literals
import re
import string
from .helpers import is_paired, normalize_label
from . import patterns
def _resolve_overlap(tokens):
if not tokens:
return tokens
result = []
prev = tokens[0]
for cur in tokens[1:]:
r = prev.relation(cur)
if r == Token.PRECEDE:
result.append(prev)
prev = cur
elif r == Token.CONTAIN:
prev.append_child(cur)
elif r == Token.INTERSECT and prev.etype.priority < cur.etype.priority:
prev = cur
result.append(prev)
return result
def make_elements(tokens, text, start=0, end=None, fallback=None):
"""Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Defaults to the start of text.
:param end: the offset of where parsing ends. Defauls to the end of text.
:param fallback: fallback element type.
:returns: a list of inline elements.
"""
result = []
end = end or len(text)
prev_end = start
for token in tokens:
if prev_end < token.start:
result.append(fallback(text[prev_end:token.start]))
result.append(token.as_element())
prev_end = token.end
if prev_end < end:
result.append(fallback(text[prev_end:end]))
return result
class Token(object):
"""An intermediate class to wrap the match object.
It can be converted to element by :meth:`as_element()`
"""
PRECEDE = 0
INTERSECT = 1
CONTAIN = 2
SHADE = 3
def __init__(self, etype, match, text, fallback):
self.etype = etype
self.match = match
self.start = match.start()
self.end = match.end()
self.inner_start = match.start(etype.parse_group)
self.inner_end = match.end(etype.parse_group)
self.text = text
self.fallback = fallback
self.children = []
def relation(self, other):
if self.end <= other.start:
return Token.PRECEDE
if self.end >= other.end:
if other.start >= self.inner_start and other.end <= self.inner_end:
return Token.CONTAIN
if self.inner_end <= other.start:
return Token.SHADE
return Token.INTERSECT
def append_child(self, child):
if not self.etype.parse_children:
return
self.children.append(child)
def as_element(self):
e = self.etype(self.match)
if e.parse_children:
self.children = _resolve_overlap(self.children)
e.children = make_elements(
self.children, self.text, self.inner_start,
self.inner_end, self.fallback
)
return e
def __repr__(self):
return '<{}: {} start={} end={}>'.format(
self.__class__.__name__, self.etype.__name__, self.start, self.end
)
def __lt__(self, o):
return self.start < o.start
def find_links_or_emphs(text, root_node):
"""Fink links/images or emphasis from text.
:param text: the original text.
:param root_node: a reference to the root node of the AST.
:returns: an iterable of match object.
"""
delimiters_re = re.compile(r'(?:!?\[|\*+|_+)')
i = 0
delimiters = []
escape = False
matches = []
code_pattern = re.compile(r'(?<!`)(`+)(?!`)([\s\S]+?)(?<!`)\1(?!`)')
while i < len(text):
if escape:
escape = False
i += 1
elif text[i] == '\\':
escape = True
i += 1
elif code_pattern.match(text, i):
i = code_pattern.match(text, i).end()
elif text[i] == ']':
node = look_for_image_or_link(text, delimiters, i, root_node, matches)
if node:
i = node.end()
matches.append(node)
else:
i += 1
else:
m = delimiters_re.match(text, i)
if m:
delimiters.append(Delimiter(m, text))
i = m.end()
else:
i += 1
process_emphasis(text, delimiters, None, matches)
return matches
def look_for_image_or_link(text, delimiters, close, root_node, matches):
for i, d in list(enumerate(delimiters))[::-1]:
if d.content not in ('[', '!['):
continue
if not d.active:
break # break to remove the delimiter and return None
if not _is_legal_link_text(text[d.end:close]):
break
link_text = (d.end, close, text[d.end:close])
etype = 'Image' if d.content == '![' else 'Link'
match = (
_expect_inline_link(text, close + 1) or
_expect_reference_link(text, close + 1, link_text[2], root_node)
)
if not match: # not a link
break
rv = MatchObj(
etype, text, d.start, match[2], link_text, match[0], match[1]
)
process_emphasis(text, delimiters, i, matches)
if etype == 'Link':
for d in delimiters[:i]:
if d.content == '[':
d.active = False
del delimiters[i]
return rv
else:
# no matching opener is found
return None
del delimiters[i]
return None
def _is_legal_link_text(text):
return is_paired(text, '[', ']')
def _expect_inline_link(text, start):
"""(link_dest "link_title")"""
if start >= len(text) or text[start] != '(':
return None
i = start + 1
m = patterns.whitespace.match(text, i)
if m:
i = m.end()
m = patterns.link_dest_1.match(text, i)
if m:
link_dest = m.start(), m.end(), m.group()
i = m.end()
else:
open_num = 0
escaped = False
prev = i
while i < len(text):
c = text[i]
if escaped:
escaped = False
elif c == '\\':
escaped = True
elif c == '(':
open_num += 1
elif c in string.whitespace:
break
elif c == ')':
if open_num > 0:
open_num -= 1
else:
break
i += 1
if open_num != 0:
return None
link_dest = prev, i, text[prev:i]
link_title = i, i, None
tail_re = re.compile(r'(?:\s+%s)?\s*\)' % patterns.link_title, flags=re.UNICODE)
m = tail_re.match(text, i)
if not m:
return None
if m.group('title'):
link_title = m.start('title'), m.end('title'), m.group('title')
return (link_dest, link_title, m.end())
def _expect_reference_link(text, start, link_text, root_node):
match = patterns.optional_label.match(text, start)
link_label = link_text
if match and match.group()[1:-1]:
link_label = match.group()[1:-1]
result = _get_reference_link(link_label, root_node)
if not result:
return None
link_dest = start, start, result[0]
link_title = start, start, result[1]
return (link_dest, link_title, match and match.end() or start)
def _get_reference_link(link_label, root_node):
normalized_label = normalize_label(link_label)
return root_node.link_ref_defs.get(normalized_label, None)
def process_emphasis(text, delimiters, stack_bottom, matches):
star_bottom = underscore_bottom = stack_bottom
cur = _next_closer(delimiters, stack_bottom)
while cur is not None:
d_closer = delimiters[cur]
bottom = star_bottom if d_closer.content[0] == '*' else underscore_bottom
opener = _nearest_opener(delimiters, cur, bottom)
if opener is not None:
d_opener = delimiters[opener]
n = 2 if len(d_opener.content) >= 2 and len(d_closer.content) >= 2 else 1
match = MatchObj(
'StrongEmphasis' if n == 2 else 'Emphasis',
text,
d_opener.end - n,
d_closer.start + n,
(d_opener.end, d_closer.start, text[d_opener.end:d_closer.start])
)
matches.append(match)
del delimiters[opener + 1:cur]
cur -= cur - opener - 1
if d_opener.remove(n):
delimiters.remove(d_opener)
cur -= 1
if d_closer.remove(n, True):
delimiters.remove(d_closer)
cur = cur - 1 if cur > 0 else None
else:
bottom = cur - 1 if cur > 1 else None
if d_closer.content[0] == '*':
star_bottom = bottom
else:
underscore_bottom = bottom
if not d_closer.can_open:
delimiters.remove(d_closer)
cur = _next_closer(delimiters, cur)
lower = stack_bottom + 1 if stack_bottom is not None else 0
del delimiters[lower:]
def _next_closer(delimiters, bound):
i = bound + 1 if bound is not None else 0
while i < len(delimiters):
d = delimiters[i]
if hasattr(d, 'can_close') and d.can_close:
return i
i += 1
return None
def _nearest_opener(delimiters, higher, lower):
i = higher - 1
lower = lower if lower is not None else -1
while i > lower:
d = delimiters[i]
if hasattr(d, 'can_open') and d.can_open and d.closed_by(delimiters[higher]):
return i
i -= 1
return None
class Delimiter(object):
whitespace_re = re.compile(r'\s', flags=re.UNICODE)
def __init__(self, match, text):
self.start = match.start()
self.end = match.end()
self.content = match.group()
self.text = text
self.active = True
if self.content[0] in ('*', '_'):
self.can_open = self._can_open()
self.can_close = self._can_close()
def _can_open(self):
if self.content[0] == '*':
return self.is_left_flanking()
return self.is_left_flanking() and (
not self.is_right_flanking()
or self.preceded_by(string.punctuation)
)
def _can_close(self):
if self.content[0] == '*':
return self.is_right_flanking()
return self.is_right_flanking() and (
not self.is_left_flanking()
or self.followed_by(string.punctuation)
)
def is_left_flanking(self):
return (
self.end < len(self.text) and
self.whitespace_re.match(self.text, self.end) is None
) and (
not self.followed_by(string.punctuation)
or self.start == 0
or self.preceded_by(string.punctuation)
or self.whitespace_re.match(self.text, self.start - 1)
)
def is_right_flanking(self):
return (
self.start > 0 and
self.whitespace_re.match(self.text, self.start - 1) is None
) and (
not self.preceded_by(string.punctuation)
or self.end == len(self.text)
or self.followed_by(string.punctuation)
or self.whitespace_re.match(self.text, self.end)
)
def followed_by(self, target):
return self.end < len(self.text) and self.text[self.end] in target
def preceded_by(self, target):
return self.start > 0 and self.text[self.start - 1] in target
def closed_by(self, other):
return not (
self.content[0] != other.content[0]
or (self.can_open and self.can_close or other.can_open and other.can_close)
and len(self.content + other.content) % 3 == 0
)
def remove(self, n, left=False):
if len(self.content) <= n:
return True
if left:
self.start += n
else:
self.end -= n
self.content = self.content[n:]
return False
def __repr__(self):
return '<Delimiter {!r} start={} end={}>'.format(
self.content, self.start, self.end)
class MatchObj(object):
"""A fake match object that memes re.match methods"""
def __init__(self, etype, text, start, end, *groups):
self._text = text
self._start = start
self._end = end
self._groups = groups
self.etype = etype
def group(self, n=0):
if n == 0:
return self._text[self._start:self._end]
return self._groups[n - 1][2]
def start(self, n=0):
if n == 0:
return self._start
return self._groups[n - 1][0]
def end(self, n=0):
if n == 0:
return self._end
return self._groups[n - 1][1]
|
frostming/marko
|
marko/inline_parser.py
|
make_elements
|
python
|
def make_elements(tokens, text, start=0, end=None, fallback=None):
result = []
end = end or len(text)
prev_end = start
for token in tokens:
if prev_end < token.start:
result.append(fallback(text[prev_end:token.start]))
result.append(token.as_element())
prev_end = token.end
if prev_end < end:
result.append(fallback(text[prev_end:end]))
return result
|
Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Defaults to the start of text.
:param end: the offset of where parsing ends. Defauls to the end of text.
:param fallback: fallback element type.
:returns: a list of inline elements.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L47-L68
| null |
"""
Parse inline elements
"""
from __future__ import unicode_literals
import re
import string
from .helpers import is_paired, normalize_label
from . import patterns
def parse(text, elements, fallback):
"""Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param elements: the element types to be included in parsing
:param fallback: fallback class when no other element type is matched.
"""
# this is a raw list of elements that may contain overlaps.
tokens = []
for etype in elements:
for match in etype.find(text):
tokens.append(Token(etype, match, text, fallback))
tokens.sort()
tokens = _resolve_overlap(tokens)
return make_elements(tokens, text, fallback=fallback)
def _resolve_overlap(tokens):
if not tokens:
return tokens
result = []
prev = tokens[0]
for cur in tokens[1:]:
r = prev.relation(cur)
if r == Token.PRECEDE:
result.append(prev)
prev = cur
elif r == Token.CONTAIN:
prev.append_child(cur)
elif r == Token.INTERSECT and prev.etype.priority < cur.etype.priority:
prev = cur
result.append(prev)
return result
class Token(object):
"""An intermediate class to wrap the match object.
It can be converted to element by :meth:`as_element()`
"""
PRECEDE = 0
INTERSECT = 1
CONTAIN = 2
SHADE = 3
def __init__(self, etype, match, text, fallback):
self.etype = etype
self.match = match
self.start = match.start()
self.end = match.end()
self.inner_start = match.start(etype.parse_group)
self.inner_end = match.end(etype.parse_group)
self.text = text
self.fallback = fallback
self.children = []
def relation(self, other):
if self.end <= other.start:
return Token.PRECEDE
if self.end >= other.end:
if other.start >= self.inner_start and other.end <= self.inner_end:
return Token.CONTAIN
if self.inner_end <= other.start:
return Token.SHADE
return Token.INTERSECT
def append_child(self, child):
if not self.etype.parse_children:
return
self.children.append(child)
def as_element(self):
e = self.etype(self.match)
if e.parse_children:
self.children = _resolve_overlap(self.children)
e.children = make_elements(
self.children, self.text, self.inner_start,
self.inner_end, self.fallback
)
return e
def __repr__(self):
return '<{}: {} start={} end={}>'.format(
self.__class__.__name__, self.etype.__name__, self.start, self.end
)
def __lt__(self, o):
return self.start < o.start
def find_links_or_emphs(text, root_node):
"""Fink links/images or emphasis from text.
:param text: the original text.
:param root_node: a reference to the root node of the AST.
:returns: an iterable of match object.
"""
delimiters_re = re.compile(r'(?:!?\[|\*+|_+)')
i = 0
delimiters = []
escape = False
matches = []
code_pattern = re.compile(r'(?<!`)(`+)(?!`)([\s\S]+?)(?<!`)\1(?!`)')
while i < len(text):
if escape:
escape = False
i += 1
elif text[i] == '\\':
escape = True
i += 1
elif code_pattern.match(text, i):
i = code_pattern.match(text, i).end()
elif text[i] == ']':
node = look_for_image_or_link(text, delimiters, i, root_node, matches)
if node:
i = node.end()
matches.append(node)
else:
i += 1
else:
m = delimiters_re.match(text, i)
if m:
delimiters.append(Delimiter(m, text))
i = m.end()
else:
i += 1
process_emphasis(text, delimiters, None, matches)
return matches
def look_for_image_or_link(text, delimiters, close, root_node, matches):
for i, d in list(enumerate(delimiters))[::-1]:
if d.content not in ('[', '!['):
continue
if not d.active:
break # break to remove the delimiter and return None
if not _is_legal_link_text(text[d.end:close]):
break
link_text = (d.end, close, text[d.end:close])
etype = 'Image' if d.content == '![' else 'Link'
match = (
_expect_inline_link(text, close + 1) or
_expect_reference_link(text, close + 1, link_text[2], root_node)
)
if not match: # not a link
break
rv = MatchObj(
etype, text, d.start, match[2], link_text, match[0], match[1]
)
process_emphasis(text, delimiters, i, matches)
if etype == 'Link':
for d in delimiters[:i]:
if d.content == '[':
d.active = False
del delimiters[i]
return rv
else:
# no matching opener is found
return None
del delimiters[i]
return None
def _is_legal_link_text(text):
return is_paired(text, '[', ']')
def _expect_inline_link(text, start):
"""(link_dest "link_title")"""
if start >= len(text) or text[start] != '(':
return None
i = start + 1
m = patterns.whitespace.match(text, i)
if m:
i = m.end()
m = patterns.link_dest_1.match(text, i)
if m:
link_dest = m.start(), m.end(), m.group()
i = m.end()
else:
open_num = 0
escaped = False
prev = i
while i < len(text):
c = text[i]
if escaped:
escaped = False
elif c == '\\':
escaped = True
elif c == '(':
open_num += 1
elif c in string.whitespace:
break
elif c == ')':
if open_num > 0:
open_num -= 1
else:
break
i += 1
if open_num != 0:
return None
link_dest = prev, i, text[prev:i]
link_title = i, i, None
tail_re = re.compile(r'(?:\s+%s)?\s*\)' % patterns.link_title, flags=re.UNICODE)
m = tail_re.match(text, i)
if not m:
return None
if m.group('title'):
link_title = m.start('title'), m.end('title'), m.group('title')
return (link_dest, link_title, m.end())
def _expect_reference_link(text, start, link_text, root_node):
match = patterns.optional_label.match(text, start)
link_label = link_text
if match and match.group()[1:-1]:
link_label = match.group()[1:-1]
result = _get_reference_link(link_label, root_node)
if not result:
return None
link_dest = start, start, result[0]
link_title = start, start, result[1]
return (link_dest, link_title, match and match.end() or start)
def _get_reference_link(link_label, root_node):
normalized_label = normalize_label(link_label)
return root_node.link_ref_defs.get(normalized_label, None)
def process_emphasis(text, delimiters, stack_bottom, matches):
star_bottom = underscore_bottom = stack_bottom
cur = _next_closer(delimiters, stack_bottom)
while cur is not None:
d_closer = delimiters[cur]
bottom = star_bottom if d_closer.content[0] == '*' else underscore_bottom
opener = _nearest_opener(delimiters, cur, bottom)
if opener is not None:
d_opener = delimiters[opener]
n = 2 if len(d_opener.content) >= 2 and len(d_closer.content) >= 2 else 1
match = MatchObj(
'StrongEmphasis' if n == 2 else 'Emphasis',
text,
d_opener.end - n,
d_closer.start + n,
(d_opener.end, d_closer.start, text[d_opener.end:d_closer.start])
)
matches.append(match)
del delimiters[opener + 1:cur]
cur -= cur - opener - 1
if d_opener.remove(n):
delimiters.remove(d_opener)
cur -= 1
if d_closer.remove(n, True):
delimiters.remove(d_closer)
cur = cur - 1 if cur > 0 else None
else:
bottom = cur - 1 if cur > 1 else None
if d_closer.content[0] == '*':
star_bottom = bottom
else:
underscore_bottom = bottom
if not d_closer.can_open:
delimiters.remove(d_closer)
cur = _next_closer(delimiters, cur)
lower = stack_bottom + 1 if stack_bottom is not None else 0
del delimiters[lower:]
def _next_closer(delimiters, bound):
i = bound + 1 if bound is not None else 0
while i < len(delimiters):
d = delimiters[i]
if hasattr(d, 'can_close') and d.can_close:
return i
i += 1
return None
def _nearest_opener(delimiters, higher, lower):
i = higher - 1
lower = lower if lower is not None else -1
while i > lower:
d = delimiters[i]
if hasattr(d, 'can_open') and d.can_open and d.closed_by(delimiters[higher]):
return i
i -= 1
return None
class Delimiter(object):
whitespace_re = re.compile(r'\s', flags=re.UNICODE)
def __init__(self, match, text):
self.start = match.start()
self.end = match.end()
self.content = match.group()
self.text = text
self.active = True
if self.content[0] in ('*', '_'):
self.can_open = self._can_open()
self.can_close = self._can_close()
def _can_open(self):
if self.content[0] == '*':
return self.is_left_flanking()
return self.is_left_flanking() and (
not self.is_right_flanking()
or self.preceded_by(string.punctuation)
)
def _can_close(self):
if self.content[0] == '*':
return self.is_right_flanking()
return self.is_right_flanking() and (
not self.is_left_flanking()
or self.followed_by(string.punctuation)
)
def is_left_flanking(self):
return (
self.end < len(self.text) and
self.whitespace_re.match(self.text, self.end) is None
) and (
not self.followed_by(string.punctuation)
or self.start == 0
or self.preceded_by(string.punctuation)
or self.whitespace_re.match(self.text, self.start - 1)
)
def is_right_flanking(self):
return (
self.start > 0 and
self.whitespace_re.match(self.text, self.start - 1) is None
) and (
not self.preceded_by(string.punctuation)
or self.end == len(self.text)
or self.followed_by(string.punctuation)
or self.whitespace_re.match(self.text, self.end)
)
def followed_by(self, target):
return self.end < len(self.text) and self.text[self.end] in target
def preceded_by(self, target):
return self.start > 0 and self.text[self.start - 1] in target
def closed_by(self, other):
return not (
self.content[0] != other.content[0]
or (self.can_open and self.can_close or other.can_open and other.can_close)
and len(self.content + other.content) % 3 == 0
)
def remove(self, n, left=False):
if len(self.content) <= n:
return True
if left:
self.start += n
else:
self.end -= n
self.content = self.content[n:]
return False
def __repr__(self):
return '<Delimiter {!r} start={} end={}>'.format(
self.content, self.start, self.end)
class MatchObj(object):
"""A fake match object that memes re.match methods"""
def __init__(self, etype, text, start, end, *groups):
self._text = text
self._start = start
self._end = end
self._groups = groups
self.etype = etype
def group(self, n=0):
if n == 0:
return self._text[self._start:self._end]
return self._groups[n - 1][2]
def start(self, n=0):
if n == 0:
return self._start
return self._groups[n - 1][0]
def end(self, n=0):
if n == 0:
return self._end
return self._groups[n - 1][1]
|
frostming/marko
|
marko/inline_parser.py
|
find_links_or_emphs
|
python
|
def find_links_or_emphs(text, root_node):
delimiters_re = re.compile(r'(?:!?\[|\*+|_+)')
i = 0
delimiters = []
escape = False
matches = []
code_pattern = re.compile(r'(?<!`)(`+)(?!`)([\s\S]+?)(?<!`)\1(?!`)')
while i < len(text):
if escape:
escape = False
i += 1
elif text[i] == '\\':
escape = True
i += 1
elif code_pattern.match(text, i):
i = code_pattern.match(text, i).end()
elif text[i] == ']':
node = look_for_image_or_link(text, delimiters, i, root_node, matches)
if node:
i = node.end()
matches.append(node)
else:
i += 1
else:
m = delimiters_re.match(text, i)
if m:
delimiters.append(Delimiter(m, text))
i = m.end()
else:
i += 1
process_emphasis(text, delimiters, None, matches)
return matches
|
Fink links/images or emphasis from text.
:param text: the original text.
:param root_node: a reference to the root node of the AST.
:returns: an iterable of match object.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L125-L163
|
[
"def process_emphasis(text, delimiters, stack_bottom, matches):\n star_bottom = underscore_bottom = stack_bottom\n cur = _next_closer(delimiters, stack_bottom)\n while cur is not None:\n d_closer = delimiters[cur]\n bottom = star_bottom if d_closer.content[0] == '*' else underscore_bottom\n opener = _nearest_opener(delimiters, cur, bottom)\n if opener is not None:\n d_opener = delimiters[opener]\n n = 2 if len(d_opener.content) >= 2 and len(d_closer.content) >= 2 else 1\n match = MatchObj(\n 'StrongEmphasis' if n == 2 else 'Emphasis',\n text,\n d_opener.end - n,\n d_closer.start + n,\n (d_opener.end, d_closer.start, text[d_opener.end:d_closer.start])\n )\n matches.append(match)\n del delimiters[opener + 1:cur]\n cur -= cur - opener - 1\n if d_opener.remove(n):\n delimiters.remove(d_opener)\n cur -= 1\n if d_closer.remove(n, True):\n delimiters.remove(d_closer)\n cur = cur - 1 if cur > 0 else None\n else:\n bottom = cur - 1 if cur > 1 else None\n if d_closer.content[0] == '*':\n star_bottom = bottom\n else:\n underscore_bottom = bottom\n if not d_closer.can_open:\n delimiters.remove(d_closer)\n cur = _next_closer(delimiters, cur)\n lower = stack_bottom + 1 if stack_bottom is not None else 0\n del delimiters[lower:]\n"
] |
"""
Parse inline elements
"""
from __future__ import unicode_literals
import re
import string
from .helpers import is_paired, normalize_label
from . import patterns
def parse(text, elements, fallback):
"""Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param elements: the element types to be included in parsing
:param fallback: fallback class when no other element type is matched.
"""
# this is a raw list of elements that may contain overlaps.
tokens = []
for etype in elements:
for match in etype.find(text):
tokens.append(Token(etype, match, text, fallback))
tokens.sort()
tokens = _resolve_overlap(tokens)
return make_elements(tokens, text, fallback=fallback)
def _resolve_overlap(tokens):
if not tokens:
return tokens
result = []
prev = tokens[0]
for cur in tokens[1:]:
r = prev.relation(cur)
if r == Token.PRECEDE:
result.append(prev)
prev = cur
elif r == Token.CONTAIN:
prev.append_child(cur)
elif r == Token.INTERSECT and prev.etype.priority < cur.etype.priority:
prev = cur
result.append(prev)
return result
def make_elements(tokens, text, start=0, end=None, fallback=None):
"""Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Defaults to the start of text.
:param end: the offset of where parsing ends. Defauls to the end of text.
:param fallback: fallback element type.
:returns: a list of inline elements.
"""
result = []
end = end or len(text)
prev_end = start
for token in tokens:
if prev_end < token.start:
result.append(fallback(text[prev_end:token.start]))
result.append(token.as_element())
prev_end = token.end
if prev_end < end:
result.append(fallback(text[prev_end:end]))
return result
class Token(object):
"""An intermediate class to wrap the match object.
It can be converted to element by :meth:`as_element()`
"""
PRECEDE = 0
INTERSECT = 1
CONTAIN = 2
SHADE = 3
def __init__(self, etype, match, text, fallback):
self.etype = etype
self.match = match
self.start = match.start()
self.end = match.end()
self.inner_start = match.start(etype.parse_group)
self.inner_end = match.end(etype.parse_group)
self.text = text
self.fallback = fallback
self.children = []
def relation(self, other):
if self.end <= other.start:
return Token.PRECEDE
if self.end >= other.end:
if other.start >= self.inner_start and other.end <= self.inner_end:
return Token.CONTAIN
if self.inner_end <= other.start:
return Token.SHADE
return Token.INTERSECT
def append_child(self, child):
if not self.etype.parse_children:
return
self.children.append(child)
def as_element(self):
e = self.etype(self.match)
if e.parse_children:
self.children = _resolve_overlap(self.children)
e.children = make_elements(
self.children, self.text, self.inner_start,
self.inner_end, self.fallback
)
return e
def __repr__(self):
return '<{}: {} start={} end={}>'.format(
self.__class__.__name__, self.etype.__name__, self.start, self.end
)
def __lt__(self, o):
return self.start < o.start
def look_for_image_or_link(text, delimiters, close, root_node, matches):
for i, d in list(enumerate(delimiters))[::-1]:
if d.content not in ('[', '!['):
continue
if not d.active:
break # break to remove the delimiter and return None
if not _is_legal_link_text(text[d.end:close]):
break
link_text = (d.end, close, text[d.end:close])
etype = 'Image' if d.content == '![' else 'Link'
match = (
_expect_inline_link(text, close + 1) or
_expect_reference_link(text, close + 1, link_text[2], root_node)
)
if not match: # not a link
break
rv = MatchObj(
etype, text, d.start, match[2], link_text, match[0], match[1]
)
process_emphasis(text, delimiters, i, matches)
if etype == 'Link':
for d in delimiters[:i]:
if d.content == '[':
d.active = False
del delimiters[i]
return rv
else:
# no matching opener is found
return None
del delimiters[i]
return None
def _is_legal_link_text(text):
return is_paired(text, '[', ']')
def _expect_inline_link(text, start):
"""(link_dest "link_title")"""
if start >= len(text) or text[start] != '(':
return None
i = start + 1
m = patterns.whitespace.match(text, i)
if m:
i = m.end()
m = patterns.link_dest_1.match(text, i)
if m:
link_dest = m.start(), m.end(), m.group()
i = m.end()
else:
open_num = 0
escaped = False
prev = i
while i < len(text):
c = text[i]
if escaped:
escaped = False
elif c == '\\':
escaped = True
elif c == '(':
open_num += 1
elif c in string.whitespace:
break
elif c == ')':
if open_num > 0:
open_num -= 1
else:
break
i += 1
if open_num != 0:
return None
link_dest = prev, i, text[prev:i]
link_title = i, i, None
tail_re = re.compile(r'(?:\s+%s)?\s*\)' % patterns.link_title, flags=re.UNICODE)
m = tail_re.match(text, i)
if not m:
return None
if m.group('title'):
link_title = m.start('title'), m.end('title'), m.group('title')
return (link_dest, link_title, m.end())
def _expect_reference_link(text, start, link_text, root_node):
match = patterns.optional_label.match(text, start)
link_label = link_text
if match and match.group()[1:-1]:
link_label = match.group()[1:-1]
result = _get_reference_link(link_label, root_node)
if not result:
return None
link_dest = start, start, result[0]
link_title = start, start, result[1]
return (link_dest, link_title, match and match.end() or start)
def _get_reference_link(link_label, root_node):
normalized_label = normalize_label(link_label)
return root_node.link_ref_defs.get(normalized_label, None)
def process_emphasis(text, delimiters, stack_bottom, matches):
star_bottom = underscore_bottom = stack_bottom
cur = _next_closer(delimiters, stack_bottom)
while cur is not None:
d_closer = delimiters[cur]
bottom = star_bottom if d_closer.content[0] == '*' else underscore_bottom
opener = _nearest_opener(delimiters, cur, bottom)
if opener is not None:
d_opener = delimiters[opener]
n = 2 if len(d_opener.content) >= 2 and len(d_closer.content) >= 2 else 1
match = MatchObj(
'StrongEmphasis' if n == 2 else 'Emphasis',
text,
d_opener.end - n,
d_closer.start + n,
(d_opener.end, d_closer.start, text[d_opener.end:d_closer.start])
)
matches.append(match)
del delimiters[opener + 1:cur]
cur -= cur - opener - 1
if d_opener.remove(n):
delimiters.remove(d_opener)
cur -= 1
if d_closer.remove(n, True):
delimiters.remove(d_closer)
cur = cur - 1 if cur > 0 else None
else:
bottom = cur - 1 if cur > 1 else None
if d_closer.content[0] == '*':
star_bottom = bottom
else:
underscore_bottom = bottom
if not d_closer.can_open:
delimiters.remove(d_closer)
cur = _next_closer(delimiters, cur)
lower = stack_bottom + 1 if stack_bottom is not None else 0
del delimiters[lower:]
def _next_closer(delimiters, bound):
i = bound + 1 if bound is not None else 0
while i < len(delimiters):
d = delimiters[i]
if hasattr(d, 'can_close') and d.can_close:
return i
i += 1
return None
def _nearest_opener(delimiters, higher, lower):
i = higher - 1
lower = lower if lower is not None else -1
while i > lower:
d = delimiters[i]
if hasattr(d, 'can_open') and d.can_open and d.closed_by(delimiters[higher]):
return i
i -= 1
return None
class Delimiter(object):
whitespace_re = re.compile(r'\s', flags=re.UNICODE)
def __init__(self, match, text):
self.start = match.start()
self.end = match.end()
self.content = match.group()
self.text = text
self.active = True
if self.content[0] in ('*', '_'):
self.can_open = self._can_open()
self.can_close = self._can_close()
def _can_open(self):
if self.content[0] == '*':
return self.is_left_flanking()
return self.is_left_flanking() and (
not self.is_right_flanking()
or self.preceded_by(string.punctuation)
)
def _can_close(self):
if self.content[0] == '*':
return self.is_right_flanking()
return self.is_right_flanking() and (
not self.is_left_flanking()
or self.followed_by(string.punctuation)
)
def is_left_flanking(self):
return (
self.end < len(self.text) and
self.whitespace_re.match(self.text, self.end) is None
) and (
not self.followed_by(string.punctuation)
or self.start == 0
or self.preceded_by(string.punctuation)
or self.whitespace_re.match(self.text, self.start - 1)
)
def is_right_flanking(self):
return (
self.start > 0 and
self.whitespace_re.match(self.text, self.start - 1) is None
) and (
not self.preceded_by(string.punctuation)
or self.end == len(self.text)
or self.followed_by(string.punctuation)
or self.whitespace_re.match(self.text, self.end)
)
def followed_by(self, target):
return self.end < len(self.text) and self.text[self.end] in target
def preceded_by(self, target):
return self.start > 0 and self.text[self.start - 1] in target
def closed_by(self, other):
return not (
self.content[0] != other.content[0]
or (self.can_open and self.can_close or other.can_open and other.can_close)
and len(self.content + other.content) % 3 == 0
)
def remove(self, n, left=False):
if len(self.content) <= n:
return True
if left:
self.start += n
else:
self.end -= n
self.content = self.content[n:]
return False
def __repr__(self):
return '<Delimiter {!r} start={} end={}>'.format(
self.content, self.start, self.end)
class MatchObj(object):
"""A fake match object that memes re.match methods"""
def __init__(self, etype, text, start, end, *groups):
self._text = text
self._start = start
self._end = end
self._groups = groups
self.etype = etype
def group(self, n=0):
if n == 0:
return self._text[self._start:self._end]
return self._groups[n - 1][2]
def start(self, n=0):
if n == 0:
return self._start
return self._groups[n - 1][0]
def end(self, n=0):
if n == 0:
return self._end
return self._groups[n - 1][1]
|
frostming/marko
|
marko/inline_parser.py
|
_expect_inline_link
|
python
|
def _expect_inline_link(text, start):
if start >= len(text) or text[start] != '(':
return None
i = start + 1
m = patterns.whitespace.match(text, i)
if m:
i = m.end()
m = patterns.link_dest_1.match(text, i)
if m:
link_dest = m.start(), m.end(), m.group()
i = m.end()
else:
open_num = 0
escaped = False
prev = i
while i < len(text):
c = text[i]
if escaped:
escaped = False
elif c == '\\':
escaped = True
elif c == '(':
open_num += 1
elif c in string.whitespace:
break
elif c == ')':
if open_num > 0:
open_num -= 1
else:
break
i += 1
if open_num != 0:
return None
link_dest = prev, i, text[prev:i]
link_title = i, i, None
tail_re = re.compile(r'(?:\s+%s)?\s*\)' % patterns.link_title, flags=re.UNICODE)
m = tail_re.match(text, i)
if not m:
return None
if m.group('title'):
link_title = m.start('title'), m.end('title'), m.group('title')
return (link_dest, link_title, m.end())
|
(link_dest "link_title")
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L205-L247
| null |
"""
Parse inline elements
"""
from __future__ import unicode_literals
import re
import string
from .helpers import is_paired, normalize_label
from . import patterns
def parse(text, elements, fallback):
"""Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param elements: the element types to be included in parsing
:param fallback: fallback class when no other element type is matched.
"""
# this is a raw list of elements that may contain overlaps.
tokens = []
for etype in elements:
for match in etype.find(text):
tokens.append(Token(etype, match, text, fallback))
tokens.sort()
tokens = _resolve_overlap(tokens)
return make_elements(tokens, text, fallback=fallback)
def _resolve_overlap(tokens):
if not tokens:
return tokens
result = []
prev = tokens[0]
for cur in tokens[1:]:
r = prev.relation(cur)
if r == Token.PRECEDE:
result.append(prev)
prev = cur
elif r == Token.CONTAIN:
prev.append_child(cur)
elif r == Token.INTERSECT and prev.etype.priority < cur.etype.priority:
prev = cur
result.append(prev)
return result
def make_elements(tokens, text, start=0, end=None, fallback=None):
"""Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Defaults to the start of text.
:param end: the offset of where parsing ends. Defauls to the end of text.
:param fallback: fallback element type.
:returns: a list of inline elements.
"""
result = []
end = end or len(text)
prev_end = start
for token in tokens:
if prev_end < token.start:
result.append(fallback(text[prev_end:token.start]))
result.append(token.as_element())
prev_end = token.end
if prev_end < end:
result.append(fallback(text[prev_end:end]))
return result
class Token(object):
"""An intermediate class to wrap the match object.
It can be converted to element by :meth:`as_element()`
"""
PRECEDE = 0
INTERSECT = 1
CONTAIN = 2
SHADE = 3
def __init__(self, etype, match, text, fallback):
self.etype = etype
self.match = match
self.start = match.start()
self.end = match.end()
self.inner_start = match.start(etype.parse_group)
self.inner_end = match.end(etype.parse_group)
self.text = text
self.fallback = fallback
self.children = []
def relation(self, other):
if self.end <= other.start:
return Token.PRECEDE
if self.end >= other.end:
if other.start >= self.inner_start and other.end <= self.inner_end:
return Token.CONTAIN
if self.inner_end <= other.start:
return Token.SHADE
return Token.INTERSECT
def append_child(self, child):
if not self.etype.parse_children:
return
self.children.append(child)
def as_element(self):
e = self.etype(self.match)
if e.parse_children:
self.children = _resolve_overlap(self.children)
e.children = make_elements(
self.children, self.text, self.inner_start,
self.inner_end, self.fallback
)
return e
def __repr__(self):
return '<{}: {} start={} end={}>'.format(
self.__class__.__name__, self.etype.__name__, self.start, self.end
)
def __lt__(self, o):
return self.start < o.start
def find_links_or_emphs(text, root_node):
"""Fink links/images or emphasis from text.
:param text: the original text.
:param root_node: a reference to the root node of the AST.
:returns: an iterable of match object.
"""
delimiters_re = re.compile(r'(?:!?\[|\*+|_+)')
i = 0
delimiters = []
escape = False
matches = []
code_pattern = re.compile(r'(?<!`)(`+)(?!`)([\s\S]+?)(?<!`)\1(?!`)')
while i < len(text):
if escape:
escape = False
i += 1
elif text[i] == '\\':
escape = True
i += 1
elif code_pattern.match(text, i):
i = code_pattern.match(text, i).end()
elif text[i] == ']':
node = look_for_image_or_link(text, delimiters, i, root_node, matches)
if node:
i = node.end()
matches.append(node)
else:
i += 1
else:
m = delimiters_re.match(text, i)
if m:
delimiters.append(Delimiter(m, text))
i = m.end()
else:
i += 1
process_emphasis(text, delimiters, None, matches)
return matches
def look_for_image_or_link(text, delimiters, close, root_node, matches):
for i, d in list(enumerate(delimiters))[::-1]:
if d.content not in ('[', '!['):
continue
if not d.active:
break # break to remove the delimiter and return None
if not _is_legal_link_text(text[d.end:close]):
break
link_text = (d.end, close, text[d.end:close])
etype = 'Image' if d.content == '![' else 'Link'
match = (
_expect_inline_link(text, close + 1) or
_expect_reference_link(text, close + 1, link_text[2], root_node)
)
if not match: # not a link
break
rv = MatchObj(
etype, text, d.start, match[2], link_text, match[0], match[1]
)
process_emphasis(text, delimiters, i, matches)
if etype == 'Link':
for d in delimiters[:i]:
if d.content == '[':
d.active = False
del delimiters[i]
return rv
else:
# no matching opener is found
return None
del delimiters[i]
return None
def _is_legal_link_text(text):
return is_paired(text, '[', ']')
def _expect_reference_link(text, start, link_text, root_node):
match = patterns.optional_label.match(text, start)
link_label = link_text
if match and match.group()[1:-1]:
link_label = match.group()[1:-1]
result = _get_reference_link(link_label, root_node)
if not result:
return None
link_dest = start, start, result[0]
link_title = start, start, result[1]
return (link_dest, link_title, match and match.end() or start)
def _get_reference_link(link_label, root_node):
normalized_label = normalize_label(link_label)
return root_node.link_ref_defs.get(normalized_label, None)
def process_emphasis(text, delimiters, stack_bottom, matches):
star_bottom = underscore_bottom = stack_bottom
cur = _next_closer(delimiters, stack_bottom)
while cur is not None:
d_closer = delimiters[cur]
bottom = star_bottom if d_closer.content[0] == '*' else underscore_bottom
opener = _nearest_opener(delimiters, cur, bottom)
if opener is not None:
d_opener = delimiters[opener]
n = 2 if len(d_opener.content) >= 2 and len(d_closer.content) >= 2 else 1
match = MatchObj(
'StrongEmphasis' if n == 2 else 'Emphasis',
text,
d_opener.end - n,
d_closer.start + n,
(d_opener.end, d_closer.start, text[d_opener.end:d_closer.start])
)
matches.append(match)
del delimiters[opener + 1:cur]
cur -= cur - opener - 1
if d_opener.remove(n):
delimiters.remove(d_opener)
cur -= 1
if d_closer.remove(n, True):
delimiters.remove(d_closer)
cur = cur - 1 if cur > 0 else None
else:
bottom = cur - 1 if cur > 1 else None
if d_closer.content[0] == '*':
star_bottom = bottom
else:
underscore_bottom = bottom
if not d_closer.can_open:
delimiters.remove(d_closer)
cur = _next_closer(delimiters, cur)
lower = stack_bottom + 1 if stack_bottom is not None else 0
del delimiters[lower:]
def _next_closer(delimiters, bound):
i = bound + 1 if bound is not None else 0
while i < len(delimiters):
d = delimiters[i]
if hasattr(d, 'can_close') and d.can_close:
return i
i += 1
return None
def _nearest_opener(delimiters, higher, lower):
i = higher - 1
lower = lower if lower is not None else -1
while i > lower:
d = delimiters[i]
if hasattr(d, 'can_open') and d.can_open and d.closed_by(delimiters[higher]):
return i
i -= 1
return None
class Delimiter(object):
whitespace_re = re.compile(r'\s', flags=re.UNICODE)
def __init__(self, match, text):
self.start = match.start()
self.end = match.end()
self.content = match.group()
self.text = text
self.active = True
if self.content[0] in ('*', '_'):
self.can_open = self._can_open()
self.can_close = self._can_close()
def _can_open(self):
if self.content[0] == '*':
return self.is_left_flanking()
return self.is_left_flanking() and (
not self.is_right_flanking()
or self.preceded_by(string.punctuation)
)
def _can_close(self):
if self.content[0] == '*':
return self.is_right_flanking()
return self.is_right_flanking() and (
not self.is_left_flanking()
or self.followed_by(string.punctuation)
)
def is_left_flanking(self):
return (
self.end < len(self.text) and
self.whitespace_re.match(self.text, self.end) is None
) and (
not self.followed_by(string.punctuation)
or self.start == 0
or self.preceded_by(string.punctuation)
or self.whitespace_re.match(self.text, self.start - 1)
)
def is_right_flanking(self):
return (
self.start > 0 and
self.whitespace_re.match(self.text, self.start - 1) is None
) and (
not self.preceded_by(string.punctuation)
or self.end == len(self.text)
or self.followed_by(string.punctuation)
or self.whitespace_re.match(self.text, self.end)
)
def followed_by(self, target):
return self.end < len(self.text) and self.text[self.end] in target
def preceded_by(self, target):
return self.start > 0 and self.text[self.start - 1] in target
def closed_by(self, other):
return not (
self.content[0] != other.content[0]
or (self.can_open and self.can_close or other.can_open and other.can_close)
and len(self.content + other.content) % 3 == 0
)
def remove(self, n, left=False):
if len(self.content) <= n:
return True
if left:
self.start += n
else:
self.end -= n
self.content = self.content[n:]
return False
def __repr__(self):
return '<Delimiter {!r} start={} end={}>'.format(
self.content, self.start, self.end)
class MatchObj(object):
"""A fake match object that memes re.match methods"""
def __init__(self, etype, text, start, end, *groups):
self._text = text
self._start = start
self._end = end
self._groups = groups
self.etype = etype
def group(self, n=0):
if n == 0:
return self._text[self._start:self._end]
return self._groups[n - 1][2]
def start(self, n=0):
if n == 0:
return self._start
return self._groups[n - 1][0]
def end(self, n=0):
if n == 0:
return self._end
return self._groups[n - 1][1]
|
frostming/marko
|
marko/parser.py
|
Parser.add_element
|
python
|
def add_element(self, element, override=False):
if issubclass(element, inline.InlineElement):
dest = self.inline_elements
elif issubclass(element, block.BlockElement):
dest = self.block_elements
else:
raise TypeError(
'The element should be a subclass of either `BlockElement` or '
'`InlineElement`.'
)
if not override:
dest[element.__name__] = element
else:
for cls in element.__bases__:
if cls in dest.values():
dest[cls.__name__] = element
break
else:
dest[element.__name__] = element
|
Add an element to the parser.
:param element: the element class.
:param override: whether to replace the default element based on.
.. note:: If one needs to call it inside ``__init__()``, please call it after
``super().__init__()`` is called.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L37-L63
| null |
class Parser(object):
"""
All elements defined in CommonMark's spec are included in the parser
by default. To add your custom elements, you can either:
1. pass the element classes as ``extras`` arguments to the constructor.
2. or subclass to your own parser and call :meth:`Parser.add_element`
inside the ``__init__`` body, especially when you want to override
the default element.
Attributes:
block_elements(dict): a dict of name: block_element pairs
inlin_elements(dict): a dict of name: inlin_element pairs
:param \*extras: extra elements to be included in parsing process.
"""
def __init__(self, *extras):
self.block_elements = {}
self.inline_elements = {}
# Create references in block and inline modules to avoid cyclic import.
for element in itertools.chain(
(getattr(block, name) for name in block.__all__),
(getattr(inline, name) for name in inline.__all__),
extras
):
self.add_element(element)
def parse(self, source_or_text):
"""Do the actual parsing and returns an AST or parsed element.
:param source_or_text: the text or source object.
Based on the type, it will do following:
- text: returns the parsed Document element.
- source: parse the source and returns the parsed children as a list.
"""
if isinstance(source_or_text, string_types):
block.parser = self
inline.parser = self
return self.block_elements['Document'](source_or_text)
element_list = self._build_block_element_list()
ast = []
while not source_or_text.exhausted:
for ele_type in element_list:
if ele_type.match(source_or_text):
result = ele_type.parse(source_or_text)
if not hasattr(result, 'priority'):
result = ele_type(result)
ast.append(result)
break
else:
# Quit the current parsing and go back to the last level.
break
return ast
def parse_inline(self, text):
"""Parses text into inline elements.
RawText is not considered in parsing but created as a wrapper of holes
that don't match any other elements.
:param text: the text to be parsed.
:returns: a list of inline elements.
"""
element_list = self._build_inline_element_list()
return inline_parser.parse(
text, element_list, fallback=self.inline_elements['RawText']
)
def _build_block_element_list(self):
"""Return a list of block elements, ordered from highest priority to lowest.
"""
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
)
def _build_inline_element_list(self):
"""Return a list of elements, each item is a list of elements
with the same priority.
"""
return [e for e in self.inline_elements.values() if not e.virtual]
|
frostming/marko
|
marko/parser.py
|
Parser.parse
|
python
|
def parse(self, source_or_text):
if isinstance(source_or_text, string_types):
block.parser = self
inline.parser = self
return self.block_elements['Document'](source_or_text)
element_list = self._build_block_element_list()
ast = []
while not source_or_text.exhausted:
for ele_type in element_list:
if ele_type.match(source_or_text):
result = ele_type.parse(source_or_text)
if not hasattr(result, 'priority'):
result = ele_type(result)
ast.append(result)
break
else:
# Quit the current parsing and go back to the last level.
break
return ast
|
Do the actual parsing and returns an AST or parsed element.
:param source_or_text: the text or source object.
Based on the type, it will do following:
- text: returns the parsed Document element.
- source: parse the source and returns the parsed children as a list.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L65-L90
|
[
"def _build_block_element_list(self):\n \"\"\"Return a list of block elements, ordered from highest priority to lowest.\n \"\"\"\n return sorted(\n [e for e in self.block_elements.values() if not e.virtual],\n key=lambda e: e.priority,\n reverse=True\n )\n"
] |
class Parser(object):
"""
All elements defined in CommonMark's spec are included in the parser
by default. To add your custom elements, you can either:
1. pass the element classes as ``extras`` arguments to the constructor.
2. or subclass to your own parser and call :meth:`Parser.add_element`
inside the ``__init__`` body, especially when you want to override
the default element.
Attributes:
block_elements(dict): a dict of name: block_element pairs
inlin_elements(dict): a dict of name: inlin_element pairs
:param \*extras: extra elements to be included in parsing process.
"""
def __init__(self, *extras):
self.block_elements = {}
self.inline_elements = {}
# Create references in block and inline modules to avoid cyclic import.
for element in itertools.chain(
(getattr(block, name) for name in block.__all__),
(getattr(inline, name) for name in inline.__all__),
extras
):
self.add_element(element)
def add_element(self, element, override=False):
"""Add an element to the parser.
:param element: the element class.
:param override: whether to replace the default element based on.
.. note:: If one needs to call it inside ``__init__()``, please call it after
``super().__init__()`` is called.
"""
if issubclass(element, inline.InlineElement):
dest = self.inline_elements
elif issubclass(element, block.BlockElement):
dest = self.block_elements
else:
raise TypeError(
'The element should be a subclass of either `BlockElement` or '
'`InlineElement`.'
)
if not override:
dest[element.__name__] = element
else:
for cls in element.__bases__:
if cls in dest.values():
dest[cls.__name__] = element
break
else:
dest[element.__name__] = element
def parse_inline(self, text):
"""Parses text into inline elements.
RawText is not considered in parsing but created as a wrapper of holes
that don't match any other elements.
:param text: the text to be parsed.
:returns: a list of inline elements.
"""
element_list = self._build_inline_element_list()
return inline_parser.parse(
text, element_list, fallback=self.inline_elements['RawText']
)
def _build_block_element_list(self):
"""Return a list of block elements, ordered from highest priority to lowest.
"""
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
)
def _build_inline_element_list(self):
"""Return a list of elements, each item is a list of elements
with the same priority.
"""
return [e for e in self.inline_elements.values() if not e.virtual]
|
frostming/marko
|
marko/parser.py
|
Parser.parse_inline
|
python
|
def parse_inline(self, text):
element_list = self._build_inline_element_list()
return inline_parser.parse(
text, element_list, fallback=self.inline_elements['RawText']
)
|
Parses text into inline elements.
RawText is not considered in parsing but created as a wrapper of holes
that don't match any other elements.
:param text: the text to be parsed.
:returns: a list of inline elements.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L92-L103
|
[
"def parse(text, elements, fallback):\n \"\"\"Parse given text and produce a list of inline elements.\n\n :param text: the text to be parsed.\n :param elements: the element types to be included in parsing\n :param fallback: fallback class when no other element type is matched.\n \"\"\"\n # this is a raw list of elements that may contain overlaps.\n tokens = []\n for etype in elements:\n for match in etype.find(text):\n tokens.append(Token(etype, match, text, fallback))\n tokens.sort()\n tokens = _resolve_overlap(tokens)\n return make_elements(tokens, text, fallback=fallback)\n",
"def _build_inline_element_list(self):\n \"\"\"Return a list of elements, each item is a list of elements\n with the same priority.\n \"\"\"\n return [e for e in self.inline_elements.values() if not e.virtual]\n"
] |
class Parser(object):
"""
All elements defined in CommonMark's spec are included in the parser
by default. To add your custom elements, you can either:
1. pass the element classes as ``extras`` arguments to the constructor.
2. or subclass to your own parser and call :meth:`Parser.add_element`
inside the ``__init__`` body, especially when you want to override
the default element.
Attributes:
block_elements(dict): a dict of name: block_element pairs
inlin_elements(dict): a dict of name: inlin_element pairs
:param \*extras: extra elements to be included in parsing process.
"""
def __init__(self, *extras):
self.block_elements = {}
self.inline_elements = {}
# Create references in block and inline modules to avoid cyclic import.
for element in itertools.chain(
(getattr(block, name) for name in block.__all__),
(getattr(inline, name) for name in inline.__all__),
extras
):
self.add_element(element)
def add_element(self, element, override=False):
"""Add an element to the parser.
:param element: the element class.
:param override: whether to replace the default element based on.
.. note:: If one needs to call it inside ``__init__()``, please call it after
``super().__init__()`` is called.
"""
if issubclass(element, inline.InlineElement):
dest = self.inline_elements
elif issubclass(element, block.BlockElement):
dest = self.block_elements
else:
raise TypeError(
'The element should be a subclass of either `BlockElement` or '
'`InlineElement`.'
)
if not override:
dest[element.__name__] = element
else:
for cls in element.__bases__:
if cls in dest.values():
dest[cls.__name__] = element
break
else:
dest[element.__name__] = element
def parse(self, source_or_text):
"""Do the actual parsing and returns an AST or parsed element.
:param source_or_text: the text or source object.
Based on the type, it will do following:
- text: returns the parsed Document element.
- source: parse the source and returns the parsed children as a list.
"""
if isinstance(source_or_text, string_types):
block.parser = self
inline.parser = self
return self.block_elements['Document'](source_or_text)
element_list = self._build_block_element_list()
ast = []
while not source_or_text.exhausted:
for ele_type in element_list:
if ele_type.match(source_or_text):
result = ele_type.parse(source_or_text)
if not hasattr(result, 'priority'):
result = ele_type(result)
ast.append(result)
break
else:
# Quit the current parsing and go back to the last level.
break
return ast
def _build_block_element_list(self):
"""Return a list of block elements, ordered from highest priority to lowest.
"""
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
)
def _build_inline_element_list(self):
"""Return a list of elements, each item is a list of elements
with the same priority.
"""
return [e for e in self.inline_elements.values() if not e.virtual]
|
frostming/marko
|
marko/parser.py
|
Parser._build_block_element_list
|
python
|
def _build_block_element_list(self):
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
)
|
Return a list of block elements, ordered from highest priority to lowest.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L105-L112
| null |
class Parser(object):
"""
All elements defined in CommonMark's spec are included in the parser
by default. To add your custom elements, you can either:
1. pass the element classes as ``extras`` arguments to the constructor.
2. or subclass to your own parser and call :meth:`Parser.add_element`
inside the ``__init__`` body, especially when you want to override
the default element.
Attributes:
block_elements(dict): a dict of name: block_element pairs
inlin_elements(dict): a dict of name: inlin_element pairs
:param \*extras: extra elements to be included in parsing process.
"""
def __init__(self, *extras):
self.block_elements = {}
self.inline_elements = {}
# Create references in block and inline modules to avoid cyclic import.
for element in itertools.chain(
(getattr(block, name) for name in block.__all__),
(getattr(inline, name) for name in inline.__all__),
extras
):
self.add_element(element)
def add_element(self, element, override=False):
"""Add an element to the parser.
:param element: the element class.
:param override: whether to replace the default element based on.
.. note:: If one needs to call it inside ``__init__()``, please call it after
``super().__init__()`` is called.
"""
if issubclass(element, inline.InlineElement):
dest = self.inline_elements
elif issubclass(element, block.BlockElement):
dest = self.block_elements
else:
raise TypeError(
'The element should be a subclass of either `BlockElement` or '
'`InlineElement`.'
)
if not override:
dest[element.__name__] = element
else:
for cls in element.__bases__:
if cls in dest.values():
dest[cls.__name__] = element
break
else:
dest[element.__name__] = element
def parse(self, source_or_text):
"""Do the actual parsing and returns an AST or parsed element.
:param source_or_text: the text or source object.
Based on the type, it will do following:
- text: returns the parsed Document element.
- source: parse the source and returns the parsed children as a list.
"""
if isinstance(source_or_text, string_types):
block.parser = self
inline.parser = self
return self.block_elements['Document'](source_or_text)
element_list = self._build_block_element_list()
ast = []
while not source_or_text.exhausted:
for ele_type in element_list:
if ele_type.match(source_or_text):
result = ele_type.parse(source_or_text)
if not hasattr(result, 'priority'):
result = ele_type(result)
ast.append(result)
break
else:
# Quit the current parsing and go back to the last level.
break
return ast
def parse_inline(self, text):
"""Parses text into inline elements.
RawText is not considered in parsing but created as a wrapper of holes
that don't match any other elements.
:param text: the text to be parsed.
:returns: a list of inline elements.
"""
element_list = self._build_inline_element_list()
return inline_parser.parse(
text, element_list, fallback=self.inline_elements['RawText']
)
def _build_inline_element_list(self):
"""Return a list of elements, each item is a list of elements
with the same priority.
"""
return [e for e in self.inline_elements.values() if not e.virtual]
|
frostming/marko
|
marko/block.py
|
BlockElement.parse_inline
|
python
|
def parse_inline(self):
if self.inline_children:
self.children = parser.parse_inline(self.children)
elif isinstance(getattr(self, 'children', None), list):
for child in self.children:
if isinstance(child, BlockElement):
child.parse_inline()
|
Inline parsing is postponed so that all link references
are seen before that.
|
train
|
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/block.py#L59-L68
| null |
class BlockElement(object):
"""Any block element should inherit this class"""
#: Use to denote the precedence in parsing
priority = 5
#: if True, it won't be included in parsing process but produced by other elements
#: other elements instead.
virtual = False
#: Whether children are parsed as inline elements.
inline_children = False
@classmethod
def match(self, source):
"""Test if the source matches the element at current position.
The source should not be consumed in the method unless you have to.
:param source: the ``Source`` object of the content to be parsed
"""
raise NotImplementedError()
@classmethod
def parse(self, source):
"""Parses the source. This is a proper place to consume the source body and
return an element or information to build one. The information tuple will be
passed to ``__init__`` method afterwards. Inline parsing, if any, should also
be performed here.
:param source: the ``Source`` object of the content to be parsed
"""
raise NotImplementedError()
def __lt__(self, o):
return self.priority < o.priority
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/commands.py
|
await_transform_exists
|
python
|
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
|
Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L29-L49
| null |
from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or not.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for all transforms specified in transform_paths to exist or not based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def fetch_transform_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['x'],
response['payload']['y']
]
def fetch_transform_normalized_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['normalized_x'],
response['payload']['normalized_y']
]
def query_renderer_visible(cli, transform_path):
"""
Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def query_scene_loaded(cli, scene_name):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool
"""
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def assign_component_value(cli, transform_path, component_type, name, value):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String | Number | Boolean)
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/commands.py
|
await_any_transforms_exist
|
python
|
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
|
Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L52-L72
| null |
from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or not.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for all transforms specified in transform_paths to exist or not based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def fetch_transform_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['x'],
response['payload']['y']
]
def fetch_transform_normalized_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['normalized_x'],
response['payload']['normalized_y']
]
def query_renderer_visible(cli, transform_path):
"""
Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def query_scene_loaded(cli, scene_name):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool
"""
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def assign_component_value(cli, transform_path, component_type, name, value):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String | Number | Boolean)
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/commands.py
|
fetch_transform_screen_position
|
python
|
def fetch_transform_screen_position(cli, transform_path):
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['x'],
response['payload']['y']
]
|
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L98-L118
| null |
from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or not.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for all transforms specified in transform_paths to exist or not based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def fetch_transform_normalized_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['normalized_x'],
response['payload']['normalized_y']
]
def query_renderer_visible(cli, transform_path):
"""
Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def query_scene_loaded(cli, scene_name):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool
"""
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def assign_component_value(cli, transform_path, component_type, name, value):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String | Number | Boolean)
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/commands.py
|
query_renderer_visible
|
python
|
def query_renderer_visible(cli, transform_path):
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
|
Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L144-L160
| null |
from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or not.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for all transforms specified in transform_paths to exist or not based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def fetch_transform_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['x'],
response['payload']['y']
]
def fetch_transform_normalized_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['normalized_x'],
response['payload']['normalized_y']
]
def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def query_scene_loaded(cli, scene_name):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool
"""
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def assign_component_value(cli, transform_path, component_type, name, value):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String | Number | Boolean)
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/commands.py
|
await_renderer_visible
|
python
|
def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
|
Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L163-L182
| null |
from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or not.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for all transforms specified in transform_paths to exist or not based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def fetch_transform_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['x'],
response['payload']['y']
]
def fetch_transform_normalized_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['normalized_x'],
response['payload']['normalized_y']
]
def query_renderer_visible(cli, transform_path):
"""
Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def query_scene_loaded(cli, scene_name):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool
"""
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def assign_component_value(cli, transform_path, component_type, name, value):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String | Number | Boolean)
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/commands.py
|
query_scene_loaded
|
python
|
def query_scene_loaded(cli, scene_name):
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
|
Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L185-L201
| null |
from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or not.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for all transforms specified in transform_paths to exist or not based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def fetch_transform_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['x'],
response['payload']['y']
]
def fetch_transform_normalized_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['normalized_x'],
response['payload']['normalized_y']
]
def query_renderer_visible(cli, transform_path):
"""
Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def assign_component_value(cli, transform_path, component_type, name, value):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String | Number | Boolean)
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/commands.py
|
await_scene_loaded
|
python
|
def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
|
Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L204-L223
| null |
from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or not.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for all transforms specified in transform_paths to exist or not based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def fetch_transform_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['x'],
response['payload']['y']
]
def fetch_transform_normalized_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['normalized_x'],
response['payload']['normalized_y']
]
def query_renderer_visible(cli, transform_path):
"""
Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def query_scene_loaded(cli, scene_name):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool
"""
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def assign_component_value(cli, transform_path, component_type, name, value):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String | Number | Boolean)
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/commands.py
|
assign_component_value
|
python
|
def assign_component_value(cli, transform_path, component_type, name, value):
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
|
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String | Number | Boolean)
:return: bool
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L226-L247
| null |
from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or not.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for all transforms specified in transform_paths to exist or not based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Message("await.unity.transform.exists", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def fetch_transform_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['x'],
response['payload']['y']
]
def fetch_transform_normalized_screen_position(cli, transform_path):
"""
Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y]
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
response['payload']['normalized_x'],
response['payload']['normalized_y']
]
def query_renderer_visible(cli, transform_path):
"""
Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool
"""
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
def query_scene_loaded(cli, scene_name):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool
"""
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result'])
def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool
"""
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['success'])
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/assertions.py
|
assert_transform_exists
|
python
|
def assert_transform_exists(cli, transform_path):
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result
|
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L9-L18
|
[
"def query_transform_exists(cli, transform_path):\n \"\"\"\n Requests status on whether a transform exists or not.\n :param cli:\n :param transform_path:\n :return: bool\n \"\"\"\n\n message_payload = {\n \"transform_path\": transform_path\n }\n msg = message.Message(\"query.unity.transform.exists\", message_payload)\n cli.send_message(msg)\n\n response = cli.read_message()\n verify_response(response)\n return bool(response['payload']['result'])\n"
] |
import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_scene_loaded(cli, scene_name):
"""
Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return:
"""
result = commands.query_scene_loaded(cli, scene_name)
assert result is True
return result
def assert_await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the transform to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_transform_exists(cli, transform_path, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for any transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_any_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for all transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_all_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the renderer to be visible based on is_visible. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param is_visible: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_renderer_visible(cli, transform_path, is_visible, timeout_seconds)
assert result is True
return result
def assert_await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the scene to be loaded based on is_loaded. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param scene_name:
:param is_loaded: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_scene_loaded(cli, scene_name, is_loaded, timeout_seconds)
assert result is True
return result
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/assertions.py
|
assert_scene_loaded
|
python
|
def assert_scene_loaded(cli, scene_name):
result = commands.query_scene_loaded(cli, scene_name)
assert result is True
return result
|
Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L21-L30
|
[
"def query_scene_loaded(cli, scene_name):\n \"\"\"\n Requests status on whether a scene is loaded or not.\n :param cli:\n :param scene_name:\n :return: bool\n \"\"\"\n\n message_payload = {\n \"scene_name\": scene_name\n }\n msg = message.Message(\"query.unity.scene.loaded\", message_payload)\n cli.send_message(msg)\n\n response = cli.read_message()\n verify_response(response)\n return bool(response['payload']['result'])\n"
] |
import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
"""
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result
def assert_await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the transform to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_transform_exists(cli, transform_path, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for any transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_any_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for all transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_all_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the renderer to be visible based on is_visible. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param is_visible: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_renderer_visible(cli, transform_path, is_visible, timeout_seconds)
assert result is True
return result
def assert_await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the scene to be loaded based on is_loaded. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param scene_name:
:param is_loaded: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_scene_loaded(cli, scene_name, is_loaded, timeout_seconds)
assert result is True
return result
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/assertions.py
|
assert_await_transform_exists
|
python
|
def assert_await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_transform_exists(cli, transform_path, does_exist, timeout_seconds)
assert result is True
return result
|
Asserts that we successfully awaited for the transform to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L33-L45
|
[
"def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for a single transform to exist based on does_exist.\n :param cli:\n :param transform_path:\n :param does_exist: Whether or not to await for exist state (True | False)\n :param timeout_seconds: How long until this returns with failure\n :return: bool\n \"\"\"\n message_payload = {\n \"transform_paths\": [transform_path],\n \"do_exist\": does_exist,\n \"match_mode\": \"All\",\n \"timeout\": timeout_seconds\n }\n msg = message.Message(\"await.unity.transform.exists\", message_payload)\n cli.send_message(msg)\n\n response = cli.read_message()\n verify_response(response)\n return bool(response['payload']['success'])\n"
] |
import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
"""
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result
def assert_scene_loaded(cli, scene_name):
"""
Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return:
"""
result = commands.query_scene_loaded(cli, scene_name)
assert result is True
return result
def assert_await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for any transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_any_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for all transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_all_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the renderer to be visible based on is_visible. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param is_visible: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_renderer_visible(cli, transform_path, is_visible, timeout_seconds)
assert result is True
return result
def assert_await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the scene to be loaded based on is_loaded. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param scene_name:
:param is_loaded: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_scene_loaded(cli, scene_name, is_loaded, timeout_seconds)
assert result is True
return result
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/assertions.py
|
assert_await_any_transforms_exist
|
python
|
def assert_await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_any_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
|
Asserts that we successfully awaited for any transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L48-L60
|
[
"def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for a transform to exist based on does_exist.\n :param cli:\n :param transform_paths: An array of transform paths [...]\n :param does_exist: Whether or not to await for exist state (True | False)\n :param timeout_seconds: How long until this returns with failure\n :return: bool\n \"\"\"\n message_payload = {\n \"transform_paths\": transform_paths,\n \"do_exist\": does_exist,\n \"match_mode\": \"Any\",\n \"timeout\": timeout_seconds\n }\n msg = message.Message(\"await.unity.transform.exists\", message_payload)\n cli.send_message(msg)\n\n response = cli.read_message()\n verify_response(response)\n return bool(response['payload']['success'])\n"
] |
import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
"""
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result
def assert_scene_loaded(cli, scene_name):
"""
Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return:
"""
result = commands.query_scene_loaded(cli, scene_name)
assert result is True
return result
def assert_await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the transform to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_transform_exists(cli, transform_path, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for all transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_all_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the renderer to be visible based on is_visible. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param is_visible: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_renderer_visible(cli, transform_path, is_visible, timeout_seconds)
assert result is True
return result
def assert_await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the scene to be loaded based on is_loaded. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param scene_name:
:param is_loaded: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_scene_loaded(cli, scene_name, is_loaded, timeout_seconds)
assert result is True
return result
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/assertions.py
|
assert_await_all_transforms_exist
|
python
|
def assert_await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_all_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
|
Asserts that we successfully awaited for all transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L63-L75
|
[
"def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for all transforms specified in transform_paths to exist or not based on does_exist.\n :param cli:\n :param transform_paths: An array of transform paths [...]\n :param does_exist: Whether or not to await for exist state (True | False)\n :param timeout_seconds: How long until this returns with failure\n :return: bool\n \"\"\"\n message_payload = {\n \"transform_paths\": transform_paths,\n \"do_exist\": does_exist,\n \"match_mode\": \"All\",\n \"timeout\": timeout_seconds\n }\n msg = message.Message(\"await.unity.transform.exists\", message_payload)\n cli.send_message(msg)\n\n response = cli.read_message()\n verify_response(response)\n return bool(response['payload']['success'])\n"
] |
import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
"""
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result
def assert_scene_loaded(cli, scene_name):
"""
Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return:
"""
result = commands.query_scene_loaded(cli, scene_name)
assert result is True
return result
def assert_await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the transform to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_transform_exists(cli, transform_path, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for any transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_any_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the renderer to be visible based on is_visible. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param is_visible: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_renderer_visible(cli, transform_path, is_visible, timeout_seconds)
assert result is True
return result
def assert_await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the scene to be loaded based on is_loaded. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param scene_name:
:param is_loaded: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_scene_loaded(cli, scene_name, is_loaded, timeout_seconds)
assert result is True
return result
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/assertions.py
|
assert_await_renderer_visible
|
python
|
def assert_await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_renderer_visible(cli, transform_path, is_visible, timeout_seconds)
assert result is True
return result
|
Asserts that we successfully awaited for the renderer to be visible based on is_visible. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param is_visible: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L78-L90
|
[
"def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for a transform renderer to become visible based on is_visible.\n :param cli:\n :param transform_path:\n :param is_visible: Whether or not to await for visible state (True | False)\n :param timeout_seconds: How long until this returns with failure\n :return: bool\n \"\"\"\n message_payload = {\n \"transform_path\": transform_path,\n \"is_visible\": is_visible,\n \"timeout\": timeout_seconds\n }\n msg = message.Message(\"await.unity.renderer.visible\", message_payload)\n cli.send_message(msg)\n\n response = cli.read_message()\n verify_response(response)\n return bool(response['payload']['success'])\n"
] |
import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
"""
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result
def assert_scene_loaded(cli, scene_name):
"""
Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return:
"""
result = commands.query_scene_loaded(cli, scene_name)
assert result is True
return result
def assert_await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the transform to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_transform_exists(cli, transform_path, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for any transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_any_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for all transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_all_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the scene to be loaded based on is_loaded. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param scene_name:
:param is_loaded: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_scene_loaded(cli, scene_name, is_loaded, timeout_seconds)
assert result is True
return result
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/assertions.py
|
assert_await_scene_loaded
|
python
|
def assert_await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_scene_loaded(cli, scene_name, is_loaded, timeout_seconds)
assert result is True
return result
|
Asserts that we successfully awaited for the scene to be loaded based on is_loaded. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param scene_name:
:param is_loaded: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L93-L105
|
[
"def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for a scene to be loaded based on is_loaded.\n :param cli:\n :param scene_name:\n :param is_loaded: Whether or not to await for loaded state (True | False)\n :param timeout_seconds: How long until this returns with failure\n :return: bool\n \"\"\"\n message_payload = {\n \"scene_name\": scene_name,\n \"is_loaded\": is_loaded,\n \"timeout\": timeout_seconds\n }\n msg = message.Message(\"await.unity.scene.loaded\", message_payload)\n cli.send_message(msg)\n\n response = cli.read_message()\n verify_response(response)\n return bool(response['payload']['success'])\n"
] |
import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
"""
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result
def assert_scene_loaded(cli, scene_name):
"""
Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return:
"""
result = commands.query_scene_loaded(cli, scene_name)
assert result is True
return result
def assert_await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the transform to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_transform_exists(cli, transform_path, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for any transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_any_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for all transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_all_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result
def assert_await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
"""
Asserts that we successfully awaited for the renderer to be visible based on is_visible. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param is_visible: (True | False) the state change we are waiting for.
:param timeout_seconds: The amount of time to wait for a change before fail.
:return:
"""
result = commands.await_renderer_visible(cli, transform_path, is_visible, timeout_seconds)
assert result is True
return result
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/transform.py
|
TransformRef.add_child_ref
|
python
|
def add_child_ref(self, transform_ref):
if not isinstance(transform_ref, TransformRef):
raise ValueError("transform_ref must be of type TransformRef")
for child in self.children:
if child is transform_ref:
return
transform_ref.parent = self
self.children.append(transform_ref)
|
Adds the TransformRef if it is not already added.
:param transform_ref:
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L11-L25
| null |
class TransformRef:
id = None
transform_path = None
children = []
parent = None
def __init__(self, transform_path):
self.id = id
self.transform_path = transform_path
def create_child_ref(self, transform_path, child_id=None):
"""
Creates a new child TransformRef with transform_path specified.
:param transform_path:
:param child_id:
:return: TransformRef child
"""
transform_ref = TransformRef(transform_path, child_id)
self.add_child_ref(transform_ref)
return transform_ref
def get_rendered_transform_path(self):
"""
Generates a rendered transform path
that is calculated from all parents.
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not None:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
def get_rendered_transform_path_relative(self, relative_transform_ref):
"""
Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not None and parent is not relative_transform_ref:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/transform.py
|
TransformRef.create_child_ref
|
python
|
def create_child_ref(self, transform_path, child_id=None):
transform_ref = TransformRef(transform_path, child_id)
self.add_child_ref(transform_ref)
return transform_ref
|
Creates a new child TransformRef with transform_path specified.
:param transform_path:
:param child_id:
:return: TransformRef child
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L27-L36
|
[
"def add_child_ref(self, transform_ref):\n \"\"\"\n Adds the TransformRef if it is not already added.\n :param transform_ref:\n :return:\n \"\"\"\n if not isinstance(transform_ref, TransformRef):\n raise ValueError(\"transform_ref must be of type TransformRef\")\n\n for child in self.children:\n if child is transform_ref:\n return\n\n transform_ref.parent = self\n self.children.append(transform_ref)\n"
] |
class TransformRef:
id = None
transform_path = None
children = []
parent = None
def __init__(self, transform_path):
self.id = id
self.transform_path = transform_path
def add_child_ref(self, transform_ref):
"""
Adds the TransformRef if it is not already added.
:param transform_ref:
:return:
"""
if not isinstance(transform_ref, TransformRef):
raise ValueError("transform_ref must be of type TransformRef")
for child in self.children:
if child is transform_ref:
return
transform_ref.parent = self
self.children.append(transform_ref)
def get_rendered_transform_path(self):
"""
Generates a rendered transform path
that is calculated from all parents.
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not None:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
def get_rendered_transform_path_relative(self, relative_transform_ref):
"""
Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not None and parent is not relative_transform_ref:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/transform.py
|
TransformRef.get_rendered_transform_path
|
python
|
def get_rendered_transform_path(self):
path = self.transform_path
parent = self.parent
while parent is not None:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
|
Generates a rendered transform path
that is calculated from all parents.
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L38-L51
| null |
class TransformRef:
id = None
transform_path = None
children = []
parent = None
def __init__(self, transform_path):
self.id = id
self.transform_path = transform_path
def add_child_ref(self, transform_ref):
"""
Adds the TransformRef if it is not already added.
:param transform_ref:
:return:
"""
if not isinstance(transform_ref, TransformRef):
raise ValueError("transform_ref must be of type TransformRef")
for child in self.children:
if child is transform_ref:
return
transform_ref.parent = self
self.children.append(transform_ref)
def create_child_ref(self, transform_path, child_id=None):
"""
Creates a new child TransformRef with transform_path specified.
:param transform_path:
:param child_id:
:return: TransformRef child
"""
transform_ref = TransformRef(transform_path, child_id)
self.add_child_ref(transform_ref)
return transform_ref
def get_rendered_transform_path_relative(self, relative_transform_ref):
"""
Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not None and parent is not relative_transform_ref:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
|
AgeOfLearning/coeus-unity-python-framework
|
coeus_unity/transform.py
|
TransformRef.get_rendered_transform_path_relative
|
python
|
def get_rendered_transform_path_relative(self, relative_transform_ref):
path = self.transform_path
parent = self.parent
while parent is not None and parent is not relative_transform_ref:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
|
Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return:
|
train
|
https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L53-L67
| null |
class TransformRef:
id = None
transform_path = None
children = []
parent = None
def __init__(self, transform_path):
self.id = id
self.transform_path = transform_path
def add_child_ref(self, transform_ref):
"""
Adds the TransformRef if it is not already added.
:param transform_ref:
:return:
"""
if not isinstance(transform_ref, TransformRef):
raise ValueError("transform_ref must be of type TransformRef")
for child in self.children:
if child is transform_ref:
return
transform_ref.parent = self
self.children.append(transform_ref)
def create_child_ref(self, transform_path, child_id=None):
"""
Creates a new child TransformRef with transform_path specified.
:param transform_path:
:param child_id:
:return: TransformRef child
"""
transform_ref = TransformRef(transform_path, child_id)
self.add_child_ref(transform_ref)
return transform_ref
def get_rendered_transform_path(self):
"""
Generates a rendered transform path
that is calculated from all parents.
:return:
"""
path = self.transform_path
parent = self.parent
while parent is not None:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
|
clement-alexandre/TotemBionet
|
totembionet/src/model_picker/model_picker.py
|
pick_a_model_randomly
|
python
|
def pick_a_model_randomly(models: List[Any]) -> Any:
try:
return random.choice(models)
except IndexError as e:
raise ModelPickerException(cause=e)
|
Naive picking function, return one of the models chosen randomly.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/model_picker/model_picker.py#L16-L21
| null |
# coding: utf-8
import random
from typing import Any, List
class ModelPickerException(Exception):
def __init__(self, message=None, cause=None):
self.message = message
self.cause = cause
def __str__(self):
return self.message or str(self.cause)
|
clement-alexandre/TotemBionet
|
totembionet/src/resource_table/resource_table_with_model.py
|
ResourceTableWithModel.as_data_frame
|
python
|
def as_data_frame(self) -> pandas.DataFrame:
header_gene = {}
header_multiplex = {}
headr_transitions = {}
for gene in self.influence_graph.genes:
header_gene[gene] = repr(gene)
header_multiplex[gene] = f"active multiplex on {gene!r}"
headr_transitions[gene] = f"K_{gene!r}"
columns = defaultdict(list)
for state in self.table.keys():
for gene in self.influence_graph.genes:
columns[header_gene[gene]].append(state[gene])
columns[header_multiplex[gene]].append(self._repr_multiplexes(gene, state))
columns[headr_transitions[gene]].append(self._repr_transition(gene, state))
header = list(header_gene.values()) + list(header_multiplex.values()) + list(headr_transitions.values())
return pandas.DataFrame(columns, columns=header)
|
Create a panda DataFrame representation of the resource table.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/resource_table/resource_table_with_model.py#L25-L43
|
[
"def _repr_multiplexes(self, gene: Gene, state: State) -> str:\n active_multiplexes = self.active_multiplexes_for_gene(gene, state)\n return f'{{{\", \".join(map(repr, active_multiplexes))}}}'\n",
"def _repr_transition(self, gene: Gene, state: State) -> str:\n transition = self.transition_table[gene, state]\n return f'{\" \".join(map(str, transition.states))}'\n"
] |
class ResourceTableWithModel(ResourceTable):
def __init__(self, model: DiscreteModel):
super().__init__(model.influence_graph)
self.model = model
self.transition_table: Dict[Tuple[Gene, State], Transition] = self._build_transition_table()
def _build_transition_table(self) -> Dict[Tuple[Gene, State], Transition]:
result = {}
for state, multiplexes in self.table.items():
for gene in self.model.genes:
result[gene, state] = self.model.find_transition(gene, multiplexes)
return result
def as_data_frame(self) -> pandas.DataFrame:
""" Create a panda DataFrame representation of the resource table. """
header_gene = {}
header_multiplex = {}
headr_transitions = {}
for gene in self.influence_graph.genes:
header_gene[gene] = repr(gene)
header_multiplex[gene] = f"active multiplex on {gene!r}"
headr_transitions[gene] = f"K_{gene!r}"
columns = defaultdict(list)
for state in self.table.keys():
for gene in self.influence_graph.genes:
columns[header_gene[gene]].append(state[gene])
columns[header_multiplex[gene]].append(self._repr_multiplexes(gene, state))
columns[headr_transitions[gene]].append(self._repr_transition(gene, state))
header = list(header_gene.values()) + list(header_multiplex.values()) + list(headr_transitions.values())
return pandas.DataFrame(columns, columns=header)
def _repr_transition(self, gene: Gene, state: State) -> str:
transition = self.transition_table[gene, state]
return f'{" ".join(map(str, transition.states))}'
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/multiplex.py
|
Multiplex.is_active
|
python
|
def is_active(self, state: 'State') -> bool:
# Remove the genes which does not contribute to the multiplex
sub_state = state.sub_state_by_gene_name(*self.expression.variables)
# If this state is not in the cache
if sub_state not in self._is_active:
params = self._transform_state_to_dict(sub_state)
# We add the result of the expression for this state of the multiplex to the cache
self._is_active[sub_state] = self.expression.evaluate(**params)
return self._is_active[sub_state]
|
Return True if the multiplex is active in the given state, false otherwise.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/multiplex.py#L21-L30
|
[
"def _transform_state_to_dict(self, state: 'State') -> Dict[str, int]:\n return {gene.name: state for gene, state in state.items()\n if gene.name in self.expression.expression}\n"
] |
class Multiplex:
def __init__(self, name: str, genes: Tuple[Gene], expression: Expression):
self.name: str = name
self.genes: Tuple[Gene] = genes
self.expression = expression
for gene in genes:
gene.add_multiplex(self)
# a cache table to store the already evaluated states with their results.
self._is_active: Dict[State, bool] = {}
def _transform_state_to_dict(self, state: 'State') -> Dict[str, int]:
return {gene.name: state for gene, state in state.items()
if gene.name in self.expression.expression}
def __str__(self) -> str:
return f'{self.name} : {self.expression} → {" ".join(map(repr, self.genes))}'
def __repr__(self) -> str:
return self.name
def __eq__(self, other) -> bool:
if not isinstance(other, Multiplex):
return False
return (self.name == other.name
and self.expression == other.expression
and set(self.genes) == set(other.genes))
def __hash__(self) -> int:
return hash((self.name, frozenset(self.genes), self.expression))
|
clement-alexandre/TotemBionet
|
totembionet/src/ggea/ggea.py
|
Graph._build_graph
|
python
|
def _build_graph(self) -> nx.DiGraph:
digraph = nx.DiGraph()
for state in self.model.all_states():
self._number_of_states += 1
for next_state in self.model.available_state(state):
self._number_of_transitions += 1
digraph.add_edge(
self._transform_state_to_string(state),
self._transform_state_to_string(next_state)
)
return digraph
|
Private method to build the graph from the model.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L22-L33
|
[
"def _transform_state_to_string(self, state: State) -> str:\n \"\"\"\n Private method which transform a state to a string.\n\n Examples\n --------\n\n The model contains 2 genes: operon = {0, 1, 2}\n mucuB = {0, 1}\n\n >>> graph._transform_state_to_string({operon: 1, mucuB: 0})\n \"10\"\n >>> graph._transform_state_to_string({operon: 2, mucuB: 1})\n \"21\"\n\n \"\"\"\n return ''.join(str(state[gene]) for gene in self.model.genes)\n"
] |
class Graph:
"""
The state graph for particular model.
"""
def __init__(self, model: DiscreteModel):
self.model = model
self._number_of_states = 0
self._number_of_transitions = 0
self._graph: nx.DiGraph = self._build_graph()
def _transform_state_to_string(self, state: State) -> str:
"""
Private method which transform a state to a string.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_state_to_string({operon: 1, mucuB: 0})
"10"
>>> graph._transform_state_to_string({operon: 2, mucuB: 1})
"21"
"""
return ''.join(str(state[gene]) for gene in self.model.genes)
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def show(self, engine: str = "dot") -> 'GraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return GraphDisplayer(self, engine)
def as_dot(self) -> str:
""" Return as a string the dot version of the graph. """
return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()
def export_to_dot(self, filename: str = 'output') -> None:
""" Export the graph to the dot file "filename.dot". """
with open(filename + '.dot', 'w') as output:
output.write(self.as_dot())
def number_of_states(self) -> int:
""" Return the numbers of states in the graph """
return self._number_of_states
def number_of_transitions(self) -> int:
""" Return the numbers of transitions in the graph """
return self._number_of_transitions
|
clement-alexandre/TotemBionet
|
totembionet/src/ggea/ggea.py
|
Graph._transform_state_to_string
|
python
|
def _transform_state_to_string(self, state: State) -> str:
return ''.join(str(state[gene]) for gene in self.model.genes)
|
Private method which transform a state to a string.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_state_to_string({operon: 1, mucuB: 0})
"10"
>>> graph._transform_state_to_string({operon: 2, mucuB: 1})
"21"
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L35-L51
| null |
class Graph:
"""
The state graph for particular model.
"""
def __init__(self, model: DiscreteModel):
self.model = model
self._number_of_states = 0
self._number_of_transitions = 0
self._graph: nx.DiGraph = self._build_graph()
def _build_graph(self) -> nx.DiGraph:
""" Private method to build the graph from the model. """
digraph = nx.DiGraph()
for state in self.model.all_states():
self._number_of_states += 1
for next_state in self.model.available_state(state):
self._number_of_transitions += 1
digraph.add_edge(
self._transform_state_to_string(state),
self._transform_state_to_string(next_state)
)
return digraph
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def show(self, engine: str = "dot") -> 'GraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return GraphDisplayer(self, engine)
def as_dot(self) -> str:
""" Return as a string the dot version of the graph. """
return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()
def export_to_dot(self, filename: str = 'output') -> None:
""" Export the graph to the dot file "filename.dot". """
with open(filename + '.dot', 'w') as output:
output.write(self.as_dot())
def number_of_states(self) -> int:
""" Return the numbers of states in the graph """
return self._number_of_states
def number_of_transitions(self) -> int:
""" Return the numbers of transitions in the graph """
return self._number_of_transitions
|
clement-alexandre/TotemBionet
|
totembionet/src/ggea/ggea.py
|
Graph.as_dot
|
python
|
def as_dot(self) -> str:
return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()
|
Return as a string the dot version of the graph.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L65-L67
| null |
class Graph:
"""
The state graph for particular model.
"""
def __init__(self, model: DiscreteModel):
self.model = model
self._number_of_states = 0
self._number_of_transitions = 0
self._graph: nx.DiGraph = self._build_graph()
def _build_graph(self) -> nx.DiGraph:
""" Private method to build the graph from the model. """
digraph = nx.DiGraph()
for state in self.model.all_states():
self._number_of_states += 1
for next_state in self.model.available_state(state):
self._number_of_transitions += 1
digraph.add_edge(
self._transform_state_to_string(state),
self._transform_state_to_string(next_state)
)
return digraph
def _transform_state_to_string(self, state: State) -> str:
"""
Private method which transform a state to a string.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_state_to_string({operon: 1, mucuB: 0})
"10"
>>> graph._transform_state_to_string({operon: 2, mucuB: 1})
"21"
"""
return ''.join(str(state[gene]) for gene in self.model.genes)
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def show(self, engine: str = "dot") -> 'GraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return GraphDisplayer(self, engine)
def export_to_dot(self, filename: str = 'output') -> None:
""" Export the graph to the dot file "filename.dot". """
with open(filename + '.dot', 'w') as output:
output.write(self.as_dot())
def number_of_states(self) -> int:
""" Return the numbers of states in the graph """
return self._number_of_states
def number_of_transitions(self) -> int:
""" Return the numbers of transitions in the graph """
return self._number_of_transitions
|
clement-alexandre/TotemBionet
|
totembionet/src/ggea/ggea.py
|
Graph.export_to_dot
|
python
|
def export_to_dot(self, filename: str = 'output') -> None:
with open(filename + '.dot', 'w') as output:
output.write(self.as_dot())
|
Export the graph to the dot file "filename.dot".
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L69-L72
|
[
"def as_dot(self) -> str:\n \"\"\" Return as a string the dot version of the graph. \"\"\"\n return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()\n"
] |
class Graph:
"""
The state graph for particular model.
"""
def __init__(self, model: DiscreteModel):
self.model = model
self._number_of_states = 0
self._number_of_transitions = 0
self._graph: nx.DiGraph = self._build_graph()
def _build_graph(self) -> nx.DiGraph:
""" Private method to build the graph from the model. """
digraph = nx.DiGraph()
for state in self.model.all_states():
self._number_of_states += 1
for next_state in self.model.available_state(state):
self._number_of_transitions += 1
digraph.add_edge(
self._transform_state_to_string(state),
self._transform_state_to_string(next_state)
)
return digraph
def _transform_state_to_string(self, state: State) -> str:
"""
Private method which transform a state to a string.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_state_to_string({operon: 1, mucuB: 0})
"10"
>>> graph._transform_state_to_string({operon: 2, mucuB: 1})
"21"
"""
return ''.join(str(state[gene]) for gene in self.model.genes)
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def show(self, engine: str = "dot") -> 'GraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return GraphDisplayer(self, engine)
def as_dot(self) -> str:
""" Return as a string the dot version of the graph. """
return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()
def number_of_states(self) -> int:
""" Return the numbers of states in the graph """
return self._number_of_states
def number_of_transitions(self) -> int:
""" Return the numbers of transitions in the graph """
return self._number_of_transitions
|
clement-alexandre/TotemBionet
|
totembionet/src/resource_table/resource_table.py
|
ResourceTable._build_table
|
python
|
def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]:
result: Dict[State, Tuple[Multiplex, ...]] = {}
for state in self.influence_graph.all_states():
result[state] = tuple(multiplex for multiplex in self.influence_graph.multiplexes
if multiplex.is_active(state))
return result
|
Private method which build the table which map a State to the active multiplex.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/resource_table/resource_table.py#L19-L25
| null |
class ResourceTable:
"""
Create the resource table from the influence graph.
"""
def __init__(self, influence_graph: InfluenceGraph):
self.influence_graph: InfluenceGraph = influence_graph
self.table: Dict[State, Tuple[Multiplex, ...]] = self._build_table()
def active_multiplexes_for_gene(self, gene: Gene, state: State) -> Tuple[Multiplex, ...]:
return tuple(multiplex for multiplex in self.table[state] if multiplex in gene.multiplexes)
def as_data_frame(self) -> pandas.DataFrame:
""" Create a panda DataFrame representation of the resource table. """
header_gene = {}
header_multiplex = {}
for gene in self.influence_graph.genes:
header_gene[gene] = repr(gene)
header_multiplex[gene] = f"active multiplex on {gene!r}"
columns = defaultdict(list)
for state in self.table.keys():
for gene in self.influence_graph.genes:
columns[header_gene[gene]].append(state[gene])
columns[header_multiplex[gene]].append(self._repr_multiplexes(gene, state))
header = list(header_gene.values()) + list(header_multiplex.values())
return pandas.DataFrame(columns, columns=header)
def _repr_html_(self):
return self.as_data_frame()._repr_html_()
def _repr_multiplexes(self, gene: Gene, state: State) -> str:
active_multiplexes = self.active_multiplexes_for_gene(gene, state)
return f'{{{", ".join(map(repr, active_multiplexes))}}}'
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/discrete_model.py
|
DiscreteModel.find_transition
|
python
|
def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)
for transition in self.transitions:
if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):
return transition
raise AttributeError(f'transition K_{gene.name}' + ''.join(f"+{multiplex!r}" for multiplex in multiplexes) + ' does not exist')
|
Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L43-L52
| null |
class DiscreteModel:
def __init__(self, influence_graph: InfluenceGraph, transitions: Tuple[Transition, ...] = ()):
self.influence_graph: InfluenceGraph = influence_graph
self.transitions: List[Transition] = list(transitions)
@property
def genes(self) -> Tuple[Gene, ...]:
""" Mapping for the InfluenceGraph.genes field. """
return tuple(self.influence_graph.genes)
@property
def multiplexes(self) -> Tuple[Multiplex, ...]:
""" Mapping for the InfluenceGraph.multiplexes field. """
return tuple(self.influence_graph.multiplexes)
def find_gene_by_name(self, gene_name: str) -> Gene:
""" Mapping for the InfluenceGraph.find_gene_by_name method. """
return self.influence_graph.find_gene_by_name(gene_name)
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
""" Mapping for the InfluenceGraph.find_multiplex_by_name method. """
return self.influence_graph.find_multiplex_by_name(multiplex_name)
def all_states(self) -> Tuple[State, ...]:
""" Mapping for the InfluenceGraph.all_states method. """
return self.influence_graph.all_states()
def add_transition(self, transition: Transition) -> None:
self.transitions.append(transition)
def available_state(self, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state. """
result = []
for gene in self.genes:
result.extend(self.available_state_for_gene(gene, state))
if len(result) > 1 and state in result:
result.remove(state)
return tuple(result)
def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state for a particular gene. """
result: List[State] = []
active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)
transition: Transition = self.find_transition(gene, active_multiplex)
current_state: int = state[gene]
done = set()
for target_state in transition.states:
target_state: int = self._state_after_transition(current_state, target_state)
if target_state not in done:
done.add(target_state)
new_state: State = state.copy()
new_state[gene] = target_state
result.append(new_state)
return tuple(result)
def _state_after_transition(self, current_state: int, target_state: int) -> int:
"""
Return the state reachable after a transition.
Since the state for a gene can only change by 1, if the absolute value of the
difference current_state - target_state is greater than 1, we lower it to 1 or -1.
Examples
--------
>>> model._state_after_transition(0, 2)
1 # Because 2 is too far from 0, the gene can only reach 1.
>>> model._state_after_transition(1, 5)
2 # 5 is still is too far from 1, so the gene can only reach 2.
>>> model._state_after_transition(2, 1)
1 # No problem here, 1 is at distance 1 from 2
>>> model._state_after_transition(1, 1)
1 # The state does not change here
"""
return current_state + (current_state < target_state) - (current_state > target_state)
def __str__(self) -> str:
string = str(self.influence_graph)
string += '\n\tmodel'
for transition in self.transitions:
string += f'\n\t\t{transition}'
return string
def __repr__(self) -> str:
return f"DiscreteModel(influence graph={self.influence_graph!r}, transitions={self.transitions})"
def __eq__(self, other: Any) -> bool:
if not isinstance(other, DiscreteModel):
return False
return (self.influence_graph == other.influence_graph
and self.transitions == other.transitions)
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/discrete_model.py
|
DiscreteModel.available_state
|
python
|
def available_state(self, state: State) -> Tuple[State, ...]:
result = []
for gene in self.genes:
result.extend(self.available_state_for_gene(gene, state))
if len(result) > 1 and state in result:
result.remove(state)
return tuple(result)
|
Return the state reachable from a given state.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L54-L61
|
[
"def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:\n \"\"\" Return the state reachable from a given state for a particular gene. \"\"\"\n result: List[State] = []\n active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)\n transition: Transition = self.find_transition(gene, active_multiplex)\n current_state: int = state[gene]\n done = set()\n for target_state in transition.states:\n target_state: int = self._state_after_transition(current_state, target_state)\n if target_state not in done:\n done.add(target_state)\n new_state: State = state.copy()\n new_state[gene] = target_state\n result.append(new_state)\n return tuple(result)\n"
] |
class DiscreteModel:
def __init__(self, influence_graph: InfluenceGraph, transitions: Tuple[Transition, ...] = ()):
self.influence_graph: InfluenceGraph = influence_graph
self.transitions: List[Transition] = list(transitions)
@property
def genes(self) -> Tuple[Gene, ...]:
""" Mapping for the InfluenceGraph.genes field. """
return tuple(self.influence_graph.genes)
@property
def multiplexes(self) -> Tuple[Multiplex, ...]:
""" Mapping for the InfluenceGraph.multiplexes field. """
return tuple(self.influence_graph.multiplexes)
def find_gene_by_name(self, gene_name: str) -> Gene:
""" Mapping for the InfluenceGraph.find_gene_by_name method. """
return self.influence_graph.find_gene_by_name(gene_name)
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
""" Mapping for the InfluenceGraph.find_multiplex_by_name method. """
return self.influence_graph.find_multiplex_by_name(multiplex_name)
def all_states(self) -> Tuple[State, ...]:
""" Mapping for the InfluenceGraph.all_states method. """
return self.influence_graph.all_states()
def add_transition(self, transition: Transition) -> None:
self.transitions.append(transition)
def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
"""
Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)
for transition in self.transitions:
if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):
return transition
raise AttributeError(f'transition K_{gene.name}' + ''.join(f"+{multiplex!r}" for multiplex in multiplexes) + ' does not exist')
def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state for a particular gene. """
result: List[State] = []
active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)
transition: Transition = self.find_transition(gene, active_multiplex)
current_state: int = state[gene]
done = set()
for target_state in transition.states:
target_state: int = self._state_after_transition(current_state, target_state)
if target_state not in done:
done.add(target_state)
new_state: State = state.copy()
new_state[gene] = target_state
result.append(new_state)
return tuple(result)
def _state_after_transition(self, current_state: int, target_state: int) -> int:
"""
Return the state reachable after a transition.
Since the state for a gene can only change by 1, if the absolute value of the
difference current_state - target_state is greater than 1, we lower it to 1 or -1.
Examples
--------
>>> model._state_after_transition(0, 2)
1 # Because 2 is too far from 0, the gene can only reach 1.
>>> model._state_after_transition(1, 5)
2 # 5 is still is too far from 1, so the gene can only reach 2.
>>> model._state_after_transition(2, 1)
1 # No problem here, 1 is at distance 1 from 2
>>> model._state_after_transition(1, 1)
1 # The state does not change here
"""
return current_state + (current_state < target_state) - (current_state > target_state)
def __str__(self) -> str:
string = str(self.influence_graph)
string += '\n\tmodel'
for transition in self.transitions:
string += f'\n\t\t{transition}'
return string
def __repr__(self) -> str:
return f"DiscreteModel(influence graph={self.influence_graph!r}, transitions={self.transitions})"
def __eq__(self, other: Any) -> bool:
if not isinstance(other, DiscreteModel):
return False
return (self.influence_graph == other.influence_graph
and self.transitions == other.transitions)
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/discrete_model.py
|
DiscreteModel.available_state_for_gene
|
python
|
def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:
result: List[State] = []
active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)
transition: Transition = self.find_transition(gene, active_multiplex)
current_state: int = state[gene]
done = set()
for target_state in transition.states:
target_state: int = self._state_after_transition(current_state, target_state)
if target_state not in done:
done.add(target_state)
new_state: State = state.copy()
new_state[gene] = target_state
result.append(new_state)
return tuple(result)
|
Return the state reachable from a given state for a particular gene.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L63-L77
|
[
"def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:\n \"\"\" \n Find and return a transition in the model for the given gene and multiplexes.\n Raise an AttributeError if there is no multiplex in the graph with the given name.\n \"\"\"\n multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)\n for transition in self.transitions:\n if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):\n return transition\n raise AttributeError(f'transition K_{gene.name}' + ''.join(f\"+{multiplex!r}\" for multiplex in multiplexes) + ' does not exist')\n",
"def _state_after_transition(self, current_state: int, target_state: int) -> int:\n \"\"\"\n Return the state reachable after a transition.\n Since the state for a gene can only change by 1, if the absolute value of the\n difference current_state - target_state is greater than 1, we lower it to 1 or -1.\n\n Examples\n --------\n\n >>> model._state_after_transition(0, 2)\n 1 # Because 2 is too far from 0, the gene can only reach 1.\n >>> model._state_after_transition(1, 5)\n 2 # 5 is still is too far from 1, so the gene can only reach 2.\n >>> model._state_after_transition(2, 1)\n 1 # No problem here, 1 is at distance 1 from 2\n >>> model._state_after_transition(1, 1)\n 1 # The state does not change here\n\n \"\"\"\n return current_state + (current_state < target_state) - (current_state > target_state)\n"
] |
class DiscreteModel:
def __init__(self, influence_graph: InfluenceGraph, transitions: Tuple[Transition, ...] = ()):
self.influence_graph: InfluenceGraph = influence_graph
self.transitions: List[Transition] = list(transitions)
@property
def genes(self) -> Tuple[Gene, ...]:
""" Mapping for the InfluenceGraph.genes field. """
return tuple(self.influence_graph.genes)
@property
def multiplexes(self) -> Tuple[Multiplex, ...]:
""" Mapping for the InfluenceGraph.multiplexes field. """
return tuple(self.influence_graph.multiplexes)
def find_gene_by_name(self, gene_name: str) -> Gene:
""" Mapping for the InfluenceGraph.find_gene_by_name method. """
return self.influence_graph.find_gene_by_name(gene_name)
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
""" Mapping for the InfluenceGraph.find_multiplex_by_name method. """
return self.influence_graph.find_multiplex_by_name(multiplex_name)
def all_states(self) -> Tuple[State, ...]:
""" Mapping for the InfluenceGraph.all_states method. """
return self.influence_graph.all_states()
def add_transition(self, transition: Transition) -> None:
self.transitions.append(transition)
def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
"""
Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)
for transition in self.transitions:
if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):
return transition
raise AttributeError(f'transition K_{gene.name}' + ''.join(f"+{multiplex!r}" for multiplex in multiplexes) + ' does not exist')
def available_state(self, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state. """
result = []
for gene in self.genes:
result.extend(self.available_state_for_gene(gene, state))
if len(result) > 1 and state in result:
result.remove(state)
return tuple(result)
def _state_after_transition(self, current_state: int, target_state: int) -> int:
"""
Return the state reachable after a transition.
Since the state for a gene can only change by 1, if the absolute value of the
difference current_state - target_state is greater than 1, we lower it to 1 or -1.
Examples
--------
>>> model._state_after_transition(0, 2)
1 # Because 2 is too far from 0, the gene can only reach 1.
>>> model._state_after_transition(1, 5)
2 # 5 is still is too far from 1, so the gene can only reach 2.
>>> model._state_after_transition(2, 1)
1 # No problem here, 1 is at distance 1 from 2
>>> model._state_after_transition(1, 1)
1 # The state does not change here
"""
return current_state + (current_state < target_state) - (current_state > target_state)
def __str__(self) -> str:
string = str(self.influence_graph)
string += '\n\tmodel'
for transition in self.transitions:
string += f'\n\t\t{transition}'
return string
def __repr__(self) -> str:
return f"DiscreteModel(influence graph={self.influence_graph!r}, transitions={self.transitions})"
def __eq__(self, other: Any) -> bool:
if not isinstance(other, DiscreteModel):
return False
return (self.influence_graph == other.influence_graph
and self.transitions == other.transitions)
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/discrete_model.py
|
DiscreteModel._state_after_transition
|
python
|
def _state_after_transition(self, current_state: int, target_state: int) -> int:
return current_state + (current_state < target_state) - (current_state > target_state)
|
Return the state reachable after a transition.
Since the state for a gene can only change by 1, if the absolute value of the
difference current_state - target_state is greater than 1, we lower it to 1 or -1.
Examples
--------
>>> model._state_after_transition(0, 2)
1 # Because 2 is too far from 0, the gene can only reach 1.
>>> model._state_after_transition(1, 5)
2 # 5 is still is too far from 1, so the gene can only reach 2.
>>> model._state_after_transition(2, 1)
1 # No problem here, 1 is at distance 1 from 2
>>> model._state_after_transition(1, 1)
1 # The state does not change here
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L79-L98
| null |
class DiscreteModel:
def __init__(self, influence_graph: InfluenceGraph, transitions: Tuple[Transition, ...] = ()):
self.influence_graph: InfluenceGraph = influence_graph
self.transitions: List[Transition] = list(transitions)
@property
def genes(self) -> Tuple[Gene, ...]:
""" Mapping for the InfluenceGraph.genes field. """
return tuple(self.influence_graph.genes)
@property
def multiplexes(self) -> Tuple[Multiplex, ...]:
""" Mapping for the InfluenceGraph.multiplexes field. """
return tuple(self.influence_graph.multiplexes)
def find_gene_by_name(self, gene_name: str) -> Gene:
""" Mapping for the InfluenceGraph.find_gene_by_name method. """
return self.influence_graph.find_gene_by_name(gene_name)
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
""" Mapping for the InfluenceGraph.find_multiplex_by_name method. """
return self.influence_graph.find_multiplex_by_name(multiplex_name)
def all_states(self) -> Tuple[State, ...]:
""" Mapping for the InfluenceGraph.all_states method. """
return self.influence_graph.all_states()
def add_transition(self, transition: Transition) -> None:
self.transitions.append(transition)
def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
"""
Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)
for transition in self.transitions:
if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):
return transition
raise AttributeError(f'transition K_{gene.name}' + ''.join(f"+{multiplex!r}" for multiplex in multiplexes) + ' does not exist')
def available_state(self, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state. """
result = []
for gene in self.genes:
result.extend(self.available_state_for_gene(gene, state))
if len(result) > 1 and state in result:
result.remove(state)
return tuple(result)
def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state for a particular gene. """
result: List[State] = []
active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)
transition: Transition = self.find_transition(gene, active_multiplex)
current_state: int = state[gene]
done = set()
for target_state in transition.states:
target_state: int = self._state_after_transition(current_state, target_state)
if target_state not in done:
done.add(target_state)
new_state: State = state.copy()
new_state[gene] = target_state
result.append(new_state)
return tuple(result)
def _state_after_transition(self, current_state: int, target_state: int) -> int:
"""
Return the state reachable after a transition.
Since the state for a gene can only change by 1, if the absolute value of the
difference current_state - target_state is greater than 1, we lower it to 1 or -1.
Examples
--------
>>> model._state_after_transition(0, 2)
1 # Because 2 is too far from 0, the gene can only reach 1.
>>> model._state_after_transition(1, 5)
2 # 5 is still is too far from 1, so the gene can only reach 2.
>>> model._state_after_transition(2, 1)
1 # No problem here, 1 is at distance 1 from 2
>>> model._state_after_transition(1, 1)
1 # The state does not change here
"""
return current_state + (current_state < target_state) - (current_state > target_state)
def __str__(self) -> str:
string = str(self.influence_graph)
string += '\n\tmodel'
for transition in self.transitions:
string += f'\n\t\t{transition}'
return string
def __repr__(self) -> str:
return f"DiscreteModel(influence graph={self.influence_graph!r}, transitions={self.transitions})"
def __eq__(self, other: Any) -> bool:
if not isinstance(other, DiscreteModel):
return False
return (self.influence_graph == other.influence_graph
and self.transitions == other.transitions)
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/state.py
|
State.sub_state_by_gene_name
|
python
|
def sub_state_by_gene_name(self, *gene_names: str) -> 'State':
return State({gene: state for gene, state in self.items() if gene.name in gene_names})
|
Create a sub state with only the gene passed in arguments.
Example
-------
>>> state.sub_state_by_gene_name('operon')
{operon: 2}
>>> state.sub_state_by_gene_name('mucuB')
{mucuB: 0}
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/state.py#L41-L54
| null |
class State(collections.UserDict):
"""
Represent a state of the system at a certain time
i.e for each gene, we assign an integer which represent its level.
Examples
--------
>>> state = State()
>>> state[operon] = 2
>>> state[mucuB] = 0
>>> state[operon]
2
>>> for gene, level in state:
... print(gene, level)
operon 2
mucuB 0
"""
def __init__(self, initial_data: Mapping[Gene, int] = {}):
super().__init__()
for gene, state in initial_data.items():
self[gene] = state
def __getitem__(self, gene: Gene) -> int:
return self.data[gene]
def __iter__(self) -> Iterable[Gene]:
yield from self.data
def __len__(self) -> int:
return len(self.data)
def sub_state_by_gene_name(self, *gene_names: str) -> 'State':
"""
Create a sub state with only the gene passed in arguments.
Example
-------
>>> state.sub_state_by_gene_name('operon')
{operon: 2}
>>> state.sub_state_by_gene_name('mucuB')
{mucuB: 0}
"""
return State({gene: state for gene, state in self.items() if gene.name in gene_names})
def __str__(self) -> str:
return str(self.data)
def __repr__(self) -> str:
return repr(self.data)
def __hash__(self) -> int:
return hash(frozenset(self.items()))
def copy(self) -> 'State':
return State(self)
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/influence_graph.py
|
InfluenceGraph.find_gene_by_name
|
python
|
def find_gene_by_name(self, gene_name: str) -> Gene:
for gene in self.genes:
if gene.name == gene_name:
return gene
raise AttributeError(f'gene "{gene_name}" does not exist')
|
Find and return a gene in the influence graph with the given name.
Raise an AttributeError if there is no gene in the graph with the given name.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L24-L32
| null |
class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
self.genes.append(gene)
def add_multiplex(self, multiplex: Multiplex) -> None:
""" Add a multiplex to the influence graph. """
self.multiplexes.append(multiplex)
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
"""
Find and return a multiplex in the influence graph with the given name.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
for multiplex in self.multiplexes:
if multiplex.name == multiplex_name:
return multiplex
raise AttributeError(f'multiplex "{multiplex_name}" does not exist')
def all_states(self) -> Tuple[State, ...]:
""" Return all the possible states of this influence graph. """
return tuple(self._transform_list_of_states_to_state(states)
for states in self._cartesian_product_of_every_states_of_each_genes())
def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]:
"""
Private method which return the cartesian product of the states
of the genes in the model. It represents all the possible state for a given model.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
Then this method returns ((0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1))
For reach tuple, the first element is the state of the operon gene, and the
second element stands for the state of the mucuB gene.
"""
if not self.genes:
return ()
return tuple(product(*[gene.states for gene in self.genes]))
def _transform_list_of_states_to_state(self, state: List[int]) -> State:
"""
Private method which transform a list which contains the state of the gene
in the models to a State object.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_list_of_states_to_dict_of_states([0, 1])
{operon: 0, mucuB: 1}
>>> graph._transform_list_of_states_to_dict_of_states([2, 0])
{operon: 2, mucuB: 0}
"""
return State({gene: state[i] for i, gene in enumerate(self.genes)})
def show(self, engine="fdp") -> 'InfluenceGraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return InfluenceGraphDisplayer(self, engine)
def __str__(self) -> str:
string = '\nInfluenceGraph\n\tgenes:\n\t\t'
string += '\n\t\t'.join(map(str, self.genes))
string += '\n\tmultiplex\n\t\t'
string += '\n\t\t'.join(map(str, self.multiplexes))
return string
def __repr__(self) -> str:
return f'InfluenceGraph(genes={self.genes}, multiplexes={self.multiplexes})'
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, InfluenceGraph):
return False
return (set(self.genes) == set(other.genes)
and set(self.multiplexes) == set(other.multiplexes))
def __hash__(self) -> int:
return hash((frozenset(self.genes), frozenset(self.multiplexes)))
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/influence_graph.py
|
InfluenceGraph.find_multiplex_by_name
|
python
|
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
for multiplex in self.multiplexes:
if multiplex.name == multiplex_name:
return multiplex
raise AttributeError(f'multiplex "{multiplex_name}" does not exist')
|
Find and return a multiplex in the influence graph with the given name.
Raise an AttributeError if there is no multiplex in the graph with the given name.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L38-L46
| null |
class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
self.genes.append(gene)
def find_gene_by_name(self, gene_name: str) -> Gene:
"""
Find and return a gene in the influence graph with the given name.
Raise an AttributeError if there is no gene in the graph with the given name.
"""
for gene in self.genes:
if gene.name == gene_name:
return gene
raise AttributeError(f'gene "{gene_name}" does not exist')
def add_multiplex(self, multiplex: Multiplex) -> None:
""" Add a multiplex to the influence graph. """
self.multiplexes.append(multiplex)
def all_states(self) -> Tuple[State, ...]:
""" Return all the possible states of this influence graph. """
return tuple(self._transform_list_of_states_to_state(states)
for states in self._cartesian_product_of_every_states_of_each_genes())
def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]:
"""
Private method which return the cartesian product of the states
of the genes in the model. It represents all the possible state for a given model.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
Then this method returns ((0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1))
For reach tuple, the first element is the state of the operon gene, and the
second element stands for the state of the mucuB gene.
"""
if not self.genes:
return ()
return tuple(product(*[gene.states for gene in self.genes]))
def _transform_list_of_states_to_state(self, state: List[int]) -> State:
"""
Private method which transform a list which contains the state of the gene
in the models to a State object.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_list_of_states_to_dict_of_states([0, 1])
{operon: 0, mucuB: 1}
>>> graph._transform_list_of_states_to_dict_of_states([2, 0])
{operon: 2, mucuB: 0}
"""
return State({gene: state[i] for i, gene in enumerate(self.genes)})
def show(self, engine="fdp") -> 'InfluenceGraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return InfluenceGraphDisplayer(self, engine)
def __str__(self) -> str:
string = '\nInfluenceGraph\n\tgenes:\n\t\t'
string += '\n\t\t'.join(map(str, self.genes))
string += '\n\tmultiplex\n\t\t'
string += '\n\t\t'.join(map(str, self.multiplexes))
return string
def __repr__(self) -> str:
return f'InfluenceGraph(genes={self.genes}, multiplexes={self.multiplexes})'
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, InfluenceGraph):
return False
return (set(self.genes) == set(other.genes)
and set(self.multiplexes) == set(other.multiplexes))
def __hash__(self) -> int:
return hash((frozenset(self.genes), frozenset(self.multiplexes)))
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/influence_graph.py
|
InfluenceGraph.all_states
|
python
|
def all_states(self) -> Tuple[State, ...]:
return tuple(self._transform_list_of_states_to_state(states)
for states in self._cartesian_product_of_every_states_of_each_genes())
|
Return all the possible states of this influence graph.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L48-L51
|
[
"def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]:\n \"\"\" \n Private method which return the cartesian product of the states\n of the genes in the model. It represents all the possible state for a given model.\n\n Examples\n --------\n\n The model contains 2 genes: operon = {0, 1, 2}\n mucuB = {0, 1}\n Then this method returns ((0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1))\n For reach tuple, the first element is the state of the operon gene, and the\n second element stands for the state of the mucuB gene.\n \"\"\"\n if not self.genes:\n return () \n return tuple(product(*[gene.states for gene in self.genes]))\n"
] |
class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
self.genes.append(gene)
def find_gene_by_name(self, gene_name: str) -> Gene:
"""
Find and return a gene in the influence graph with the given name.
Raise an AttributeError if there is no gene in the graph with the given name.
"""
for gene in self.genes:
if gene.name == gene_name:
return gene
raise AttributeError(f'gene "{gene_name}" does not exist')
def add_multiplex(self, multiplex: Multiplex) -> None:
""" Add a multiplex to the influence graph. """
self.multiplexes.append(multiplex)
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
"""
Find and return a multiplex in the influence graph with the given name.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
for multiplex in self.multiplexes:
if multiplex.name == multiplex_name:
return multiplex
raise AttributeError(f'multiplex "{multiplex_name}" does not exist')
def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]:
"""
Private method which return the cartesian product of the states
of the genes in the model. It represents all the possible state for a given model.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
Then this method returns ((0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1))
For reach tuple, the first element is the state of the operon gene, and the
second element stands for the state of the mucuB gene.
"""
if not self.genes:
return ()
return tuple(product(*[gene.states for gene in self.genes]))
def _transform_list_of_states_to_state(self, state: List[int]) -> State:
"""
Private method which transform a list which contains the state of the gene
in the models to a State object.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_list_of_states_to_dict_of_states([0, 1])
{operon: 0, mucuB: 1}
>>> graph._transform_list_of_states_to_dict_of_states([2, 0])
{operon: 2, mucuB: 0}
"""
return State({gene: state[i] for i, gene in enumerate(self.genes)})
def show(self, engine="fdp") -> 'InfluenceGraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return InfluenceGraphDisplayer(self, engine)
def __str__(self) -> str:
string = '\nInfluenceGraph\n\tgenes:\n\t\t'
string += '\n\t\t'.join(map(str, self.genes))
string += '\n\tmultiplex\n\t\t'
string += '\n\t\t'.join(map(str, self.multiplexes))
return string
def __repr__(self) -> str:
return f'InfluenceGraph(genes={self.genes}, multiplexes={self.multiplexes})'
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, InfluenceGraph):
return False
return (set(self.genes) == set(other.genes)
and set(self.multiplexes) == set(other.multiplexes))
def __hash__(self) -> int:
return hash((frozenset(self.genes), frozenset(self.multiplexes)))
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/influence_graph.py
|
InfluenceGraph._cartesian_product_of_every_states_of_each_genes
|
python
|
def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]:
if not self.genes:
return ()
return tuple(product(*[gene.states for gene in self.genes]))
|
Private method which return the cartesian product of the states
of the genes in the model. It represents all the possible state for a given model.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
Then this method returns ((0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1))
For reach tuple, the first element is the state of the operon gene, and the
second element stands for the state of the mucuB gene.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L53-L69
| null |
class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
self.genes.append(gene)
def find_gene_by_name(self, gene_name: str) -> Gene:
"""
Find and return a gene in the influence graph with the given name.
Raise an AttributeError if there is no gene in the graph with the given name.
"""
for gene in self.genes:
if gene.name == gene_name:
return gene
raise AttributeError(f'gene "{gene_name}" does not exist')
def add_multiplex(self, multiplex: Multiplex) -> None:
""" Add a multiplex to the influence graph. """
self.multiplexes.append(multiplex)
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
"""
Find and return a multiplex in the influence graph with the given name.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
for multiplex in self.multiplexes:
if multiplex.name == multiplex_name:
return multiplex
raise AttributeError(f'multiplex "{multiplex_name}" does not exist')
def all_states(self) -> Tuple[State, ...]:
""" Return all the possible states of this influence graph. """
return tuple(self._transform_list_of_states_to_state(states)
for states in self._cartesian_product_of_every_states_of_each_genes())
def _transform_list_of_states_to_state(self, state: List[int]) -> State:
"""
Private method which transform a list which contains the state of the gene
in the models to a State object.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_list_of_states_to_dict_of_states([0, 1])
{operon: 0, mucuB: 1}
>>> graph._transform_list_of_states_to_dict_of_states([2, 0])
{operon: 2, mucuB: 0}
"""
return State({gene: state[i] for i, gene in enumerate(self.genes)})
def show(self, engine="fdp") -> 'InfluenceGraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return InfluenceGraphDisplayer(self, engine)
def __str__(self) -> str:
string = '\nInfluenceGraph\n\tgenes:\n\t\t'
string += '\n\t\t'.join(map(str, self.genes))
string += '\n\tmultiplex\n\t\t'
string += '\n\t\t'.join(map(str, self.multiplexes))
return string
def __repr__(self) -> str:
return f'InfluenceGraph(genes={self.genes}, multiplexes={self.multiplexes})'
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, InfluenceGraph):
return False
return (set(self.genes) == set(other.genes)
and set(self.multiplexes) == set(other.multiplexes))
def __hash__(self) -> int:
return hash((frozenset(self.genes), frozenset(self.multiplexes)))
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/influence_graph.py
|
InfluenceGraph._transform_list_of_states_to_state
|
python
|
def _transform_list_of_states_to_state(self, state: List[int]) -> State:
return State({gene: state[i] for i, gene in enumerate(self.genes)})
|
Private method which transform a list which contains the state of the gene
in the models to a State object.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_list_of_states_to_dict_of_states([0, 1])
{operon: 0, mucuB: 1}
>>> graph._transform_list_of_states_to_dict_of_states([2, 0])
{operon: 2, mucuB: 0}
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L71-L86
| null |
class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
self.genes.append(gene)
def find_gene_by_name(self, gene_name: str) -> Gene:
"""
Find and return a gene in the influence graph with the given name.
Raise an AttributeError if there is no gene in the graph with the given name.
"""
for gene in self.genes:
if gene.name == gene_name:
return gene
raise AttributeError(f'gene "{gene_name}" does not exist')
def add_multiplex(self, multiplex: Multiplex) -> None:
""" Add a multiplex to the influence graph. """
self.multiplexes.append(multiplex)
def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
"""
Find and return a multiplex in the influence graph with the given name.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
for multiplex in self.multiplexes:
if multiplex.name == multiplex_name:
return multiplex
raise AttributeError(f'multiplex "{multiplex_name}" does not exist')
def all_states(self) -> Tuple[State, ...]:
""" Return all the possible states of this influence graph. """
return tuple(self._transform_list_of_states_to_state(states)
for states in self._cartesian_product_of_every_states_of_each_genes())
def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]:
"""
Private method which return the cartesian product of the states
of the genes in the model. It represents all the possible state for a given model.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
Then this method returns ((0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1))
For reach tuple, the first element is the state of the operon gene, and the
second element stands for the state of the mucuB gene.
"""
if not self.genes:
return ()
return tuple(product(*[gene.states for gene in self.genes]))
def show(self, engine="fdp") -> 'InfluenceGraphDisplayer':
"""
Display the graph using one of the graphviz engine.
Available engines: 'dot', 'twopi', 'fdp', 'patchwork',
'neato', 'osage', 'circo', 'sfdp'.
"""
return InfluenceGraphDisplayer(self, engine)
def __str__(self) -> str:
string = '\nInfluenceGraph\n\tgenes:\n\t\t'
string += '\n\t\t'.join(map(str, self.genes))
string += '\n\tmultiplex\n\t\t'
string += '\n\t\t'.join(map(str, self.multiplexes))
return string
def __repr__(self) -> str:
return f'InfluenceGraph(genes={self.genes}, multiplexes={self.multiplexes})'
def _repr_svg_(self) -> str:
""" Display the graph as html in the notebook. """
return self.show()._repr_svg_()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, InfluenceGraph):
return False
return (set(self.genes) == set(other.genes)
and set(self.multiplexes) == set(other.multiplexes))
def __hash__(self) -> int:
return hash((frozenset(self.genes), frozenset(self.multiplexes)))
|
clement-alexandre/TotemBionet
|
totembionet/src/discrete_model/gene.py
|
Gene.active_multiplex
|
python
|
def active_multiplex(self, state: 'State') -> Tuple['Multiplex']:
return tuple(multiplex for multiplex in self.multiplexes if multiplex.is_active(state))
|
Return a tuple of all the active multiplex in the given state.
|
train
|
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/gene.py#L16-L20
| null |
class Gene:
def __init__(self, name: str, states: Tuple[int, ...]):
self.name: str = name
self.states: Tuple[int, ...] = states
self.multiplexes: List['Multiplex'] = []
def add_multiplex(self, multiplex: 'Multiplex') -> None:
if multiplex not in self.multiplexes:
self.multiplexes.append(multiplex)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Gene):
return False
return self.name == other.name and self.states == other.states
def __hash__(self) -> int:
return hash((self.name, self.states))
def __str__(self) -> str:
return f'{self.name} = {" ".join(map(str, self.states))}'
def __repr__(self) -> str:
return self.name
|
ttroy50/pyephember
|
pyephember/pyephember.py
|
EphEmber._requires_refresh_token
|
python
|
def _requires_refresh_token(self):
expires_on = datetime.datetime.strptime(
self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ')
refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
return expires_on < refresh
|
Check if a refresh of the token is needed
|
train
|
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L32-L39
| null |
class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _request_token(self, force=False):
"""
Request a new auth token
"""
if self.login_data is None:
raise RuntimeError("Don't have a token to refresh")
if not force:
if not self._requires_refresh_token():
# no need to refresh as token is valid
return True
headers = {
"Accept": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "account/RefreshToken"
response = requests.get(url, headers=headers, timeout=10)
if response.status_code != 200:
return False
refresh_data = response.json()
if 'token' not in refresh_data:
return False
self.login_data['token']['accessToken'] = refresh_data['accessToken']
self.login_data['token']['issuedOn'] = refresh_data['issuedOn']
self.login_data['token']['expiresOn'] = refresh_data['expiresOn']
return True
def _login(self):
"""
Login using username / password and get the first auth token
"""
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
url = self.api_base_url + "account/directlogin"
data = {'Email': self.username,
'Password': self.password,
'RememberMe': 'True'}
response = requests.post(url, data=data, headers=headers, timeout=10)
if response.status_code != 200:
return False
self.login_data = response.json()
if not self.login_data['isSuccess']:
self.login_data = None
return False
if ('token' in self.login_data
and 'accessToken' in self.login_data['token']):
self.home_id = self.login_data['token']['currentHomeId']
self.user_id = self.login_data['token']['userId']
return True
self.login_data = None
return False
def _do_auth(self):
"""
Do authentication to the system (if required)
"""
if self.login_data is None:
return self._login()
return self._request_token()
# Public interface
def get_home(self, home_id=None):
"""
Get the data about a home
"""
now = datetime.datetime.utcnow()
if self.home and now < self.home_refresh_at:
return self.home
if not self._do_auth():
raise RuntimeError("Unable to login")
if home_id is None:
home_id = self.home_id
url = self.api_base_url + "Home/GetHomeById"
params = {
"homeId": home_id
}
headers = {
"Accept": "application/json",
'Authorization':
'bearer ' + self.login_data['token']['accessToken']
}
response = requests.get(
url, params=params, headers=headers, timeout=10)
if response.status_code != 200:
raise RuntimeError(
"{} response code when getting home".format(
response.status_code))
home = response.json()
if self.cache_home:
self.home = home
self.home_refresh_at = (datetime.datetime.utcnow()
+ datetime.timedelta(minutes=5))
return home
def get_zones(self):
"""
Get all zones
"""
home_data = self.get_home()
if not home_data['isSuccess']:
return []
zones = []
for receiver in home_data['data']['receivers']:
for zone in receiver['zones']:
zones.append(zone)
return zones
def get_zone_names(self):
"""
Get the name of all zones
"""
zone_names = []
for zone in self.get_zones():
zone_names.append(zone['name'])
return zone_names
def get_zone(self, zone_name):
"""
Get the information about a particular zone
"""
for zone in self.get_zones():
if zone_name == zone['name']:
return zone
raise RuntimeError("Unknown zone")
def is_zone_active(self, zone_name):
"""
Check if a zone is active
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unable to get zone")
return zone['isCurrentlyActive']
def get_zone_temperature(self, zone_name):
"""
Get the temperature for a zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['currentTemperature']
def is_boost_active(self, zone_name):
"""
Check if a zone is active
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['isBoostActive']
def is_target_temperature_reached(self, zone_name):
"""
Check if a zone is active
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['isTargetTemperatureReached']
def set_target_temperature_by_id(self, zone_id, target_temperature):
"""
Set the target temperature for a zone by id
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"TargetTemperature": target_temperature
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/ZoneTargetTemperature"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
zone_change_data = response.json()
return zone_change_data.get("isSuccess", False)
def set_target_temperture_by_name(self, zone_name, target_temperature):
"""
Set the target temperature for a zone by name
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.set_target_temperature_by_id(zone["zoneId"],
target_temperature)
def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1):
"""
Activate boost for a zone based on the numeric id
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
zones = [zone_id]
data = {
"ZoneIds": zones,
"NumberOfHours": num_hours,
"TargetTemperature": target_temperature
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/ActivateZoneBoost"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
boost_data = response.json()
return boost_data.get("isSuccess", False)
def activate_boost_by_name(self,
zone_name,
target_temperature,
num_hours=1):
"""
Activate boost by the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.activate_boost_by_id(zone["zoneId"],
target_temperature, num_hours)
def deactivate_boost_by_id(self, zone_id):
"""
Deactivate boost for a zone based on the numeric id
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
zones = [zone_id]
data = zones
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/DeActivateZoneBoost"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
boost_data = response.json()
return boost_data.get("isSuccess", False)
def deactivate_boost_by_name(self, zone_name):
"""
Deactivate boost by the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.deactivate_boost_by_id(zone["zoneId"])
def set_mode_by_id(self, zone_id, mode):
"""
Set the mode by using the zone id
Supported zones are available in the enum Mode
"""
if not self._do_auth():
raise RuntimeError("Unable to login")
data = {
"ZoneId": zone_id,
"mode": mode.value
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization':
'Bearer ' + self.login_data['token']['accessToken']
}
url = self.api_base_url + "Home/SetZoneMode"
response = requests.post(url, data=json.dumps(
data), headers=headers, timeout=10)
if response.status_code != 200:
return False
mode_data = response.json()
return mode_data.get("isSuccess", False)
def set_mode_by_name(self, zone_name, mode):
"""
Set the mode by using the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.set_mode_by_id(zone["zoneId"], mode)
def get_zone_mode(self, zone_name):
"""
Get the mode for a zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return ZoneMode(zone['mode'])
# Ctor
def __init__(self, username, password, cache_home=False):
"""Performs login and save session cookie."""
# HTTPS Interface
self.home_id = None
self.user_id = None
self.login_data = None
self.username = username
self.password = password
self.cache_home = cache_home
self.home = None
self.home_refresh_at = None
self.api_base_url = 'https://ember.ephcontrols.com/api/'
if not self._login():
raise RuntimeError("Unable to login")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.