code stringlengths 17 6.64M |
|---|
def _padboth(width, s, has_invisible=True):
"Center string.\n\n >>> _padboth(6, 'яйца') == ' яйца '\n True\n\n "
iwidth = (((width + len(s)) - len(_strip_invisible(s))) if has_invisible else width)
fmt = ('{0:^%ds}' % iwidth)
return fmt.format(s)
|
def _strip_invisible(s):
'Remove invisible ANSI color codes.'
if isinstance(s, _text_type):
return re.sub(_invisible_codes, '', s)
else:
return re.sub(_invisible_codes_bytes, '', s)
|
def _visible_width(s):
'Visible width of a printed string. ANSI color codes are removed.\n\n >>> _visible_width(\'\x1b[31mhello\x1b[0m\'), _visible_width("world")\n (5, 5)\n\n '
if (isinstance(s, _text_type) or isinstance(s, _binary_type)):
return len(_strip_invisible(s))
else:
return len(_text_type(s))
|
def _align_column(strings, alignment, minwidth=0, has_invisible=True):
'[string] -> [padded_string]\n\n >>> list(map(str,_align_column(["12.345", "-1234.5", "1.23", "1234.5", "1e+234", "1.0e234"], "decimal")))\n [\' 12.345 \', \'-1234.5 \', \' 1.23 \', \' 1234.5 \', \' 1e+234 \', \' 1.0e234\']\n\n >>> list(map(str,_align_column([\'123.4\', \'56.7890\'], None)))\n [\'123.4\', \'56.7890\']\n\n '
if (alignment == 'right'):
strings = [s.strip() for s in strings]
padfn = _padleft
elif (alignment == 'center'):
strings = [s.strip() for s in strings]
padfn = _padboth
elif (alignment == 'decimal'):
decimals = [_afterpoint(s) for s in strings]
maxdecimals = max(decimals)
strings = [(s + ((maxdecimals - decs) * ' ')) for (s, decs) in zip(strings, decimals)]
padfn = _padleft
elif (not alignment):
return strings
else:
strings = [s.strip() for s in strings]
padfn = _padright
if has_invisible:
width_fn = _visible_width
else:
width_fn = len
maxwidth = max(max(list(map(width_fn, strings))), minwidth)
padded_strings = [padfn(maxwidth, s, has_invisible) for s in strings]
return padded_strings
|
def _more_generic(type1, type2):
types = {_none_type: 0, int: 1, float: 2, _binary_type: 3, _text_type: 4}
invtypes = {4: _text_type, 3: _binary_type, 2: float, 1: int, 0: _none_type}
moregeneric = max(types.get(type1, 4), types.get(type2, 4))
return invtypes[moregeneric]
|
def _column_type(strings, has_invisible=True):
'The least generic type all column values are convertible to.\n\n >>> _column_type(["1", "2"]) is _int_type\n True\n >>> _column_type(["1", "2.3"]) is _float_type\n True\n >>> _column_type(["1", "2.3", "four"]) is _text_type\n True\n >>> _column_type(["four", \'пять\']) is _text_type\n True\n >>> _column_type([None, "brux"]) is _text_type\n True\n >>> _column_type([1, 2, None]) is _int_type\n True\n >>> import datetime as dt\n >>> _column_type([dt.datetime(1991,2,19), dt.time(17,35)]) is _text_type\n True\n\n '
types = [_type(s, has_invisible) for s in strings]
return reduce(_more_generic, types, int)
|
def _format(val, valtype, floatfmt, missingval=''):
"Format a value accoding to its type.\n\n Unicode is supported:\n\n >>> hrow = ['буква', 'цифра'] ; tbl = [['аз', 2], ['буки', 4]] ; good_result = '\\u0431\\u0443\\u043a\\u0432\\u0430 \\u0446\\u0438\\u0444\\u0440\\u0430\\n------- -------\\n\\u0430\\u0437 2\\n\\u0431\\u0443\\u043a\\u0438 4' ; tabulate(tbl, headers=hrow) == good_result\n True\n\n "
if (val is None):
return missingval
if (valtype in [int, _text_type]):
return '{0}'.format(val)
elif (valtype is _binary_type):
return _text_type(val, 'ascii')
elif (valtype is float):
return format(float(val), floatfmt)
else:
return '{0}'.format(val)
|
def _align_header(header, alignment, width):
if (alignment == 'left'):
return _padright(width, header)
elif (alignment == 'center'):
return _padboth(width, header)
elif (not alignment):
return '{0}'.format(header)
else:
return _padleft(width, header)
|
def _normalize_tabular_data(tabular_data, headers):
'Transform a supported data type to a list of lists, and a list of headers.\n\n Supported tabular data types:\n\n * list-of-lists or another iterable of iterables\n\n * list of named tuples (usually used with headers="keys")\n\n * 2D NumPy arrays\n\n * NumPy record arrays (usually used with headers="keys")\n\n * dict of iterables (usually used with headers="keys")\n\n * pandas.DataFrame (usually used with headers="keys")\n\n The first row can be used as headers if headers="firstrow",\n column indices can be used as headers if headers="keys".\n\n '
if (hasattr(tabular_data, 'keys') and hasattr(tabular_data, 'values')):
if hasattr(tabular_data.values, '__call__'):
keys = list(tabular_data.keys())
rows = list(zip_longest(*list(tabular_data.values())))
elif hasattr(tabular_data, 'index'):
keys = list(tabular_data.keys())
vals = tabular_data.values
names = tabular_data.index
rows = [([v] + list(row)) for (v, row) in zip(names, vals)]
else:
raise ValueError("tabular data doesn't appear to be a dict or a DataFrame")
if (headers == 'keys'):
headers = list(map(_text_type, keys))
else:
rows = list(tabular_data)
if ((headers == 'keys') and hasattr(tabular_data, 'dtype') and getattr(tabular_data.dtype, 'names')):
headers = tabular_data.dtype.names
elif ((headers == 'keys') and (len(rows) > 0) and isinstance(rows[0], tuple) and hasattr(rows[0], '_fields')):
headers = list(map(_text_type, rows[0]._fields))
elif ((headers == 'keys') and (len(rows) > 0)):
headers = list(map(_text_type, list(range(len(rows[0])))))
if ((headers == 'firstrow') and (len(rows) > 0)):
headers = list(map(_text_type, rows[0]))
rows = rows[1:]
headers = list(headers)
rows = list(map(list, rows))
if (headers and (len(rows) > 0)):
nhs = len(headers)
ncols = len(rows[0])
if (nhs < ncols):
headers = (([''] * (ncols - nhs)) + headers)
return (rows, headers)
|
def tabulate(tabular_data, headers=[], tablefmt='simple', floatfmt='g', numalign='decimal', stralign='left', missingval=''):
'Format a fixed width table for pretty printing.\n\n >>> print(tabulate([[1, 2.34], [-56, "8.999"], ["2", "10001"]]))\n --- ---------\n 1 2.34\n -56 8.999\n 2 10001\n --- ---------\n\n The first required argument (`tabular_data`) can be a\n list-of-lists (or another iterable of iterables), a list of named\n tuples, a dictionary of iterables, a two-dimensional NumPy array,\n NumPy record array, or a Pandas\' dataframe.\n\n\n Table headers\n -------------\n\n To print nice column headers, supply the second argument (`headers`):\n\n - `headers` can be an explicit list of column headers\n - if `headers="firstrow"`, then the first row of data is used\n - if `headers="keys"`, then dictionary keys or column indices are used\n\n Otherwise a headerless table is produced.\n\n If the number of headers is less than the number of columns, they\n are supposed to be names of the last columns. This is consistent\n with the plain-text format of R and Pandas\' dataframes.\n\n >>> print(tabulate([["sex","age"],["Alice","F",24],["Bob","M",19]],\n ... headers="firstrow"))\n sex age\n ----- ----- -----\n Alice F 24\n Bob M 19\n\n\n Column alignment\n ----------------\n\n `tabulate` tries to detect column types automatically, and aligns\n the values properly. By default it aligns decimal points of the\n numbers (or flushes integer numbers to the right), and flushes\n everything else to the left. Possible column alignments\n (`numalign`, `stralign`) are: "right", "center", "left", "decimal"\n (only for `numalign`), and None (to disable alignment).\n\n\n Table formats\n -------------\n\n `floatfmt` is a format specification used for columns which\n contain numeric data with a decimal point.\n\n `None` values are replaced with a `missingval` string:\n\n >>> print(tabulate([["spam", 1, None],\n ... ["eggs", 42, 3.14],\n ... ["other", None, 2.7]], missingval="?"))\n ----- -- ----\n spam 1 ?\n eggs 42 3.14\n other ? 2.7\n ----- -- ----\n\n Various plain-text table formats (`tablefmt`) are supported:\n \'plain\', \'simple\', \'grid\', \'pipe\', \'orgtbl\', \'rst\', \'mediawiki\',\n and \'latex\'. Variable `tabulate_formats` contains the list of\n currently supported formats.\n\n "plain" format doesn\'t use any pseudographics to draw tables,\n it separates columns with a double space:\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],\n ... ["strings", "numbers"], "plain"))\n strings numbers\n spam 41.9999\n eggs 451\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="plain"))\n spam 41.9999\n eggs 451\n\n "simple" format is like Pandoc simple_tables:\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],\n ... ["strings", "numbers"], "simple"))\n strings numbers\n --------- ---------\n spam 41.9999\n eggs 451\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="simple"))\n ---- --------\n spam 41.9999\n eggs 451\n ---- --------\n\n "grid" is similar to tables produced by Emacs table.el package or\n Pandoc grid_tables:\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],\n ... ["strings", "numbers"], "grid"))\n +-----------+-----------+\n | strings | numbers |\n +===========+===========+\n | spam | 41.9999 |\n +-----------+-----------+\n | eggs | 451 |\n +-----------+-----------+\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="grid"))\n +------+----------+\n | spam | 41.9999 |\n +------+----------+\n | eggs | 451 |\n +------+----------+\n\n "pipe" is like tables in PHP Markdown Extra extension or Pandoc\n pipe_tables:\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],\n ... ["strings", "numbers"], "pipe"))\n | strings | numbers |\n |:----------|----------:|\n | spam | 41.9999 |\n | eggs | 451 |\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="pipe"))\n |:-----|---------:|\n | spam | 41.9999 |\n | eggs | 451 |\n\n "orgtbl" is like tables in Emacs org-mode and orgtbl-mode. They\n are slightly different from "pipe" format by not using colons to\n define column alignment, and using a "+" sign to indicate line\n intersections:\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],\n ... ["strings", "numbers"], "orgtbl"))\n | strings | numbers |\n |-----------+-----------|\n | spam | 41.9999 |\n | eggs | 451 |\n\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="orgtbl"))\n | spam | 41.9999 |\n | eggs | 451 |\n\n "rst" is like a simple table format from reStructuredText; please\n note that reStructuredText accepts also "grid" tables:\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],\n ... ["strings", "numbers"], "rst"))\n ========= =========\n strings numbers\n ========= =========\n spam 41.9999\n eggs 451\n ========= =========\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="rst"))\n ==== ========\n spam 41.9999\n eggs 451\n ==== ========\n\n "mediawiki" produces a table markup used in Wikipedia and on other\n MediaWiki-based sites:\n\n >>> print(tabulate([["strings", "numbers"], ["spam", 41.9999], ["eggs", "451.0"]],\n ... headers="firstrow", tablefmt="mediawiki"))\n {| class="wikitable" style="text-align: left;"\n |+ <!-- caption -->\n |-\n ! strings !! align="right"| numbers\n |-\n | spam || align="right"| 41.9999\n |-\n | eggs || align="right"| 451\n |}\n\n "latex" produces a tabular environment of LaTeX document markup:\n\n >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="latex"))\n \\begin{tabular}{lr}\n \\hline\n spam & 41.9999 \\\\\n eggs & 451 \\\\\n \\hline\n \\end{tabular}\n\n '
(list_of_lists, headers) = _normalize_tabular_data(tabular_data, headers)
plain_text = '\n'.join((['\t'.join(map(_text_type, headers))] + ['\t'.join(map(_text_type, row)) for row in list_of_lists]))
has_invisible = re.search(_invisible_codes, plain_text)
if has_invisible:
width_fn = _visible_width
else:
width_fn = len
cols = list(zip(*list_of_lists))
coltypes = list(map(_column_type, cols))
cols = [[_format(v, ct, floatfmt, missingval) for v in c] for (c, ct) in zip(cols, coltypes)]
aligns = [(numalign if (ct in [int, float]) else stralign) for ct in coltypes]
minwidths = ([(width_fn(h) + 2) for h in headers] if headers else ([0] * len(cols)))
cols = [_align_column(c, a, minw, has_invisible) for (c, a, minw) in zip(cols, aligns, minwidths)]
if headers:
minwidths = [max(minw, width_fn(c[0])) for (minw, c) in zip(minwidths, cols)]
headers = [_align_header(h, a, minw) for (h, a, minw) in zip(headers, aligns, minwidths)]
rows = list(zip(*cols))
else:
minwidths = [width_fn(c[0]) for c in cols]
rows = list(zip(*cols))
if (not isinstance(tablefmt, TableFormat)):
tablefmt = _table_formats.get(tablefmt, _table_formats['simple'])
return _format_table(tablefmt, headers, rows, minwidths, aligns)
|
def _build_simple_row(padded_cells, rowfmt):
'Format row according to DataRow format without padding.'
(begin, sep, end) = rowfmt
return ((begin + sep.join(padded_cells)) + end).rstrip()
|
def _build_row(padded_cells, colwidths, colaligns, rowfmt):
'Return a string which represents a row of data cells.'
if (not rowfmt):
return None
if hasattr(rowfmt, '__call__'):
return rowfmt(padded_cells, colwidths, colaligns)
else:
return _build_simple_row(padded_cells, rowfmt)
|
def _build_line(colwidths, colaligns, linefmt):
'Return a string which represents a horizontal line.'
if (not linefmt):
return None
if hasattr(linefmt, '__call__'):
return linefmt(colwidths, colaligns)
else:
(begin, fill, sep, end) = linefmt
cells = [(fill * w) for w in colwidths]
return _build_simple_row(cells, (begin, sep, end))
|
def _pad_row(cells, padding):
if cells:
pad = (' ' * padding)
padded_cells = [((pad + cell) + pad) for cell in cells]
return padded_cells
else:
return cells
|
def _format_table(fmt, headers, rows, colwidths, colaligns):
'Produce a plain-text representation of the table.'
lines = []
hidden = (fmt.with_header_hide if (headers and fmt.with_header_hide) else [])
pad = fmt.padding
headerrow = fmt.headerrow
padded_widths = [(w + (2 * pad)) for w in colwidths]
padded_headers = _pad_row(headers, pad)
padded_rows = [_pad_row(row, pad) for row in rows]
if (fmt.lineabove and ('lineabove' not in hidden)):
lines.append(_build_line(padded_widths, colaligns, fmt.lineabove))
if padded_headers:
lines.append(_build_row(padded_headers, padded_widths, colaligns, headerrow))
if (fmt.linebelowheader and ('linebelowheader' not in hidden)):
lines.append(_build_line(padded_widths, colaligns, fmt.linebelowheader))
if (padded_rows and fmt.linebetweenrows and ('linebetweenrows' not in hidden)):
for row in padded_rows[:(- 1)]:
lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow))
lines.append(_build_line(padded_widths, colaligns, fmt.linebetweenrows))
lines.append(_build_row(padded_rows[(- 1)], padded_widths, colaligns, fmt.datarow))
else:
for row in padded_rows:
lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow))
if (fmt.linebelow and ('linebelow' not in hidden)):
lines.append(_build_line(padded_widths, colaligns, fmt.linebelow))
return '\n'.join(lines)
|
def flatten_tensors(tensors):
if (len(tensors) > 0):
return np.concatenate([np.reshape(x, [(- 1)]) for x in tensors])
else:
return np.asarray([])
|
def unflatten_tensors(flattened, tensor_shapes):
tensor_sizes = list(map(np.prod, tensor_shapes))
indices = np.cumsum(tensor_sizes)[:(- 1)]
return [np.reshape(pair[0], pair[1]) for pair in zip(np.split(flattened, indices), tensor_shapes)]
|
def pad_tensor(x, max_len, mode='zero'):
padding = np.zeros_like(x[0])
if (mode == 'last'):
padding = x[(- 1)]
return np.concatenate([x, np.tile(padding, (((max_len - len(x)),) + ((1,) * np.ndim(x[0]))))])
|
def pad_tensor_n(xs, max_len):
ret = np.zeros(((len(xs), max_len) + xs[0].shape[1:]), dtype=xs[0].dtype)
for (idx, x) in enumerate(xs):
ret[idx][:len(x)] = x
return ret
|
def pad_tensor_dict(tensor_dict, max_len, mode='zero'):
keys = list(tensor_dict.keys())
ret = dict()
for k in keys:
if isinstance(tensor_dict[k], dict):
ret[k] = pad_tensor_dict(tensor_dict[k], max_len, mode=mode)
else:
ret[k] = pad_tensor(tensor_dict[k], max_len, mode=mode)
return ret
|
def high_res_normalize(probs):
return [(x / sum(map(float, probs))) for x in list(map(float, probs))]
|
def stack_tensor_list(tensor_list):
return np.array(tensor_list)
|
def stack_tensor_dict_list(tensor_dict_list):
'\n Stack a list of dictionaries of {tensors or dictionary of tensors}.\n :param tensor_dict_list: a list of dictionaries of {tensors or dictionary of tensors}.\n :return: a dictionary of {stacked tensors or dictionary of stacked tensors}\n '
keys = list(tensor_dict_list[0].keys())
ret = dict()
for k in keys:
example = tensor_dict_list[0][k]
if isinstance(example, dict):
v = stack_tensor_dict_list([x[k] for x in tensor_dict_list])
else:
v = stack_tensor_list([x[k] for x in tensor_dict_list])
ret[k] = v
return ret
|
def concat_tensor_list(tensor_list):
return np.concatenate(tensor_list, axis=0)
|
def concat_tensor_dict_list(tensor_dict_list):
keys = list(tensor_dict_list[0].keys())
ret = dict()
for k in keys:
example = tensor_dict_list[0][k]
if isinstance(example, dict):
v = concat_tensor_dict_list([x[k] for x in tensor_dict_list])
else:
v = concat_tensor_list([x[k] for x in tensor_dict_list])
ret[k] = v
return ret
|
def split_tensor_dict_list(tensor_dict):
keys = list(tensor_dict.keys())
ret = None
for k in keys:
vals = tensor_dict[k]
if isinstance(vals, dict):
vals = split_tensor_dict_list(vals)
if (ret is None):
ret = [{k: v} for v in vals]
else:
for (v, cur_dict) in zip(vals, ret):
cur_dict[k] = v
return ret
|
def truncate_tensor_list(tensor_list, truncated_len):
return tensor_list[:truncated_len]
|
def truncate_tensor_dict(tensor_dict, truncated_len):
ret = dict()
for (k, v) in tensor_dict.items():
if isinstance(v, dict):
ret[k] = truncate_tensor_dict(v, truncated_len)
else:
ret[k] = truncate_tensor_list(v, truncated_len)
return ret
|
class Colors(object):
black = (0, 0, 0)
white = (255, 255, 255)
blue = (0, 0, 255)
red = (255, 0, 0)
green = (0, 255, 0)
|
class Viewer2D(object):
def __init__(self, size=(640, 480), xlim=None, ylim=None):
pygame.init()
screen = pygame.display.set_mode(size)
if (xlim is None):
xlim = (0, size[0])
if (ylim is None):
ylim = (0, size[1])
self._screen = screen
self._xlim = xlim
self._ylim = ylim
@property
def xlim(self):
return self._xlim
@xlim.setter
def xlim(self, value):
self._xlim = value
@property
def ylim(self):
return self._ylim
@ylim.setter
def ylim(self, value):
self._ylim = value
def reset(self):
self.fill(Colors.white)
def fill(self, color):
self.screen.fill(color)
def scale_x(self, world_x):
(xmin, xmax) = self.xlim
return int((((world_x - xmin) * self.screen.get_width()) / (xmax - xmin)))
def scale_y(self, world_y):
(ymin, ymax) = self.ylim
return int((self.screen.get_height() - (((world_y - ymin) * self.screen.get_height()) / (ymax - ymin))))
def scale_point(self, point):
(x, y) = point
return (self.scale_x(x), self.scale_y(y))
@property
def scale_factor(self):
(xmin, xmax) = self.xlim
(ymin, ymax) = self.ylim
return min((self.screen.get_width() / (xmax - xmin)), (self.screen.get_height() / (ymax - ymin)))
def scale_size(self, size):
if hasattr(size, '__len__'):
(x, y) = size
return (self.scale_x((x + self.xlim[0])), (self.screen.get_height() - self.scale_y((y + self.ylim[0]))))
return (size * self.scale_factor)
def line(self, color, p1, p2, width=None):
if (width is None):
width = 1
else:
width = int((width * self.scale_factor))
(x1, y1) = self.scale_point(p1)
(x2, y2) = self.scale_point(p2)
pygame.draw.line(self.screen, color, (x1, y1), (x2, y2), width)
def circle(self, color, p, radius):
pygame.draw.circle(self.screen, color, self.scale_point(p), int(self.scale_size(radius)))
def rect(self, color, center, size):
(cx, cy) = self.scale_point(center)
(w, h) = self.scale_size(size)
if (len(color) > 3):
s = pygame.Surface((w, h), pygame.SRCALPHA)
s.fill(color)
self.screen.blit(s, ((cx - (w / 2)), (cy - (h / 2))))
else:
pygame.draw.rect(self.screen, color, pygame.Rect((cx - (w / 2)), (cy - (h / 2)), w, h))
def polygon(self, color, points):
if (len(color) > 3):
s = pygame.Surface((self.screen.get_width(), self.screen.get_height()), pygame.SRCALPHA)
s.fill((0, 0, 0, 0))
pygame.draw.polygon(s, color, list(map(self.scale_point, points)))
self.screen.blit(s, (0, 0))
else:
pygame.draw.polygon(self.screen, color, list(map(self.scale_point, points)))
@property
def screen(self):
return self._screen
def loop_once(self):
pygame.display.flip()
def checker(self, colors=[Colors.white, Colors.black], granularity=4, offset=(0, 0)):
screen_height = self.screen.get_height()
screen_width = self.screen.get_width()
screen_size = min(screen_height, screen_width)
checker_size = int((screen_size / granularity))
offset_x = self.scale_x((offset[0] + self.xlim[0]))
offset_y = self.scale_y((offset[1] + self.ylim[0]))
start_idx = (int((offset_x / checker_size)) + int((offset_y / checker_size)))
offset_x = (((offset_x % checker_size) + checker_size) % checker_size)
offset_y = (((offset_y % checker_size) + checker_size) % checker_size)
for row in range((- 1), (int(np.ceil(((screen_height * 1.0) / checker_size))) + 1)):
for col in range((- 1), (int(np.ceil(((screen_width * 1.0) / checker_size))) + 1)):
the_square = (((col * checker_size) + offset_x), ((row * checker_size) + offset_y), checker_size, checker_size)
self.screen.fill(colors[(((start_idx + row) + col) % 2)], the_square)
def pause(self):
print('press any key on the screen to continue...')
while True:
event = pygame.event.wait()
if (event.type == pygame.KEYDOWN):
break
print('continuing')
|
def _find_library_candidates(library_names, library_file_extensions, library_search_paths):
'\n Finds and returns filenames which might be the library you are looking for.\n '
candidates = set()
for library_name in library_names:
for search_path in library_search_paths:
glob_query = os.path.join(search_path, (('*' + library_name) + '*'))
for filename in glob.iglob(glob_query):
filename = os.path.realpath(filename)
if (filename in candidates):
continue
basename = os.path.basename(filename)
if basename.startswith(('lib' + library_name)):
basename_end = basename[len(('lib' + library_name)):]
elif basename.startswith(library_name):
basename_end = basename[len(library_name):]
else:
continue
for file_extension in library_file_extensions:
if basename_end.startswith(file_extension):
if (basename_end[len(file_extension):][:1] in ('', '.')):
candidates.add(filename)
if basename_end.endswith(file_extension):
basename_middle = basename_end[:(- len(file_extension))]
if all(((c in '0123456789.') for c in basename_middle)):
candidates.add(filename)
return candidates
|
def _load_library():
'\n Finds, loads and returns the most recent version of the library.\n '
osp = os.path
if sys.platform.startswith('darwin'):
libfile = osp.abspath(osp.join(osp.dirname(__file__), '../../vendor/mujoco/libglfw.3.dylib'))
elif sys.platform.startswith('linux'):
libfile = osp.abspath(osp.join(osp.dirname(__file__), '../../vendor/mujoco/libglfw.so.3'))
elif sys.platform.startswith('win'):
libfile = osp.abspath(osp.join(osp.dirname(__file__), '../../vendor/mujoco/glfw3.dll'))
else:
raise RuntimeError(('unrecognized platform %s' % sys.platform))
return ctypes.CDLL(libfile)
|
def _glfw_get_version(filename):
'\n Queries and returns the library version tuple or None by using a\n subprocess.\n '
version_checker_source = "\n import sys\n import ctypes\n\n def get_version(library_handle):\n '''\n Queries and returns the library version tuple or None.\n '''\n major_value = ctypes.c_int(0)\n major = ctypes.pointer(major_value)\n minor_value = ctypes.c_int(0)\n minor = ctypes.pointer(minor_value)\n rev_value = ctypes.c_int(0)\n rev = ctypes.pointer(rev_value)\n if hasattr(library_handle, 'glfwGetVersion'):\n library_handle.glfwGetVersion(major, minor, rev)\n version = (major_value.value,\n minor_value.value,\n rev_value.value)\n return version\n else:\n return None\n\n try:\n input_func = raw_input\n except NameError:\n input_func = input\n filename = input_func().strip()\n\n try:\n library_handle = ctypes.CDLL(filename)\n except OSError:\n pass\n else:\n version = get_version(library_handle)\n print(version)\n "
args = [sys.executable, '-c', textwrap.dedent(version_checker_source)]
process = subprocess.Popen(args, universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out = process.communicate(_to_char_p(filename))[0]
out = out.strip()
if out:
return eval(out)
else:
return None
|
class _GLFWwindow(ctypes.Structure):
'\n Wrapper for:\n typedef struct GLFWwindow GLFWwindow;\n '
_fields_ = [('dummy', ctypes.c_int)]
|
class _GLFWmonitor(ctypes.Structure):
'\n Wrapper for:\n typedef struct GLFWmonitor GLFWmonitor;\n '
_fields_ = [('dummy', ctypes.c_int)]
|
class _GLFWvidmode(ctypes.Structure):
'\n Wrapper for:\n typedef struct GLFWvidmode GLFWvidmode;\n '
_fields_ = [('width', ctypes.c_int), ('height', ctypes.c_int), ('red_bits', ctypes.c_int), ('green_bits', ctypes.c_int), ('blue_bits', ctypes.c_int), ('refresh_rate', ctypes.c_uint)]
def __init__(self):
ctypes.Structure.__init__(self)
self.width = 0
self.height = 0
self.red_bits = 0
self.green_bits = 0
self.blue_bits = 0
self.refresh_rate = 0
def wrap(self, video_mode):
'\n Wraps a nested python sequence.\n '
(size, bits, self.refresh_rate) = video_mode
(self.width, self.height) = size
(self.red_bits, self.green_bits, self.blue_bits) = bits
def unwrap(self):
'\n Returns a nested python sequence.\n '
size = (self.width, self.height)
bits = (self.red_bits, self.green_bits, self.blue_bits)
return (size, bits, self.refresh_rate)
|
class _GLFWgammaramp(ctypes.Structure):
'\n Wrapper for:\n typedef struct GLFWgammaramp GLFWgammaramp;\n '
_fields_ = [('red', ctypes.POINTER(ctypes.c_ushort)), ('green', ctypes.POINTER(ctypes.c_ushort)), ('blue', ctypes.POINTER(ctypes.c_ushort)), ('size', ctypes.c_uint)]
def __init__(self):
ctypes.Structure.__init__(self)
self.red = None
self.red_array = None
self.green = None
self.green_array = None
self.blue = None
self.blue_array = None
self.size = 0
def wrap(self, gammaramp):
'\n Wraps a nested python sequence.\n '
(red, green, blue) = gammaramp
size = min(len(red), len(green), len(blue))
array_type = (ctypes.c_ushort * size)
self.size = ctypes.c_uint(size)
self.red_array = array_type()
self.green_array = array_type()
self.blue_array = array_type()
for i in range(self.size):
self.red_array[i] = int((red[i] * 65535))
self.green_array[i] = int((green[i] * 65535))
self.blue_array[i] = int((blue[i] * 65535))
pointer_type = ctypes.POINTER(ctypes.c_ushort)
self.red = ctypes.cast(self.red_array, pointer_type)
self.green = ctypes.cast(self.green_array, pointer_type)
self.blue = ctypes.cast(self.blue_array, pointer_type)
def unwrap(self):
'\n Returns a nested python sequence.\n '
red = [(self.red[i] / 65535.0) for i in range(self.size)]
green = [(self.green[i] / 65535.0) for i in range(self.size)]
blue = [(self.blue[i] / 65535.0) for i in range(self.size)]
return (red, green, blue)
|
def init():
'\n Initializes the GLFW library.\n\n Wrapper for:\n int glfwInit(void);\n '
cwd = _getcwd()
res = _glfw.glfwInit()
os.chdir(cwd)
return res
|
def terminate():
'\n Terminates the GLFW library.\n\n Wrapper for:\n void glfwTerminate(void);\n '
_glfw.glfwTerminate()
|
def get_version():
'\n Retrieves the version of the GLFW library.\n\n Wrapper for:\n void glfwGetVersion(int* major, int* minor, int* rev);\n '
major_value = ctypes.c_int(0)
major = ctypes.pointer(major_value)
minor_value = ctypes.c_int(0)
minor = ctypes.pointer(minor_value)
rev_value = ctypes.c_int(0)
rev = ctypes.pointer(rev_value)
_glfw.glfwGetVersion(major, minor, rev)
return (major_value.value, minor_value.value, rev_value.value)
|
def get_version_string():
'\n Returns a string describing the compile-time configuration.\n\n Wrapper for:\n const char* glfwGetVersionString(void);\n '
return _glfw.glfwGetVersionString()
|
def set_error_callback(cbfun):
'\n Sets the error callback.\n\n Wrapper for:\n GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);\n '
global _error_callback
previous_callback = _error_callback
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWerrorfun(cbfun)
_error_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetErrorCallback(cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def get_monitors():
'\n Returns the currently connected monitors.\n\n Wrapper for:\n GLFWmonitor** glfwGetMonitors(int* count);\n '
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetMonitors(count)
monitors = [result[i] for i in range(count_value.value)]
return monitors
|
def get_primary_monitor():
'\n Returns the primary monitor.\n\n Wrapper for:\n GLFWmonitor* glfwGetPrimaryMonitor(void);\n '
return _glfw.glfwGetPrimaryMonitor()
|
def get_monitor_pos(monitor):
"\n Returns the position of the monitor's viewport on the virtual screen.\n\n Wrapper for:\n void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos);\n "
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_int(0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetMonitorPos(monitor, xpos, ypos)
return (xpos_value.value, ypos_value.value)
|
def get_monitor_physical_size(monitor):
'\n Returns the physical size of the monitor.\n\n Wrapper for:\n void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height);\n '
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetMonitorPhysicalSize(monitor, width, height)
return (width_value.value, height_value.value)
|
def get_monitor_name(monitor):
'\n Returns the name of the specified monitor.\n\n Wrapper for:\n const char* glfwGetMonitorName(GLFWmonitor* monitor);\n '
return _glfw.glfwGetMonitorName(monitor)
|
def set_monitor_callback(cbfun):
'\n Sets the monitor configuration callback.\n\n Wrapper for:\n GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun);\n '
global _monitor_callback
previous_callback = _monitor_callback
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWmonitorfun(cbfun)
_monitor_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetMonitorCallback(cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def get_video_modes(monitor):
'\n Returns the available video modes for the specified monitor.\n\n Wrapper for:\n const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count);\n '
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetVideoModes(monitor, count)
videomodes = [result[i].unwrap() for i in range(count_value.value)]
return videomodes
|
def get_video_mode(monitor):
'\n Returns the current mode of the specified monitor.\n\n Wrapper for:\n const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor);\n '
videomode = _glfw.glfwGetVideoMode(monitor).contents
return videomode.unwrap()
|
def set_gamma(monitor, gamma):
'\n Generates a gamma ramp and sets it for the specified monitor.\n\n Wrapper for:\n void glfwSetGamma(GLFWmonitor* monitor, float gamma);\n '
_glfw.glfwSetGamma(monitor, gamma)
|
def get_gamma_ramp(monitor):
'\n Retrieves the current gamma ramp for the specified monitor.\n\n Wrapper for:\n const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor);\n '
gammaramp = _glfw.glfwGetGammaRamp(monitor).contents
return gammaramp.unwrap()
|
def set_gamma_ramp(monitor, ramp):
'\n Sets the current gamma ramp for the specified monitor.\n\n Wrapper for:\n void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp);\n '
gammaramp = _GLFWgammaramp()
gammaramp.wrap(ramp)
_glfw.glfwSetGammaRamp(monitor, ctypes.pointer(gammaramp))
|
def default_window_hints():
'\n Resets all window hints to their default values.\n\n Wrapper for:\n void glfwDefaultWindowHints(void);\n '
_glfw.glfwDefaultWindowHints()
|
def window_hint(target, hint):
'\n Sets the specified window hint to the desired value.\n\n Wrapper for:\n void glfwWindowHint(int target, int hint);\n '
_glfw.glfwWindowHint(target, hint)
|
def create_window(width, height, title, monitor, share):
'\n Creates a window and its associated context.\n\n Wrapper for:\n GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share);\n\n '
return _glfw.glfwCreateWindow(width, height, _to_char_p(title), monitor, share)
|
def destroy_window(window):
'\n Destroys the specified window and its context.\n\n Wrapper for:\n void glfwDestroyWindow(GLFWwindow* window);\n '
_glfw.glfwDestroyWindow(window)
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_ulong)).contents.value
for callback_repository in _callback_repositories:
del callback_repository[window_addr]
|
def window_should_close(window):
'\n Checks the close flag of the specified window.\n\n Wrapper for:\n int glfwWindowShouldClose(GLFWwindow* window);\n '
return _glfw.glfwWindowShouldClose(window)
|
def set_window_should_close(window, value):
'\n Sets the close flag of the specified window.\n\n Wrapper for:\n void glfwSetWindowShouldClose(GLFWwindow* window, int value);\n '
_glfw.glfwSetWindowShouldClose(window, value)
|
def set_window_title(window, title):
'\n Sets the title of the specified window.\n\n Wrapper for:\n void glfwSetWindowTitle(GLFWwindow* window, const char* title);\n '
_glfw.glfwSetWindowTitle(window, _to_char_p(title))
|
def get_window_pos(window):
'\n Retrieves the position of the client area of the specified window.\n\n Wrapper for:\n void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos);\n '
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_int(0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetWindowPos(window, xpos, ypos)
return (xpos_value.value, ypos_value.value)
|
def set_window_pos(window, xpos, ypos):
'\n Sets the position of the client area of the specified window.\n\n Wrapper for:\n void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos);\n '
_glfw.glfwSetWindowPos(window, xpos, ypos)
|
def get_window_size(window):
'\n Retrieves the size of the client area of the specified window.\n\n Wrapper for:\n void glfwGetWindowSize(GLFWwindow* window, int* width, int* height);\n '
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetWindowSize(window, width, height)
return (width_value.value, height_value.value)
|
def set_window_size(window, width, height):
'\n Sets the size of the client area of the specified window.\n\n Wrapper for:\n void glfwSetWindowSize(GLFWwindow* window, int width, int height);\n '
_glfw.glfwSetWindowSize(window, width, height)
|
def get_framebuffer_size(window):
'\n Retrieves the size of the framebuffer of the specified window.\n\n Wrapper for:\n void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height);\n '
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetFramebufferSize(window, width, height)
return (width_value.value, height_value.value)
|
def iconify_window(window):
'\n Iconifies the specified window.\n\n Wrapper for:\n void glfwIconifyWindow(GLFWwindow* window);\n '
_glfw.glfwIconifyWindow(window)
|
def restore_window(window):
'\n Restores the specified window.\n\n Wrapper for:\n void glfwRestoreWindow(GLFWwindow* window);\n '
_glfw.glfwRestoreWindow(window)
|
def show_window(window):
'\n Makes the specified window visible.\n\n Wrapper for:\n void glfwShowWindow(GLFWwindow* window);\n '
_glfw.glfwShowWindow(window)
|
def hide_window(window):
'\n Hides the specified window.\n\n Wrapper for:\n void glfwHideWindow(GLFWwindow* window);\n '
_glfw.glfwHideWindow(window)
|
def get_window_monitor(window):
'\n Returns the monitor that the window uses for full screen mode.\n\n Wrapper for:\n GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window);\n '
return _glfw.glfwGetWindowMonitor(window)
|
def get_window_attrib(window, attrib):
'\n Returns an attribute of the specified window.\n\n Wrapper for:\n int glfwGetWindowAttrib(GLFWwindow* window, int attrib);\n '
return _glfw.glfwGetWindowAttrib(window, attrib)
|
def set_window_user_pointer(window, pointer):
'\n Sets the user pointer of the specified window.\n\n Wrapper for:\n void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer);\n '
_glfw.glfwSetWindowUserPointer(window, pointer)
|
def get_window_user_pointer(window):
'\n Returns the user pointer of the specified window.\n\n Wrapper for:\n void* glfwGetWindowUserPointer(GLFWwindow* window);\n '
return _glfw.glfwGetWindowUserPointer(window)
|
def set_window_pos_callback(window, cbfun):
'\n Sets the position callback for the specified window.\n\n Wrapper for:\n GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _window_pos_callback_repository):
previous_callback = _window_pos_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWwindowposfun(cbfun)
_window_pos_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowPosCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_window_size_callback(window, cbfun):
'\n Sets the size callback for the specified window.\n\n Wrapper for:\n GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _window_size_callback_repository):
previous_callback = _window_size_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWwindowsizefun(cbfun)
_window_size_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowSizeCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_window_close_callback(window, cbfun):
'\n Sets the close callback for the specified window.\n\n Wrapper for:\n GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _window_close_callback_repository):
previous_callback = _window_close_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWwindowclosefun(cbfun)
_window_close_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowCloseCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_window_refresh_callback(window, cbfun):
'\n Sets the refresh callback for the specified window.\n\n Wrapper for:\n GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _window_refresh_callback_repository):
previous_callback = _window_refresh_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWwindowrefreshfun(cbfun)
_window_refresh_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowRefreshCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_window_focus_callback(window, cbfun):
'\n Sets the focus callback for the specified window.\n\n Wrapper for:\n GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _window_focus_callback_repository):
previous_callback = _window_focus_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWwindowfocusfun(cbfun)
_window_focus_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowFocusCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_window_iconify_callback(window, cbfun):
'\n Sets the iconify callback for the specified window.\n\n Wrapper for:\n GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _window_iconify_callback_repository):
previous_callback = _window_iconify_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWwindowiconifyfun(cbfun)
_window_iconify_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowIconifyCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_framebuffer_size_callback(window, cbfun):
'\n Sets the framebuffer resize callback for the specified window.\n\n Wrapper for:\n GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _framebuffer_size_callback_repository):
previous_callback = _framebuffer_size_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWframebuffersizefun(cbfun)
_framebuffer_size_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetFramebufferSizeCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def poll_events():
'\n Processes all pending events.\n\n Wrapper for:\n void glfwPollEvents(void);\n '
_glfw.glfwPollEvents()
|
def wait_events():
'\n Waits until events are pending and processes them.\n\n Wrapper for:\n void glfwWaitEvents(void);\n '
_glfw.glfwWaitEvents()
|
def get_input_mode(window, mode):
'\n Returns the value of an input option for the specified window.\n\n Wrapper for:\n int glfwGetInputMode(GLFWwindow* window, int mode);\n '
return _glfw.glfwGetInputMode(window, mode)
|
def set_input_mode(window, mode, value):
'\n Sets an input option for the specified window.\n @param[in] window The window whose input mode to set.\n @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or\n `GLFW_STICKY_MOUSE_BUTTONS`.\n @param[in] value The new value of the specified input mode.\n\n Wrapper for:\n void glfwSetInputMode(GLFWwindow* window, int mode, int value);\n '
_glfw.glfwSetInputMode(window, mode, value)
|
def get_key(window, key):
'\n Returns the last reported state of a keyboard key for the specified\n window.\n\n Wrapper for:\n int glfwGetKey(GLFWwindow* window, int key);\n '
return _glfw.glfwGetKey(window, key)
|
def get_mouse_button(window, button):
'\n Returns the last reported state of a mouse button for the specified\n window.\n\n Wrapper for:\n int glfwGetMouseButton(GLFWwindow* window, int button);\n '
return _glfw.glfwGetMouseButton(window, button)
|
def get_cursor_pos(window):
'\n Retrieves the last reported cursor position, relative to the client\n area of the window.\n\n Wrapper for:\n void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos);\n '
xpos_value = ctypes.c_double(0.0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_double(0.0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetCursorPos(window, xpos, ypos)
return (xpos_value.value, ypos_value.value)
|
def set_cursor_pos(window, xpos, ypos):
'\n Sets the position of the cursor, relative to the client area of the window.\n\n Wrapper for:\n void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos);\n '
_glfw.glfwSetCursorPos(window, xpos, ypos)
|
def set_key_callback(window, cbfun):
'\n Sets the key callback.\n\n Wrapper for:\n GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _key_callback_repository):
previous_callback = _key_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWkeyfun(cbfun)
_key_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetKeyCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_char_callback(window, cbfun):
'\n Sets the Unicode character callback.\n\n Wrapper for:\n GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _char_callback_repository):
previous_callback = _char_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWcharfun(cbfun)
_char_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCharCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_mouse_button_callback(window, cbfun):
'\n Sets the mouse button callback.\n\n Wrapper for:\n GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _mouse_button_callback_repository):
previous_callback = _mouse_button_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWmousebuttonfun(cbfun)
_mouse_button_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetMouseButtonCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_cursor_pos_callback(window, cbfun):
'\n Sets the cursor position callback.\n\n Wrapper for:\n GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _cursor_pos_callback_repository):
previous_callback = _cursor_pos_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWcursorposfun(cbfun)
_cursor_pos_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCursorPosCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_cursor_enter_callback(window, cbfun):
'\n Sets the cursor enter/exit callback.\n\n Wrapper for:\n GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _cursor_enter_callback_repository):
previous_callback = _cursor_enter_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWcursorenterfun(cbfun)
_cursor_enter_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCursorEnterCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def set_scroll_callback(window, cbfun):
'\n Sets the scroll callback.\n\n Wrapper for:\n GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun);\n '
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value
if (window_addr in _scroll_callback_repository):
previous_callback = _scroll_callback_repository[window_addr]
else:
previous_callback = None
if (cbfun is None):
cbfun = 0
c_cbfun = _GLFWscrollfun(cbfun)
_scroll_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetScrollCallback(window, cbfun)
if ((previous_callback is not None) and (previous_callback[0] != 0)):
return previous_callback[0]
|
def joystick_present(joy):
'\n Returns whether the specified joystick is present.\n\n Wrapper for:\n int glfwJoystickPresent(int joy);\n '
return _glfw.glfwJoystickPresent(joy)
|
def get_joystick_axes(joy):
'\n Returns the values of all axes of the specified joystick.\n\n Wrapper for:\n const float* glfwGetJoystickAxes(int joy, int* count);\n '
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetJoystickAxes(joy, count)
return (result, count_value.value)
|
def get_joystick_buttons(joy):
'\n Returns the state of all buttons of the specified joystick.\n\n Wrapper for:\n const unsigned char* glfwGetJoystickButtons(int joy, int* count);\n '
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetJoystickButtons(joy, count)
return (result, count_value.value)
|
def get_joystick_name(joy):
'\n Returns the name of the specified joystick.\n\n Wrapper for:\n const char* glfwGetJoystickName(int joy);\n '
return _glfw.glfwGetJoystickName(joy)
|
def set_clipboard_string(window, string):
'\n Sets the clipboard to the specified string.\n\n Wrapper for:\n void glfwSetClipboardString(GLFWwindow* window, const char* string);\n '
_glfw.glfwSetClipboardString(window, _to_char_p(string))
|
def get_clipboard_string(window):
'\n Retrieves the contents of the clipboard as a string.\n\n Wrapper for:\n const char* glfwGetClipboardString(GLFWwindow* window);\n '
return _glfw.glfwGetClipboardString(window)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.