id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
17,500
|
jcrobak/parquet-python
|
parquet/encoding.py
|
read_plain_int96
|
def read_plain_int96(file_obj, count):
"""Read `count` 96-bit ints using the plain encoding."""
items = struct.unpack(b"<" + b"qi" * count, file_obj.read(12 * count))
return [q << 32 | i for (q, i) in zip(items[0::2], items[1::2])]
|
python
|
def read_plain_int96(file_obj, count):
"""Read `count` 96-bit ints using the plain encoding."""
items = struct.unpack(b"<" + b"qi" * count, file_obj.read(12 * count))
return [q << 32 | i for (q, i) in zip(items[0::2], items[1::2])]
|
[
"def",
"read_plain_int96",
"(",
"file_obj",
",",
"count",
")",
":",
"items",
"=",
"struct",
".",
"unpack",
"(",
"b\"<\"",
"+",
"b\"qi\"",
"*",
"count",
",",
"file_obj",
".",
"read",
"(",
"12",
"*",
"count",
")",
")",
"return",
"[",
"q",
"<<",
"32",
"|",
"i",
"for",
"(",
"q",
",",
"i",
")",
"in",
"zip",
"(",
"items",
"[",
"0",
":",
":",
"2",
"]",
",",
"items",
"[",
"1",
":",
":",
"2",
"]",
")",
"]"
] |
Read `count` 96-bit ints using the plain encoding.
|
[
"Read",
"count",
"96",
"-",
"bit",
"ints",
"using",
"the",
"plain",
"encoding",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L51-L54
|
17,501
|
jcrobak/parquet-python
|
parquet/encoding.py
|
read_plain_float
|
def read_plain_float(file_obj, count):
"""Read `count` 32-bit floats using the plain encoding."""
return struct.unpack("<{}f".format(count).encode("utf-8"), file_obj.read(4 * count))
|
python
|
def read_plain_float(file_obj, count):
"""Read `count` 32-bit floats using the plain encoding."""
return struct.unpack("<{}f".format(count).encode("utf-8"), file_obj.read(4 * count))
|
[
"def",
"read_plain_float",
"(",
"file_obj",
",",
"count",
")",
":",
"return",
"struct",
".",
"unpack",
"(",
"\"<{}f\"",
".",
"format",
"(",
"count",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"file_obj",
".",
"read",
"(",
"4",
"*",
"count",
")",
")"
] |
Read `count` 32-bit floats using the plain encoding.
|
[
"Read",
"count",
"32",
"-",
"bit",
"floats",
"using",
"the",
"plain",
"encoding",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L57-L59
|
17,502
|
jcrobak/parquet-python
|
parquet/encoding.py
|
read_plain_byte_array
|
def read_plain_byte_array(file_obj, count):
"""Read `count` byte arrays using the plain encoding."""
return [file_obj.read(struct.unpack(b"<i", file_obj.read(4))[0]) for i in range(count)]
|
python
|
def read_plain_byte_array(file_obj, count):
"""Read `count` byte arrays using the plain encoding."""
return [file_obj.read(struct.unpack(b"<i", file_obj.read(4))[0]) for i in range(count)]
|
[
"def",
"read_plain_byte_array",
"(",
"file_obj",
",",
"count",
")",
":",
"return",
"[",
"file_obj",
".",
"read",
"(",
"struct",
".",
"unpack",
"(",
"b\"<i\"",
",",
"file_obj",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"count",
")",
"]"
] |
Read `count` byte arrays using the plain encoding.
|
[
"Read",
"count",
"byte",
"arrays",
"using",
"the",
"plain",
"encoding",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L67-L69
|
17,503
|
jcrobak/parquet-python
|
parquet/encoding.py
|
read_plain
|
def read_plain(file_obj, type_, count):
"""Read `count` items `type` from the fo using the plain encoding."""
if count == 0:
return []
conv = DECODE_PLAIN[type_]
return conv(file_obj, count)
|
python
|
def read_plain(file_obj, type_, count):
"""Read `count` items `type` from the fo using the plain encoding."""
if count == 0:
return []
conv = DECODE_PLAIN[type_]
return conv(file_obj, count)
|
[
"def",
"read_plain",
"(",
"file_obj",
",",
"type_",
",",
"count",
")",
":",
"if",
"count",
"==",
"0",
":",
"return",
"[",
"]",
"conv",
"=",
"DECODE_PLAIN",
"[",
"type_",
"]",
"return",
"conv",
"(",
"file_obj",
",",
"count",
")"
] |
Read `count` items `type` from the fo using the plain encoding.
|
[
"Read",
"count",
"items",
"type",
"from",
"the",
"fo",
"using",
"the",
"plain",
"encoding",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L89-L94
|
17,504
|
jcrobak/parquet-python
|
parquet/encoding.py
|
read_unsigned_var_int
|
def read_unsigned_var_int(file_obj):
"""Read a value using the unsigned, variable int encoding."""
result = 0
shift = 0
while True:
byte = struct.unpack(b"<B", file_obj.read(1))[0]
result |= ((byte & 0x7F) << shift)
if (byte & 0x80) == 0:
break
shift += 7
return result
|
python
|
def read_unsigned_var_int(file_obj):
"""Read a value using the unsigned, variable int encoding."""
result = 0
shift = 0
while True:
byte = struct.unpack(b"<B", file_obj.read(1))[0]
result |= ((byte & 0x7F) << shift)
if (byte & 0x80) == 0:
break
shift += 7
return result
|
[
"def",
"read_unsigned_var_int",
"(",
"file_obj",
")",
":",
"result",
"=",
"0",
"shift",
"=",
"0",
"while",
"True",
":",
"byte",
"=",
"struct",
".",
"unpack",
"(",
"b\"<B\"",
",",
"file_obj",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"result",
"|=",
"(",
"(",
"byte",
"&",
"0x7F",
")",
"<<",
"shift",
")",
"if",
"(",
"byte",
"&",
"0x80",
")",
"==",
"0",
":",
"break",
"shift",
"+=",
"7",
"return",
"result"
] |
Read a value using the unsigned, variable int encoding.
|
[
"Read",
"a",
"value",
"using",
"the",
"unsigned",
"variable",
"int",
"encoding",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L97-L107
|
17,505
|
jcrobak/parquet-python
|
parquet/encoding.py
|
read_rle
|
def read_rle(file_obj, header, bit_width, debug_logging):
"""Read a run-length encoded run from the given fo with the given header and bit_width.
The count is determined from the header and the width is used to grab the
value that's repeated. Yields the value repeated count times.
"""
count = header >> 1
zero_data = b"\x00\x00\x00\x00"
width = (bit_width + 7) // 8
data = file_obj.read(width)
data = data + zero_data[len(data):]
value = struct.unpack(b"<i", data)[0]
if debug_logging:
logger.debug("Read RLE group with value %s of byte-width %s and count %s",
value, width, count)
for _ in range(count):
yield value
|
python
|
def read_rle(file_obj, header, bit_width, debug_logging):
"""Read a run-length encoded run from the given fo with the given header and bit_width.
The count is determined from the header and the width is used to grab the
value that's repeated. Yields the value repeated count times.
"""
count = header >> 1
zero_data = b"\x00\x00\x00\x00"
width = (bit_width + 7) // 8
data = file_obj.read(width)
data = data + zero_data[len(data):]
value = struct.unpack(b"<i", data)[0]
if debug_logging:
logger.debug("Read RLE group with value %s of byte-width %s and count %s",
value, width, count)
for _ in range(count):
yield value
|
[
"def",
"read_rle",
"(",
"file_obj",
",",
"header",
",",
"bit_width",
",",
"debug_logging",
")",
":",
"count",
"=",
"header",
">>",
"1",
"zero_data",
"=",
"b\"\\x00\\x00\\x00\\x00\"",
"width",
"=",
"(",
"bit_width",
"+",
"7",
")",
"//",
"8",
"data",
"=",
"file_obj",
".",
"read",
"(",
"width",
")",
"data",
"=",
"data",
"+",
"zero_data",
"[",
"len",
"(",
"data",
")",
":",
"]",
"value",
"=",
"struct",
".",
"unpack",
"(",
"b\"<i\"",
",",
"data",
")",
"[",
"0",
"]",
"if",
"debug_logging",
":",
"logger",
".",
"debug",
"(",
"\"Read RLE group with value %s of byte-width %s and count %s\"",
",",
"value",
",",
"width",
",",
"count",
")",
"for",
"_",
"in",
"range",
"(",
"count",
")",
":",
"yield",
"value"
] |
Read a run-length encoded run from the given fo with the given header and bit_width.
The count is determined from the header and the width is used to grab the
value that's repeated. Yields the value repeated count times.
|
[
"Read",
"a",
"run",
"-",
"length",
"encoded",
"run",
"from",
"the",
"given",
"fo",
"with",
"the",
"given",
"header",
"and",
"bit_width",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L110-L126
|
17,506
|
jcrobak/parquet-python
|
parquet/encoding.py
|
read_bitpacked_deprecated
|
def read_bitpacked_deprecated(file_obj, byte_count, count, width, debug_logging):
"""Read `count` values from `fo` using the deprecated bitpacking encoding."""
raw_bytes = array.array(ARRAY_BYTE_STR, file_obj.read(byte_count)).tolist()
mask = _mask_for_bits(width)
index = 0
res = []
word = 0
bits_in_word = 0
while len(res) < count and index <= len(raw_bytes):
if debug_logging:
logger.debug("index = %d", index)
logger.debug("bits in word = %d", bits_in_word)
logger.debug("word = %s", bin(word))
if bits_in_word >= width:
# how many bits over the value is stored
offset = (bits_in_word - width)
# figure out the value
value = (word & (mask << offset)) >> offset
if debug_logging:
logger.debug("offset = %d", offset)
logger.debug("value = %d (%s)", value, bin(value))
res.append(value)
bits_in_word -= width
else:
word = (word << 8) | raw_bytes[index]
index += 1
bits_in_word += 8
return res
|
python
|
def read_bitpacked_deprecated(file_obj, byte_count, count, width, debug_logging):
"""Read `count` values from `fo` using the deprecated bitpacking encoding."""
raw_bytes = array.array(ARRAY_BYTE_STR, file_obj.read(byte_count)).tolist()
mask = _mask_for_bits(width)
index = 0
res = []
word = 0
bits_in_word = 0
while len(res) < count and index <= len(raw_bytes):
if debug_logging:
logger.debug("index = %d", index)
logger.debug("bits in word = %d", bits_in_word)
logger.debug("word = %s", bin(word))
if bits_in_word >= width:
# how many bits over the value is stored
offset = (bits_in_word - width)
# figure out the value
value = (word & (mask << offset)) >> offset
if debug_logging:
logger.debug("offset = %d", offset)
logger.debug("value = %d (%s)", value, bin(value))
res.append(value)
bits_in_word -= width
else:
word = (word << 8) | raw_bytes[index]
index += 1
bits_in_word += 8
return res
|
[
"def",
"read_bitpacked_deprecated",
"(",
"file_obj",
",",
"byte_count",
",",
"count",
",",
"width",
",",
"debug_logging",
")",
":",
"raw_bytes",
"=",
"array",
".",
"array",
"(",
"ARRAY_BYTE_STR",
",",
"file_obj",
".",
"read",
"(",
"byte_count",
")",
")",
".",
"tolist",
"(",
")",
"mask",
"=",
"_mask_for_bits",
"(",
"width",
")",
"index",
"=",
"0",
"res",
"=",
"[",
"]",
"word",
"=",
"0",
"bits_in_word",
"=",
"0",
"while",
"len",
"(",
"res",
")",
"<",
"count",
"and",
"index",
"<=",
"len",
"(",
"raw_bytes",
")",
":",
"if",
"debug_logging",
":",
"logger",
".",
"debug",
"(",
"\"index = %d\"",
",",
"index",
")",
"logger",
".",
"debug",
"(",
"\"bits in word = %d\"",
",",
"bits_in_word",
")",
"logger",
".",
"debug",
"(",
"\"word = %s\"",
",",
"bin",
"(",
"word",
")",
")",
"if",
"bits_in_word",
">=",
"width",
":",
"# how many bits over the value is stored",
"offset",
"=",
"(",
"bits_in_word",
"-",
"width",
")",
"# figure out the value",
"value",
"=",
"(",
"word",
"&",
"(",
"mask",
"<<",
"offset",
")",
")",
">>",
"offset",
"if",
"debug_logging",
":",
"logger",
".",
"debug",
"(",
"\"offset = %d\"",
",",
"offset",
")",
"logger",
".",
"debug",
"(",
"\"value = %d (%s)\"",
",",
"value",
",",
"bin",
"(",
"value",
")",
")",
"res",
".",
"append",
"(",
"value",
")",
"bits_in_word",
"-=",
"width",
"else",
":",
"word",
"=",
"(",
"word",
"<<",
"8",
")",
"|",
"raw_bytes",
"[",
"index",
"]",
"index",
"+=",
"1",
"bits_in_word",
"+=",
"8",
"return",
"res"
] |
Read `count` values from `fo` using the deprecated bitpacking encoding.
|
[
"Read",
"count",
"values",
"from",
"fo",
"using",
"the",
"deprecated",
"bitpacking",
"encoding",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L183-L213
|
17,507
|
jcrobak/parquet-python
|
parquet/converted_types.py
|
_convert_unsigned
|
def _convert_unsigned(data, fmt):
"""Convert data from signed to unsigned in bulk."""
num = len(data)
return struct.unpack(
"{}{}".format(num, fmt.upper()).encode("utf-8"),
struct.pack("{}{}".format(num, fmt).encode("utf-8"), *data)
)
|
python
|
def _convert_unsigned(data, fmt):
"""Convert data from signed to unsigned in bulk."""
num = len(data)
return struct.unpack(
"{}{}".format(num, fmt.upper()).encode("utf-8"),
struct.pack("{}{}".format(num, fmt).encode("utf-8"), *data)
)
|
[
"def",
"_convert_unsigned",
"(",
"data",
",",
"fmt",
")",
":",
"num",
"=",
"len",
"(",
"data",
")",
"return",
"struct",
".",
"unpack",
"(",
"\"{}{}\"",
".",
"format",
"(",
"num",
",",
"fmt",
".",
"upper",
"(",
")",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"struct",
".",
"pack",
"(",
"\"{}{}\"",
".",
"format",
"(",
"num",
",",
"fmt",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"*",
"data",
")",
")"
] |
Convert data from signed to unsigned in bulk.
|
[
"Convert",
"data",
"from",
"signed",
"to",
"unsigned",
"in",
"bulk",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/converted_types.py#L52-L58
|
17,508
|
jcrobak/parquet-python
|
parquet/converted_types.py
|
convert_column
|
def convert_column(data, schemae):
"""Convert known types from primitive to rich."""
ctype = schemae.converted_type
if ctype == parquet_thrift.ConvertedType.DECIMAL:
scale_factor = Decimal("10e-{}".format(schemae.scale))
if schemae.type == parquet_thrift.Type.INT32 or schemae.type == parquet_thrift.Type.INT64:
return [Decimal(unscaled) * scale_factor for unscaled in data]
return [Decimal(intbig(unscaled)) * scale_factor for unscaled in data]
elif ctype == parquet_thrift.ConvertedType.DATE:
return [datetime.date.fromordinal(d) for d in data]
elif ctype == parquet_thrift.ConvertedType.TIME_MILLIS:
return [datetime.timedelta(milliseconds=d) for d in data]
elif ctype == parquet_thrift.ConvertedType.TIMESTAMP_MILLIS:
return [datetime.datetime.utcfromtimestamp(d / 1000.0) for d in data]
elif ctype == parquet_thrift.ConvertedType.UTF8:
return [codecs.decode(item, "utf-8") for item in data]
elif ctype == parquet_thrift.ConvertedType.UINT_8:
return _convert_unsigned(data, 'b')
elif ctype == parquet_thrift.ConvertedType.UINT_16:
return _convert_unsigned(data, 'h')
elif ctype == parquet_thrift.ConvertedType.UINT_32:
return _convert_unsigned(data, 'i')
elif ctype == parquet_thrift.ConvertedType.UINT_64:
return _convert_unsigned(data, 'q')
elif ctype == parquet_thrift.ConvertedType.JSON:
return [json.loads(s) for s in codecs.iterdecode(data, "utf-8")]
elif ctype == parquet_thrift.ConvertedType.BSON and bson:
return [bson.BSON(s).decode() for s in data]
else:
logger.info("Converted type '%s'' not handled",
parquet_thrift.ConvertedType._VALUES_TO_NAMES[ctype]) # pylint:disable=protected-access
return data
|
python
|
def convert_column(data, schemae):
"""Convert known types from primitive to rich."""
ctype = schemae.converted_type
if ctype == parquet_thrift.ConvertedType.DECIMAL:
scale_factor = Decimal("10e-{}".format(schemae.scale))
if schemae.type == parquet_thrift.Type.INT32 or schemae.type == parquet_thrift.Type.INT64:
return [Decimal(unscaled) * scale_factor for unscaled in data]
return [Decimal(intbig(unscaled)) * scale_factor for unscaled in data]
elif ctype == parquet_thrift.ConvertedType.DATE:
return [datetime.date.fromordinal(d) for d in data]
elif ctype == parquet_thrift.ConvertedType.TIME_MILLIS:
return [datetime.timedelta(milliseconds=d) for d in data]
elif ctype == parquet_thrift.ConvertedType.TIMESTAMP_MILLIS:
return [datetime.datetime.utcfromtimestamp(d / 1000.0) for d in data]
elif ctype == parquet_thrift.ConvertedType.UTF8:
return [codecs.decode(item, "utf-8") for item in data]
elif ctype == parquet_thrift.ConvertedType.UINT_8:
return _convert_unsigned(data, 'b')
elif ctype == parquet_thrift.ConvertedType.UINT_16:
return _convert_unsigned(data, 'h')
elif ctype == parquet_thrift.ConvertedType.UINT_32:
return _convert_unsigned(data, 'i')
elif ctype == parquet_thrift.ConvertedType.UINT_64:
return _convert_unsigned(data, 'q')
elif ctype == parquet_thrift.ConvertedType.JSON:
return [json.loads(s) for s in codecs.iterdecode(data, "utf-8")]
elif ctype == parquet_thrift.ConvertedType.BSON and bson:
return [bson.BSON(s).decode() for s in data]
else:
logger.info("Converted type '%s'' not handled",
parquet_thrift.ConvertedType._VALUES_TO_NAMES[ctype]) # pylint:disable=protected-access
return data
|
[
"def",
"convert_column",
"(",
"data",
",",
"schemae",
")",
":",
"ctype",
"=",
"schemae",
".",
"converted_type",
"if",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"DECIMAL",
":",
"scale_factor",
"=",
"Decimal",
"(",
"\"10e-{}\"",
".",
"format",
"(",
"schemae",
".",
"scale",
")",
")",
"if",
"schemae",
".",
"type",
"==",
"parquet_thrift",
".",
"Type",
".",
"INT32",
"or",
"schemae",
".",
"type",
"==",
"parquet_thrift",
".",
"Type",
".",
"INT64",
":",
"return",
"[",
"Decimal",
"(",
"unscaled",
")",
"*",
"scale_factor",
"for",
"unscaled",
"in",
"data",
"]",
"return",
"[",
"Decimal",
"(",
"intbig",
"(",
"unscaled",
")",
")",
"*",
"scale_factor",
"for",
"unscaled",
"in",
"data",
"]",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"DATE",
":",
"return",
"[",
"datetime",
".",
"date",
".",
"fromordinal",
"(",
"d",
")",
"for",
"d",
"in",
"data",
"]",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"TIME_MILLIS",
":",
"return",
"[",
"datetime",
".",
"timedelta",
"(",
"milliseconds",
"=",
"d",
")",
"for",
"d",
"in",
"data",
"]",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"TIMESTAMP_MILLIS",
":",
"return",
"[",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"d",
"/",
"1000.0",
")",
"for",
"d",
"in",
"data",
"]",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"UTF8",
":",
"return",
"[",
"codecs",
".",
"decode",
"(",
"item",
",",
"\"utf-8\"",
")",
"for",
"item",
"in",
"data",
"]",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"UINT_8",
":",
"return",
"_convert_unsigned",
"(",
"data",
",",
"'b'",
")",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"UINT_16",
":",
"return",
"_convert_unsigned",
"(",
"data",
",",
"'h'",
")",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"UINT_32",
":",
"return",
"_convert_unsigned",
"(",
"data",
",",
"'i'",
")",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"UINT_64",
":",
"return",
"_convert_unsigned",
"(",
"data",
",",
"'q'",
")",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"JSON",
":",
"return",
"[",
"json",
".",
"loads",
"(",
"s",
")",
"for",
"s",
"in",
"codecs",
".",
"iterdecode",
"(",
"data",
",",
"\"utf-8\"",
")",
"]",
"elif",
"ctype",
"==",
"parquet_thrift",
".",
"ConvertedType",
".",
"BSON",
"and",
"bson",
":",
"return",
"[",
"bson",
".",
"BSON",
"(",
"s",
")",
".",
"decode",
"(",
")",
"for",
"s",
"in",
"data",
"]",
"else",
":",
"logger",
".",
"info",
"(",
"\"Converted type '%s'' not handled\"",
",",
"parquet_thrift",
".",
"ConvertedType",
".",
"_VALUES_TO_NAMES",
"[",
"ctype",
"]",
")",
"# pylint:disable=protected-access",
"return",
"data"
] |
Convert known types from primitive to rich.
|
[
"Convert",
"known",
"types",
"from",
"primitive",
"to",
"rich",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/converted_types.py#L61-L92
|
17,509
|
jcrobak/parquet-python
|
parquet/__main__.py
|
setup_logging
|
def setup_logging(options=None):
"""Configure logging based on options."""
level = logging.DEBUG if options is not None and options.debug \
else logging.WARNING
console = logging.StreamHandler()
console.setLevel(level)
formatter = logging.Formatter('%(name)s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('parquet').setLevel(level)
logging.getLogger('parquet').addHandler(console)
|
python
|
def setup_logging(options=None):
"""Configure logging based on options."""
level = logging.DEBUG if options is not None and options.debug \
else logging.WARNING
console = logging.StreamHandler()
console.setLevel(level)
formatter = logging.Formatter('%(name)s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('parquet').setLevel(level)
logging.getLogger('parquet').addHandler(console)
|
[
"def",
"setup_logging",
"(",
"options",
"=",
"None",
")",
":",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"options",
"is",
"not",
"None",
"and",
"options",
".",
"debug",
"else",
"logging",
".",
"WARNING",
"console",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"console",
".",
"setLevel",
"(",
"level",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(name)s: %(levelname)-8s %(message)s'",
")",
"console",
".",
"setFormatter",
"(",
"formatter",
")",
"logging",
".",
"getLogger",
"(",
"'parquet'",
")",
".",
"setLevel",
"(",
"level",
")",
"logging",
".",
"getLogger",
"(",
"'parquet'",
")",
".",
"addHandler",
"(",
"console",
")"
] |
Configure logging based on options.
|
[
"Configure",
"logging",
"based",
"on",
"options",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__main__.py#L13-L22
|
17,510
|
jcrobak/parquet-python
|
parquet/__main__.py
|
main
|
def main(argv=None):
"""Run parquet utility application."""
argv = argv or sys.argv[1:]
parser = argparse.ArgumentParser('parquet',
description='Read parquet files')
parser.add_argument('--metadata', action='store_true',
help='show metadata on file')
parser.add_argument('--row-group-metadata', action='store_true',
help="show per row group metadata")
parser.add_argument('--no-data', action='store_true',
help="don't dump any data from the file")
parser.add_argument('--limit', action='store', type=int, default=-1,
help='max records to output')
parser.add_argument('--col', action='append', type=str,
help='only include this column (can be '
'specified multiple times)')
parser.add_argument('--no-headers', action='store_true',
help='skip headers in output (only applies if '
'format=csv)')
parser.add_argument('--format', action='store', type=str, default='csv',
help='format for the output data. can be csv or json.')
parser.add_argument('--debug', action='store_true',
help='log debug info to stderr')
parser.add_argument('file',
help='path to the file to parse')
args = parser.parse_args(argv)
setup_logging(args)
import parquet
if args.metadata:
parquet.dump_metadata(args.file, args.row_group_metadata)
if not args.no_data:
parquet.dump(args.file, args)
|
python
|
def main(argv=None):
"""Run parquet utility application."""
argv = argv or sys.argv[1:]
parser = argparse.ArgumentParser('parquet',
description='Read parquet files')
parser.add_argument('--metadata', action='store_true',
help='show metadata on file')
parser.add_argument('--row-group-metadata', action='store_true',
help="show per row group metadata")
parser.add_argument('--no-data', action='store_true',
help="don't dump any data from the file")
parser.add_argument('--limit', action='store', type=int, default=-1,
help='max records to output')
parser.add_argument('--col', action='append', type=str,
help='only include this column (can be '
'specified multiple times)')
parser.add_argument('--no-headers', action='store_true',
help='skip headers in output (only applies if '
'format=csv)')
parser.add_argument('--format', action='store', type=str, default='csv',
help='format for the output data. can be csv or json.')
parser.add_argument('--debug', action='store_true',
help='log debug info to stderr')
parser.add_argument('file',
help='path to the file to parse')
args = parser.parse_args(argv)
setup_logging(args)
import parquet
if args.metadata:
parquet.dump_metadata(args.file, args.row_group_metadata)
if not args.no_data:
parquet.dump(args.file, args)
|
[
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"argv",
"=",
"argv",
"or",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"'parquet'",
",",
"description",
"=",
"'Read parquet files'",
")",
"parser",
".",
"add_argument",
"(",
"'--metadata'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'show metadata on file'",
")",
"parser",
".",
"add_argument",
"(",
"'--row-group-metadata'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"show per row group metadata\"",
")",
"parser",
".",
"add_argument",
"(",
"'--no-data'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"don't dump any data from the file\"",
")",
"parser",
".",
"add_argument",
"(",
"'--limit'",
",",
"action",
"=",
"'store'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"-",
"1",
",",
"help",
"=",
"'max records to output'",
")",
"parser",
".",
"add_argument",
"(",
"'--col'",
",",
"action",
"=",
"'append'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'only include this column (can be '",
"'specified multiple times)'",
")",
"parser",
".",
"add_argument",
"(",
"'--no-headers'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'skip headers in output (only applies if '",
"'format=csv)'",
")",
"parser",
".",
"add_argument",
"(",
"'--format'",
",",
"action",
"=",
"'store'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'csv'",
",",
"help",
"=",
"'format for the output data. can be csv or json.'",
")",
"parser",
".",
"add_argument",
"(",
"'--debug'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'log debug info to stderr'",
")",
"parser",
".",
"add_argument",
"(",
"'file'",
",",
"help",
"=",
"'path to the file to parse'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
")",
"setup_logging",
"(",
"args",
")",
"import",
"parquet",
"if",
"args",
".",
"metadata",
":",
"parquet",
".",
"dump_metadata",
"(",
"args",
".",
"file",
",",
"args",
".",
"row_group_metadata",
")",
"if",
"not",
"args",
".",
"no_data",
":",
"parquet",
".",
"dump",
"(",
"args",
".",
"file",
",",
"args",
")"
] |
Run parquet utility application.
|
[
"Run",
"parquet",
"utility",
"application",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__main__.py#L25-L61
|
17,511
|
jcrobak/parquet-python
|
parquet/schema.py
|
SchemaHelper.is_required
|
def is_required(self, name):
"""Return true iff the schema element with the given name is required."""
return self.schema_element(name).repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED
|
python
|
def is_required(self, name):
"""Return true iff the schema element with the given name is required."""
return self.schema_element(name).repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED
|
[
"def",
"is_required",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"schema_element",
"(",
"name",
")",
".",
"repetition_type",
"==",
"parquet_thrift",
".",
"FieldRepetitionType",
".",
"REQUIRED"
] |
Return true iff the schema element with the given name is required.
|
[
"Return",
"true",
"iff",
"the",
"schema",
"element",
"with",
"the",
"given",
"name",
"is",
"required",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/schema.py#L30-L32
|
17,512
|
jcrobak/parquet-python
|
parquet/schema.py
|
SchemaHelper.max_repetition_level
|
def max_repetition_level(self, path):
"""Get the max repetition level for the given schema path."""
max_level = 0
for part in path:
element = self.schema_element(part)
if element.repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED:
max_level += 1
return max_level
|
python
|
def max_repetition_level(self, path):
"""Get the max repetition level for the given schema path."""
max_level = 0
for part in path:
element = self.schema_element(part)
if element.repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED:
max_level += 1
return max_level
|
[
"def",
"max_repetition_level",
"(",
"self",
",",
"path",
")",
":",
"max_level",
"=",
"0",
"for",
"part",
"in",
"path",
":",
"element",
"=",
"self",
".",
"schema_element",
"(",
"part",
")",
"if",
"element",
".",
"repetition_type",
"==",
"parquet_thrift",
".",
"FieldRepetitionType",
".",
"REQUIRED",
":",
"max_level",
"+=",
"1",
"return",
"max_level"
] |
Get the max repetition level for the given schema path.
|
[
"Get",
"the",
"max",
"repetition",
"level",
"for",
"the",
"given",
"schema",
"path",
"."
] |
e2caab7aceca91a3075998d0113e186f8ba2ca37
|
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/schema.py#L34-L41
|
17,513
|
joke2k/django-faker
|
django_faker/populator.py
|
Populator.execute
|
def execute(self, using=None):
"""
Populate the database using all the Entity classes previously added.
:param using A Django database connection name
:rtype: A list of the inserted PKs
"""
if not using:
using = self.getConnection()
insertedEntities = {}
for klass in self.orders:
number = self.quantities[klass]
if klass not in insertedEntities:
insertedEntities[klass] = []
for i in range(0,number):
insertedEntities[klass].append( self.entities[klass].execute(using, insertedEntities) )
return insertedEntities
|
python
|
def execute(self, using=None):
"""
Populate the database using all the Entity classes previously added.
:param using A Django database connection name
:rtype: A list of the inserted PKs
"""
if not using:
using = self.getConnection()
insertedEntities = {}
for klass in self.orders:
number = self.quantities[klass]
if klass not in insertedEntities:
insertedEntities[klass] = []
for i in range(0,number):
insertedEntities[klass].append( self.entities[klass].execute(using, insertedEntities) )
return insertedEntities
|
[
"def",
"execute",
"(",
"self",
",",
"using",
"=",
"None",
")",
":",
"if",
"not",
"using",
":",
"using",
"=",
"self",
".",
"getConnection",
"(",
")",
"insertedEntities",
"=",
"{",
"}",
"for",
"klass",
"in",
"self",
".",
"orders",
":",
"number",
"=",
"self",
".",
"quantities",
"[",
"klass",
"]",
"if",
"klass",
"not",
"in",
"insertedEntities",
":",
"insertedEntities",
"[",
"klass",
"]",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"number",
")",
":",
"insertedEntities",
"[",
"klass",
"]",
".",
"append",
"(",
"self",
".",
"entities",
"[",
"klass",
"]",
".",
"execute",
"(",
"using",
",",
"insertedEntities",
")",
")",
"return",
"insertedEntities"
] |
Populate the database using all the Entity classes previously added.
:param using A Django database connection name
:rtype: A list of the inserted PKs
|
[
"Populate",
"the",
"database",
"using",
"all",
"the",
"Entity",
"classes",
"previously",
"added",
"."
] |
345e3eebcf636e2566d9890ae7b35788ebdb5173
|
https://github.com/joke2k/django-faker/blob/345e3eebcf636e2566d9890ae7b35788ebdb5173/django_faker/populator.py#L147-L165
|
17,514
|
joke2k/django-faker
|
django_faker/__init__.py
|
Faker.getGenerator
|
def getGenerator(cls, locale=None, providers=None, codename=None):
"""
use a codename to cache generators
"""
codename = codename or cls.getCodename(locale, providers)
if codename not in cls.generators:
from faker import Faker as FakerGenerator
# initialize with faker.generator.Generator instance
# and remember in cache
cls.generators[codename] = FakerGenerator( locale, providers )
cls.generators[codename].seed( cls.generators[codename].randomInt() )
return cls.generators[codename]
|
python
|
def getGenerator(cls, locale=None, providers=None, codename=None):
"""
use a codename to cache generators
"""
codename = codename or cls.getCodename(locale, providers)
if codename not in cls.generators:
from faker import Faker as FakerGenerator
# initialize with faker.generator.Generator instance
# and remember in cache
cls.generators[codename] = FakerGenerator( locale, providers )
cls.generators[codename].seed( cls.generators[codename].randomInt() )
return cls.generators[codename]
|
[
"def",
"getGenerator",
"(",
"cls",
",",
"locale",
"=",
"None",
",",
"providers",
"=",
"None",
",",
"codename",
"=",
"None",
")",
":",
"codename",
"=",
"codename",
"or",
"cls",
".",
"getCodename",
"(",
"locale",
",",
"providers",
")",
"if",
"codename",
"not",
"in",
"cls",
".",
"generators",
":",
"from",
"faker",
"import",
"Faker",
"as",
"FakerGenerator",
"# initialize with faker.generator.Generator instance",
"# and remember in cache",
"cls",
".",
"generators",
"[",
"codename",
"]",
"=",
"FakerGenerator",
"(",
"locale",
",",
"providers",
")",
"cls",
".",
"generators",
"[",
"codename",
"]",
".",
"seed",
"(",
"cls",
".",
"generators",
"[",
"codename",
"]",
".",
"randomInt",
"(",
")",
")",
"return",
"cls",
".",
"generators",
"[",
"codename",
"]"
] |
use a codename to cache generators
|
[
"use",
"a",
"codename",
"to",
"cache",
"generators"
] |
345e3eebcf636e2566d9890ae7b35788ebdb5173
|
https://github.com/joke2k/django-faker/blob/345e3eebcf636e2566d9890ae7b35788ebdb5173/django_faker/__init__.py#L48-L62
|
17,515
|
brandonxiang/geojson-python-utils
|
geojson_utils/geojson_utils.py
|
_point_in_bbox
|
def _point_in_bbox(point, bounds):
"""
valid whether the point is inside the bounding box
"""
return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] > bounds[2]
or point['coordinates'][0] < bounds[1] or point['coordinates'][0] > bounds[3])
|
python
|
def _point_in_bbox(point, bounds):
"""
valid whether the point is inside the bounding box
"""
return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] > bounds[2]
or point['coordinates'][0] < bounds[1] or point['coordinates'][0] > bounds[3])
|
[
"def",
"_point_in_bbox",
"(",
"point",
",",
"bounds",
")",
":",
"return",
"not",
"(",
"point",
"[",
"'coordinates'",
"]",
"[",
"1",
"]",
"<",
"bounds",
"[",
"0",
"]",
"or",
"point",
"[",
"'coordinates'",
"]",
"[",
"1",
"]",
">",
"bounds",
"[",
"2",
"]",
"or",
"point",
"[",
"'coordinates'",
"]",
"[",
"0",
"]",
"<",
"bounds",
"[",
"1",
"]",
"or",
"point",
"[",
"'coordinates'",
"]",
"[",
"0",
"]",
">",
"bounds",
"[",
"3",
"]",
")"
] |
valid whether the point is inside the bounding box
|
[
"valid",
"whether",
"the",
"point",
"is",
"inside",
"the",
"bounding",
"box"
] |
33d0dcd5f16e0567b48c0d49fd292a4f1db16b41
|
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L56-L61
|
17,516
|
brandonxiang/geojson-python-utils
|
geojson_utils/geojson_utils.py
|
point_in_polygon
|
def point_in_polygon(point, poly):
"""
valid whether the point is located in a polygon
Keyword arguments:
point -- point geojson object
poly -- polygon geojson object
if(point inside poly) return true else false
"""
coords = [poly['coordinates']] if poly[
'type'] == 'Polygon' else poly['coordinates']
return _point_in_polygon(point, coords)
|
python
|
def point_in_polygon(point, poly):
"""
valid whether the point is located in a polygon
Keyword arguments:
point -- point geojson object
poly -- polygon geojson object
if(point inside poly) return true else false
"""
coords = [poly['coordinates']] if poly[
'type'] == 'Polygon' else poly['coordinates']
return _point_in_polygon(point, coords)
|
[
"def",
"point_in_polygon",
"(",
"point",
",",
"poly",
")",
":",
"coords",
"=",
"[",
"poly",
"[",
"'coordinates'",
"]",
"]",
"if",
"poly",
"[",
"'type'",
"]",
"==",
"'Polygon'",
"else",
"poly",
"[",
"'coordinates'",
"]",
"return",
"_point_in_polygon",
"(",
"point",
",",
"coords",
")"
] |
valid whether the point is located in a polygon
Keyword arguments:
point -- point geojson object
poly -- polygon geojson object
if(point inside poly) return true else false
|
[
"valid",
"whether",
"the",
"point",
"is",
"located",
"in",
"a",
"polygon"
] |
33d0dcd5f16e0567b48c0d49fd292a4f1db16b41
|
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L111-L123
|
17,517
|
brandonxiang/geojson-python-utils
|
geojson_utils/geojson_utils.py
|
draw_circle
|
def draw_circle(radius_in_meters, center_point, steps=15):
"""
get a circle shape polygon based on centerPoint and radius
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
if(point inside multipoly) return true else false
"""
steps = steps if steps > 15 else 15
center = [center_point['coordinates'][1], center_point['coordinates'][0]]
dist = (radius_in_meters / 1000) / 6371
# convert meters to radiant
rad_center = [number2radius(center[0]), number2radius(center[1])]
# 15 sided circle
poly = []
for step in range(0, steps):
brng = 2 * math.pi * step / steps
lat = math.asin(math.sin(rad_center[0]) * math.cos(dist) +
math.cos(rad_center[0]) * math.sin(dist) * math.cos(brng))
lng = rad_center[1] + math.atan2(math.sin(brng) * math.sin(dist)
* math.cos(rad_center[0]), math.cos(dist) - math.sin(rad_center[0]) * math.sin(lat))
poly.append([number2degree(lng), number2degree(lat)])
return {"type": "Polygon", "coordinates": [poly]}
|
python
|
def draw_circle(radius_in_meters, center_point, steps=15):
"""
get a circle shape polygon based on centerPoint and radius
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
if(point inside multipoly) return true else false
"""
steps = steps if steps > 15 else 15
center = [center_point['coordinates'][1], center_point['coordinates'][0]]
dist = (radius_in_meters / 1000) / 6371
# convert meters to radiant
rad_center = [number2radius(center[0]), number2radius(center[1])]
# 15 sided circle
poly = []
for step in range(0, steps):
brng = 2 * math.pi * step / steps
lat = math.asin(math.sin(rad_center[0]) * math.cos(dist) +
math.cos(rad_center[0]) * math.sin(dist) * math.cos(brng))
lng = rad_center[1] + math.atan2(math.sin(brng) * math.sin(dist)
* math.cos(rad_center[0]), math.cos(dist) - math.sin(rad_center[0]) * math.sin(lat))
poly.append([number2degree(lng), number2degree(lat)])
return {"type": "Polygon", "coordinates": [poly]}
|
[
"def",
"draw_circle",
"(",
"radius_in_meters",
",",
"center_point",
",",
"steps",
"=",
"15",
")",
":",
"steps",
"=",
"steps",
"if",
"steps",
">",
"15",
"else",
"15",
"center",
"=",
"[",
"center_point",
"[",
"'coordinates'",
"]",
"[",
"1",
"]",
",",
"center_point",
"[",
"'coordinates'",
"]",
"[",
"0",
"]",
"]",
"dist",
"=",
"(",
"radius_in_meters",
"/",
"1000",
")",
"/",
"6371",
"# convert meters to radiant",
"rad_center",
"=",
"[",
"number2radius",
"(",
"center",
"[",
"0",
"]",
")",
",",
"number2radius",
"(",
"center",
"[",
"1",
"]",
")",
"]",
"# 15 sided circle",
"poly",
"=",
"[",
"]",
"for",
"step",
"in",
"range",
"(",
"0",
",",
"steps",
")",
":",
"brng",
"=",
"2",
"*",
"math",
".",
"pi",
"*",
"step",
"/",
"steps",
"lat",
"=",
"math",
".",
"asin",
"(",
"math",
".",
"sin",
"(",
"rad_center",
"[",
"0",
"]",
")",
"*",
"math",
".",
"cos",
"(",
"dist",
")",
"+",
"math",
".",
"cos",
"(",
"rad_center",
"[",
"0",
"]",
")",
"*",
"math",
".",
"sin",
"(",
"dist",
")",
"*",
"math",
".",
"cos",
"(",
"brng",
")",
")",
"lng",
"=",
"rad_center",
"[",
"1",
"]",
"+",
"math",
".",
"atan2",
"(",
"math",
".",
"sin",
"(",
"brng",
")",
"*",
"math",
".",
"sin",
"(",
"dist",
")",
"*",
"math",
".",
"cos",
"(",
"rad_center",
"[",
"0",
"]",
")",
",",
"math",
".",
"cos",
"(",
"dist",
")",
"-",
"math",
".",
"sin",
"(",
"rad_center",
"[",
"0",
"]",
")",
"*",
"math",
".",
"sin",
"(",
"lat",
")",
")",
"poly",
".",
"append",
"(",
"[",
"number2degree",
"(",
"lng",
")",
",",
"number2degree",
"(",
"lat",
")",
"]",
")",
"return",
"{",
"\"type\"",
":",
"\"Polygon\"",
",",
"\"coordinates\"",
":",
"[",
"poly",
"]",
"}"
] |
get a circle shape polygon based on centerPoint and radius
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
if(point inside multipoly) return true else false
|
[
"get",
"a",
"circle",
"shape",
"polygon",
"based",
"on",
"centerPoint",
"and",
"radius"
] |
33d0dcd5f16e0567b48c0d49fd292a4f1db16b41
|
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L170-L194
|
17,518
|
brandonxiang/geojson-python-utils
|
geojson_utils/geojson_utils.py
|
rectangle_centroid
|
def rectangle_centroid(rectangle):
"""
get the centroid of the rectangle
Keyword arguments:
rectangle -- polygon geojson object
return centroid
"""
bbox = rectangle['coordinates'][0]
xmin = bbox[0][0]
ymin = bbox[0][1]
xmax = bbox[2][0]
ymax = bbox[2][1]
xwidth = xmax - xmin
ywidth = ymax - ymin
return {'type': 'Point', 'coordinates': [xmin + xwidth / 2, ymin + ywidth / 2]}
|
python
|
def rectangle_centroid(rectangle):
"""
get the centroid of the rectangle
Keyword arguments:
rectangle -- polygon geojson object
return centroid
"""
bbox = rectangle['coordinates'][0]
xmin = bbox[0][0]
ymin = bbox[0][1]
xmax = bbox[2][0]
ymax = bbox[2][1]
xwidth = xmax - xmin
ywidth = ymax - ymin
return {'type': 'Point', 'coordinates': [xmin + xwidth / 2, ymin + ywidth / 2]}
|
[
"def",
"rectangle_centroid",
"(",
"rectangle",
")",
":",
"bbox",
"=",
"rectangle",
"[",
"'coordinates'",
"]",
"[",
"0",
"]",
"xmin",
"=",
"bbox",
"[",
"0",
"]",
"[",
"0",
"]",
"ymin",
"=",
"bbox",
"[",
"0",
"]",
"[",
"1",
"]",
"xmax",
"=",
"bbox",
"[",
"2",
"]",
"[",
"0",
"]",
"ymax",
"=",
"bbox",
"[",
"2",
"]",
"[",
"1",
"]",
"xwidth",
"=",
"xmax",
"-",
"xmin",
"ywidth",
"=",
"ymax",
"-",
"ymin",
"return",
"{",
"'type'",
":",
"'Point'",
",",
"'coordinates'",
":",
"[",
"xmin",
"+",
"xwidth",
"/",
"2",
",",
"ymin",
"+",
"ywidth",
"/",
"2",
"]",
"}"
] |
get the centroid of the rectangle
Keyword arguments:
rectangle -- polygon geojson object
return centroid
|
[
"get",
"the",
"centroid",
"of",
"the",
"rectangle"
] |
33d0dcd5f16e0567b48c0d49fd292a4f1db16b41
|
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L197-L213
|
17,519
|
brandonxiang/geojson-python-utils
|
geojson_utils/geojson_utils.py
|
geometry_within_radius
|
def geometry_within_radius(geometry, center, radius):
"""
To valid whether point or linestring or polygon is inside a radius around a center
Keyword arguments:
geometry -- point/linstring/polygon geojson object
center -- point geojson object
radius -- radius
if(geometry inside radius) return true else false
"""
if geometry['type'] == 'Point':
return point_distance(geometry, center) <= radius
elif geometry['type'] == 'LineString' or geometry['type'] == 'Polygon':
point = {}
# it's enough to check the exterior ring of the Polygon
coordinates = geometry['coordinates'][0] if geometry['type'] == 'Polygon' else geometry['coordinates']
for coordinate in coordinates:
point['coordinates'] = coordinate
if point_distance(point, center) > radius:
return False
return True
|
python
|
def geometry_within_radius(geometry, center, radius):
"""
To valid whether point or linestring or polygon is inside a radius around a center
Keyword arguments:
geometry -- point/linstring/polygon geojson object
center -- point geojson object
radius -- radius
if(geometry inside radius) return true else false
"""
if geometry['type'] == 'Point':
return point_distance(geometry, center) <= radius
elif geometry['type'] == 'LineString' or geometry['type'] == 'Polygon':
point = {}
# it's enough to check the exterior ring of the Polygon
coordinates = geometry['coordinates'][0] if geometry['type'] == 'Polygon' else geometry['coordinates']
for coordinate in coordinates:
point['coordinates'] = coordinate
if point_distance(point, center) > radius:
return False
return True
|
[
"def",
"geometry_within_radius",
"(",
"geometry",
",",
"center",
",",
"radius",
")",
":",
"if",
"geometry",
"[",
"'type'",
"]",
"==",
"'Point'",
":",
"return",
"point_distance",
"(",
"geometry",
",",
"center",
")",
"<=",
"radius",
"elif",
"geometry",
"[",
"'type'",
"]",
"==",
"'LineString'",
"or",
"geometry",
"[",
"'type'",
"]",
"==",
"'Polygon'",
":",
"point",
"=",
"{",
"}",
"# it's enough to check the exterior ring of the Polygon",
"coordinates",
"=",
"geometry",
"[",
"'coordinates'",
"]",
"[",
"0",
"]",
"if",
"geometry",
"[",
"'type'",
"]",
"==",
"'Polygon'",
"else",
"geometry",
"[",
"'coordinates'",
"]",
"for",
"coordinate",
"in",
"coordinates",
":",
"point",
"[",
"'coordinates'",
"]",
"=",
"coordinate",
"if",
"point_distance",
"(",
"point",
",",
"center",
")",
">",
"radius",
":",
"return",
"False",
"return",
"True"
] |
To valid whether point or linestring or polygon is inside a radius around a center
Keyword arguments:
geometry -- point/linstring/polygon geojson object
center -- point geojson object
radius -- radius
if(geometry inside radius) return true else false
|
[
"To",
"valid",
"whether",
"point",
"or",
"linestring",
"or",
"polygon",
"is",
"inside",
"a",
"radius",
"around",
"a",
"center"
] |
33d0dcd5f16e0567b48c0d49fd292a4f1db16b41
|
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L264-L286
|
17,520
|
brandonxiang/geojson-python-utils
|
geojson_utils/geojson_utils.py
|
area
|
def area(poly):
"""
calculate the area of polygon
Keyword arguments:
poly -- polygon geojson object
return polygon area
"""
poly_area = 0
# TODO: polygon holes at coordinates[1]
points = poly['coordinates'][0]
j = len(points) - 1
count = len(points)
for i in range(0, count):
p1_x = points[i][1]
p1_y = points[i][0]
p2_x = points[j][1]
p2_y = points[j][0]
poly_area += p1_x * p2_y
poly_area -= p1_y * p2_x
j = i
poly_area /= 2
return poly_area
|
python
|
def area(poly):
"""
calculate the area of polygon
Keyword arguments:
poly -- polygon geojson object
return polygon area
"""
poly_area = 0
# TODO: polygon holes at coordinates[1]
points = poly['coordinates'][0]
j = len(points) - 1
count = len(points)
for i in range(0, count):
p1_x = points[i][1]
p1_y = points[i][0]
p2_x = points[j][1]
p2_y = points[j][0]
poly_area += p1_x * p2_y
poly_area -= p1_y * p2_x
j = i
poly_area /= 2
return poly_area
|
[
"def",
"area",
"(",
"poly",
")",
":",
"poly_area",
"=",
"0",
"# TODO: polygon holes at coordinates[1]",
"points",
"=",
"poly",
"[",
"'coordinates'",
"]",
"[",
"0",
"]",
"j",
"=",
"len",
"(",
"points",
")",
"-",
"1",
"count",
"=",
"len",
"(",
"points",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"count",
")",
":",
"p1_x",
"=",
"points",
"[",
"i",
"]",
"[",
"1",
"]",
"p1_y",
"=",
"points",
"[",
"i",
"]",
"[",
"0",
"]",
"p2_x",
"=",
"points",
"[",
"j",
"]",
"[",
"1",
"]",
"p2_y",
"=",
"points",
"[",
"j",
"]",
"[",
"0",
"]",
"poly_area",
"+=",
"p1_x",
"*",
"p2_y",
"poly_area",
"-=",
"p1_y",
"*",
"p2_x",
"j",
"=",
"i",
"poly_area",
"/=",
"2",
"return",
"poly_area"
] |
calculate the area of polygon
Keyword arguments:
poly -- polygon geojson object
return polygon area
|
[
"calculate",
"the",
"area",
"of",
"polygon"
] |
33d0dcd5f16e0567b48c0d49fd292a4f1db16b41
|
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L289-L315
|
17,521
|
brandonxiang/geojson-python-utils
|
geojson_utils/geojson_utils.py
|
destination_point
|
def destination_point(point, brng, dist):
"""
Calculate a destination Point base on a base point and a distance
Keyword arguments:
pt -- polygon geojson object
brng -- an angle in degrees
dist -- distance in Kilometer between destination and base point
return destination point object
"""
dist = float(dist) / 6371 # convert dist to angular distance in radians
brng = number2radius(brng)
lon1 = number2radius(point['coordinates'][0])
lat1 = number2radius(point['coordinates'][1])
lat2 = math.asin(math.sin(lat1) * math.cos(dist) +
math.cos(lat1) * math.sin(dist) * math.cos(brng))
lon2 = lon1 + math.atan2(math.sin(brng) * math.sin(dist) *
math.cos(lat1), math.cos(dist) - math.sin(lat1) * math.sin(lat2))
lon2 = (lon2 + 3 * math.pi) % (2 * math.pi) - math.pi # normalise to -180 degree +180 degree
return {'type': 'Point', 'coordinates': [number2degree(lon2), number2degree(lat2)]}
|
python
|
def destination_point(point, brng, dist):
"""
Calculate a destination Point base on a base point and a distance
Keyword arguments:
pt -- polygon geojson object
brng -- an angle in degrees
dist -- distance in Kilometer between destination and base point
return destination point object
"""
dist = float(dist) / 6371 # convert dist to angular distance in radians
brng = number2radius(brng)
lon1 = number2radius(point['coordinates'][0])
lat1 = number2radius(point['coordinates'][1])
lat2 = math.asin(math.sin(lat1) * math.cos(dist) +
math.cos(lat1) * math.sin(dist) * math.cos(brng))
lon2 = lon1 + math.atan2(math.sin(brng) * math.sin(dist) *
math.cos(lat1), math.cos(dist) - math.sin(lat1) * math.sin(lat2))
lon2 = (lon2 + 3 * math.pi) % (2 * math.pi) - math.pi # normalise to -180 degree +180 degree
return {'type': 'Point', 'coordinates': [number2degree(lon2), number2degree(lat2)]}
|
[
"def",
"destination_point",
"(",
"point",
",",
"brng",
",",
"dist",
")",
":",
"dist",
"=",
"float",
"(",
"dist",
")",
"/",
"6371",
"# convert dist to angular distance in radians",
"brng",
"=",
"number2radius",
"(",
"brng",
")",
"lon1",
"=",
"number2radius",
"(",
"point",
"[",
"'coordinates'",
"]",
"[",
"0",
"]",
")",
"lat1",
"=",
"number2radius",
"(",
"point",
"[",
"'coordinates'",
"]",
"[",
"1",
"]",
")",
"lat2",
"=",
"math",
".",
"asin",
"(",
"math",
".",
"sin",
"(",
"lat1",
")",
"*",
"math",
".",
"cos",
"(",
"dist",
")",
"+",
"math",
".",
"cos",
"(",
"lat1",
")",
"*",
"math",
".",
"sin",
"(",
"dist",
")",
"*",
"math",
".",
"cos",
"(",
"brng",
")",
")",
"lon2",
"=",
"lon1",
"+",
"math",
".",
"atan2",
"(",
"math",
".",
"sin",
"(",
"brng",
")",
"*",
"math",
".",
"sin",
"(",
"dist",
")",
"*",
"math",
".",
"cos",
"(",
"lat1",
")",
",",
"math",
".",
"cos",
"(",
"dist",
")",
"-",
"math",
".",
"sin",
"(",
"lat1",
")",
"*",
"math",
".",
"sin",
"(",
"lat2",
")",
")",
"lon2",
"=",
"(",
"lon2",
"+",
"3",
"*",
"math",
".",
"pi",
")",
"%",
"(",
"2",
"*",
"math",
".",
"pi",
")",
"-",
"math",
".",
"pi",
"# normalise to -180 degree +180 degree",
"return",
"{",
"'type'",
":",
"'Point'",
",",
"'coordinates'",
":",
"[",
"number2degree",
"(",
"lon2",
")",
",",
"number2degree",
"(",
"lat2",
")",
"]",
"}"
] |
Calculate a destination Point base on a base point and a distance
Keyword arguments:
pt -- polygon geojson object
brng -- an angle in degrees
dist -- distance in Kilometer between destination and base point
return destination point object
|
[
"Calculate",
"a",
"destination",
"Point",
"base",
"on",
"a",
"base",
"point",
"and",
"a",
"distance"
] |
33d0dcd5f16e0567b48c0d49fd292a4f1db16b41
|
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L351-L375
|
17,522
|
brandonxiang/geojson-python-utils
|
geojson_utils/merger.py
|
merge_featurecollection
|
def merge_featurecollection(*jsons):
"""
merge features into one featurecollection
Keyword arguments:
jsons -- jsons object list
return geojson featurecollection
"""
features = []
for json in jsons:
if json['type'] == 'FeatureCollection':
for feature in json['features']:
features.append(feature)
return {"type":'FeatureCollection', "features":features}
|
python
|
def merge_featurecollection(*jsons):
"""
merge features into one featurecollection
Keyword arguments:
jsons -- jsons object list
return geojson featurecollection
"""
features = []
for json in jsons:
if json['type'] == 'FeatureCollection':
for feature in json['features']:
features.append(feature)
return {"type":'FeatureCollection', "features":features}
|
[
"def",
"merge_featurecollection",
"(",
"*",
"jsons",
")",
":",
"features",
"=",
"[",
"]",
"for",
"json",
"in",
"jsons",
":",
"if",
"json",
"[",
"'type'",
"]",
"==",
"'FeatureCollection'",
":",
"for",
"feature",
"in",
"json",
"[",
"'features'",
"]",
":",
"features",
".",
"append",
"(",
"feature",
")",
"return",
"{",
"\"type\"",
":",
"'FeatureCollection'",
",",
"\"features\"",
":",
"features",
"}"
] |
merge features into one featurecollection
Keyword arguments:
jsons -- jsons object list
return geojson featurecollection
|
[
"merge",
"features",
"into",
"one",
"featurecollection"
] |
33d0dcd5f16e0567b48c0d49fd292a4f1db16b41
|
https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/merger.py#L6-L20
|
17,523
|
gotcha/vimpdb
|
src/vimpdb/debugger.py
|
trace_dispatch
|
def trace_dispatch(self, frame, event, arg):
"""allow to switch to Vimpdb instance"""
if hasattr(self, 'vimpdb'):
return self.vimpdb.trace_dispatch(frame, event, arg)
else:
return self._orig_trace_dispatch(frame, event, arg)
|
python
|
def trace_dispatch(self, frame, event, arg):
"""allow to switch to Vimpdb instance"""
if hasattr(self, 'vimpdb'):
return self.vimpdb.trace_dispatch(frame, event, arg)
else:
return self._orig_trace_dispatch(frame, event, arg)
|
[
"def",
"trace_dispatch",
"(",
"self",
",",
"frame",
",",
"event",
",",
"arg",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'vimpdb'",
")",
":",
"return",
"self",
".",
"vimpdb",
".",
"trace_dispatch",
"(",
"frame",
",",
"event",
",",
"arg",
")",
"else",
":",
"return",
"self",
".",
"_orig_trace_dispatch",
"(",
"frame",
",",
"event",
",",
"arg",
")"
] |
allow to switch to Vimpdb instance
|
[
"allow",
"to",
"switch",
"to",
"Vimpdb",
"instance"
] |
1171938751127d23f66f6b750dd79166c64bdf20
|
https://github.com/gotcha/vimpdb/blob/1171938751127d23f66f6b750dd79166c64bdf20/src/vimpdb/debugger.py#L237-L242
|
17,524
|
gotcha/vimpdb
|
src/vimpdb/debugger.py
|
hook
|
def hook(klass):
"""
monkey-patch pdb.Pdb class
adds a 'vim' (and 'v') command:
it switches to debugging with vimpdb
"""
if not hasattr(klass, 'do_vim'):
setupMethod(klass, trace_dispatch)
klass.__bases__ += (SwitcherToVimpdb, )
|
python
|
def hook(klass):
"""
monkey-patch pdb.Pdb class
adds a 'vim' (and 'v') command:
it switches to debugging with vimpdb
"""
if not hasattr(klass, 'do_vim'):
setupMethod(klass, trace_dispatch)
klass.__bases__ += (SwitcherToVimpdb, )
|
[
"def",
"hook",
"(",
"klass",
")",
":",
"if",
"not",
"hasattr",
"(",
"klass",
",",
"'do_vim'",
")",
":",
"setupMethod",
"(",
"klass",
",",
"trace_dispatch",
")",
"klass",
".",
"__bases__",
"+=",
"(",
"SwitcherToVimpdb",
",",
")"
] |
monkey-patch pdb.Pdb class
adds a 'vim' (and 'v') command:
it switches to debugging with vimpdb
|
[
"monkey",
"-",
"patch",
"pdb",
".",
"Pdb",
"class"
] |
1171938751127d23f66f6b750dd79166c64bdf20
|
https://github.com/gotcha/vimpdb/blob/1171938751127d23f66f6b750dd79166c64bdf20/src/vimpdb/debugger.py#L277-L287
|
17,525
|
gotcha/vimpdb
|
src/vimpdb/debugger.py
|
VimPdb.trace_dispatch
|
def trace_dispatch(self, frame, event, arg):
"""allow to switch to Pdb instance"""
if hasattr(self, 'pdb'):
return self.pdb.trace_dispatch(frame, event, arg)
else:
return Pdb.trace_dispatch(self, frame, event, arg)
|
python
|
def trace_dispatch(self, frame, event, arg):
"""allow to switch to Pdb instance"""
if hasattr(self, 'pdb'):
return self.pdb.trace_dispatch(frame, event, arg)
else:
return Pdb.trace_dispatch(self, frame, event, arg)
|
[
"def",
"trace_dispatch",
"(",
"self",
",",
"frame",
",",
"event",
",",
"arg",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'pdb'",
")",
":",
"return",
"self",
".",
"pdb",
".",
"trace_dispatch",
"(",
"frame",
",",
"event",
",",
"arg",
")",
"else",
":",
"return",
"Pdb",
".",
"trace_dispatch",
"(",
"self",
",",
"frame",
",",
"event",
",",
"arg",
")"
] |
allow to switch to Pdb instance
|
[
"allow",
"to",
"switch",
"to",
"Pdb",
"instance"
] |
1171938751127d23f66f6b750dd79166c64bdf20
|
https://github.com/gotcha/vimpdb/blob/1171938751127d23f66f6b750dd79166c64bdf20/src/vimpdb/debugger.py#L97-L102
|
17,526
|
rkhleics/wagtailmenus
|
wagtailmenus/models/mixins.py
|
DefinesSubMenuTemplatesMixin.get_context_data
|
def get_context_data(self, **kwargs):
"""
Include the name of the sub menu template in the context. This is
purely for backwards compatibility. Any sub menus rendered as part of
this menu will call `sub_menu_template` on the original menu instance
to get an actual `Template`
"""
data = {}
if self._contextual_vals.current_level == 1 and self.max_levels > 1:
data['sub_menu_template'] = self.sub_menu_template.template.name
data.update(kwargs)
return super().get_context_data(**data)
|
python
|
def get_context_data(self, **kwargs):
"""
Include the name of the sub menu template in the context. This is
purely for backwards compatibility. Any sub menus rendered as part of
this menu will call `sub_menu_template` on the original menu instance
to get an actual `Template`
"""
data = {}
if self._contextual_vals.current_level == 1 and self.max_levels > 1:
data['sub_menu_template'] = self.sub_menu_template.template.name
data.update(kwargs)
return super().get_context_data(**data)
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"}",
"if",
"self",
".",
"_contextual_vals",
".",
"current_level",
"==",
"1",
"and",
"self",
".",
"max_levels",
">",
"1",
":",
"data",
"[",
"'sub_menu_template'",
"]",
"=",
"self",
".",
"sub_menu_template",
".",
"template",
".",
"name",
"data",
".",
"update",
"(",
"kwargs",
")",
"return",
"super",
"(",
")",
".",
"get_context_data",
"(",
"*",
"*",
"data",
")"
] |
Include the name of the sub menu template in the context. This is
purely for backwards compatibility. Any sub menus rendered as part of
this menu will call `sub_menu_template` on the original menu instance
to get an actual `Template`
|
[
"Include",
"the",
"name",
"of",
"the",
"sub",
"menu",
"template",
"in",
"the",
"context",
".",
"This",
"is",
"purely",
"for",
"backwards",
"compatibility",
".",
"Any",
"sub",
"menus",
"rendered",
"as",
"part",
"of",
"this",
"menu",
"will",
"call",
"sub_menu_template",
"on",
"the",
"original",
"menu",
"instance",
"to",
"get",
"an",
"actual",
"Template"
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/mixins.py#L105-L116
|
17,527
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu.render_from_tag
|
def render_from_tag(
cls, context, max_levels=None, use_specific=None,
apply_active_classes=True, allow_repeating_parents=True,
use_absolute_page_urls=False, add_sub_menus_inline=None,
template_name='', **kwargs
):
"""
A template tag should call this method to render a menu.
The ``Context`` instance and option values provided are used to get or
create a relevant menu instance, prepare it, then render it and it's
menu items to an appropriate template.
It shouldn't be neccessary to override this method, as any new option
values will be available as a dict in `opt_vals.extra`, and there are
more specific methods for overriding certain behaviour at different
stages of rendering, such as:
* get_from_collected_values() (if the class is a Django model), OR
* create_from_collected_values() (if it isn't)
* prepare_to_render()
* get_context_data()
* render_to_template()
"""
instance = cls._get_render_prepared_object(
context,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template_name,
**kwargs
)
if not instance:
return ''
return instance.render_to_template()
|
python
|
def render_from_tag(
cls, context, max_levels=None, use_specific=None,
apply_active_classes=True, allow_repeating_parents=True,
use_absolute_page_urls=False, add_sub_menus_inline=None,
template_name='', **kwargs
):
"""
A template tag should call this method to render a menu.
The ``Context`` instance and option values provided are used to get or
create a relevant menu instance, prepare it, then render it and it's
menu items to an appropriate template.
It shouldn't be neccessary to override this method, as any new option
values will be available as a dict in `opt_vals.extra`, and there are
more specific methods for overriding certain behaviour at different
stages of rendering, such as:
* get_from_collected_values() (if the class is a Django model), OR
* create_from_collected_values() (if it isn't)
* prepare_to_render()
* get_context_data()
* render_to_template()
"""
instance = cls._get_render_prepared_object(
context,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template_name,
**kwargs
)
if not instance:
return ''
return instance.render_to_template()
|
[
"def",
"render_from_tag",
"(",
"cls",
",",
"context",
",",
"max_levels",
"=",
"None",
",",
"use_specific",
"=",
"None",
",",
"apply_active_classes",
"=",
"True",
",",
"allow_repeating_parents",
"=",
"True",
",",
"use_absolute_page_urls",
"=",
"False",
",",
"add_sub_menus_inline",
"=",
"None",
",",
"template_name",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"cls",
".",
"_get_render_prepared_object",
"(",
"context",
",",
"max_levels",
"=",
"max_levels",
",",
"use_specific",
"=",
"use_specific",
",",
"apply_active_classes",
"=",
"apply_active_classes",
",",
"allow_repeating_parents",
"=",
"allow_repeating_parents",
",",
"use_absolute_page_urls",
"=",
"use_absolute_page_urls",
",",
"add_sub_menus_inline",
"=",
"add_sub_menus_inline",
",",
"template_name",
"=",
"template_name",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"instance",
":",
"return",
"''",
"return",
"instance",
".",
"render_to_template",
"(",
")"
] |
A template tag should call this method to render a menu.
The ``Context`` instance and option values provided are used to get or
create a relevant menu instance, prepare it, then render it and it's
menu items to an appropriate template.
It shouldn't be neccessary to override this method, as any new option
values will be available as a dict in `opt_vals.extra`, and there are
more specific methods for overriding certain behaviour at different
stages of rendering, such as:
* get_from_collected_values() (if the class is a Django model), OR
* create_from_collected_values() (if it isn't)
* prepare_to_render()
* get_context_data()
* render_to_template()
|
[
"A",
"template",
"tag",
"should",
"call",
"this",
"method",
"to",
"render",
"a",
"menu",
".",
"The",
"Context",
"instance",
"and",
"option",
"values",
"provided",
"are",
"used",
"to",
"get",
"or",
"create",
"a",
"relevant",
"menu",
"instance",
"prepare",
"it",
"then",
"render",
"it",
"and",
"it",
"s",
"menu",
"items",
"to",
"an",
"appropriate",
"template",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L68-L105
|
17,528
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu._create_contextualvals_obj_from_context
|
def _create_contextualvals_obj_from_context(cls, context):
"""
Gathers all of the 'contextual' data needed to render a menu instance
and returns it in a structure that can be conveniently referenced
throughout the process of preparing the menu and menu items and
for rendering.
"""
context_processor_vals = context.get('wagtailmenus_vals', {})
return ContextualVals(
context,
context['request'],
get_site_from_request(context['request']),
context.get('current_level', 0) + 1,
context.get('original_menu_tag', cls.related_templatetag_name),
context.get('original_menu_instance'),
context_processor_vals.get('current_page'),
context_processor_vals.get('section_root'),
context_processor_vals.get('current_page_ancestor_ids', ()),
)
|
python
|
def _create_contextualvals_obj_from_context(cls, context):
"""
Gathers all of the 'contextual' data needed to render a menu instance
and returns it in a structure that can be conveniently referenced
throughout the process of preparing the menu and menu items and
for rendering.
"""
context_processor_vals = context.get('wagtailmenus_vals', {})
return ContextualVals(
context,
context['request'],
get_site_from_request(context['request']),
context.get('current_level', 0) + 1,
context.get('original_menu_tag', cls.related_templatetag_name),
context.get('original_menu_instance'),
context_processor_vals.get('current_page'),
context_processor_vals.get('section_root'),
context_processor_vals.get('current_page_ancestor_ids', ()),
)
|
[
"def",
"_create_contextualvals_obj_from_context",
"(",
"cls",
",",
"context",
")",
":",
"context_processor_vals",
"=",
"context",
".",
"get",
"(",
"'wagtailmenus_vals'",
",",
"{",
"}",
")",
"return",
"ContextualVals",
"(",
"context",
",",
"context",
"[",
"'request'",
"]",
",",
"get_site_from_request",
"(",
"context",
"[",
"'request'",
"]",
")",
",",
"context",
".",
"get",
"(",
"'current_level'",
",",
"0",
")",
"+",
"1",
",",
"context",
".",
"get",
"(",
"'original_menu_tag'",
",",
"cls",
".",
"related_templatetag_name",
")",
",",
"context",
".",
"get",
"(",
"'original_menu_instance'",
")",
",",
"context_processor_vals",
".",
"get",
"(",
"'current_page'",
")",
",",
"context_processor_vals",
".",
"get",
"(",
"'section_root'",
")",
",",
"context_processor_vals",
".",
"get",
"(",
"'current_page_ancestor_ids'",
",",
"(",
")",
")",
",",
")"
] |
Gathers all of the 'contextual' data needed to render a menu instance
and returns it in a structure that can be conveniently referenced
throughout the process of preparing the menu and menu items and
for rendering.
|
[
"Gathers",
"all",
"of",
"the",
"contextual",
"data",
"needed",
"to",
"render",
"a",
"menu",
"instance",
"and",
"returns",
"it",
"in",
"a",
"structure",
"that",
"can",
"be",
"conveniently",
"referenced",
"throughout",
"the",
"process",
"of",
"preparing",
"the",
"menu",
"and",
"menu",
"items",
"and",
"for",
"rendering",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L128-L146
|
17,529
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu.render_to_template
|
def render_to_template(self):
"""
Render the current menu instance to a template and return a string
"""
context_data = self.get_context_data()
template = self.get_template()
context_data['current_template'] = template.template.name
return template.render(context_data)
|
python
|
def render_to_template(self):
"""
Render the current menu instance to a template and return a string
"""
context_data = self.get_context_data()
template = self.get_template()
context_data['current_template'] = template.template.name
return template.render(context_data)
|
[
"def",
"render_to_template",
"(",
"self",
")",
":",
"context_data",
"=",
"self",
".",
"get_context_data",
"(",
")",
"template",
"=",
"self",
".",
"get_template",
"(",
")",
"context_data",
"[",
"'current_template'",
"]",
"=",
"template",
".",
"template",
".",
"name",
"return",
"template",
".",
"render",
"(",
"context_data",
")"
] |
Render the current menu instance to a template and return a string
|
[
"Render",
"the",
"current",
"menu",
"instance",
"to",
"a",
"template",
"and",
"return",
"a",
"string"
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L222-L230
|
17,530
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu.get_common_hook_kwargs
|
def get_common_hook_kwargs(self, **kwargs):
"""
Returns a dictionary of common values to be passed as keyword
arguments to methods registered as 'hooks'.
"""
opt_vals = self._option_vals
hook_kwargs = self._contextual_vals._asdict()
hook_kwargs.update({
'menu_instance': self,
'menu_tag': self.related_templatetag_name,
'parent_page': None,
'max_levels': self.max_levels,
'use_specific': self.use_specific,
'apply_active_classes': opt_vals.apply_active_classes,
'allow_repeating_parents': opt_vals.allow_repeating_parents,
'use_absolute_page_urls': opt_vals.use_absolute_page_urls,
})
if hook_kwargs['original_menu_instance'] is None:
hook_kwargs['original_menu_instance'] = self
hook_kwargs.update(kwargs)
return hook_kwargs
|
python
|
def get_common_hook_kwargs(self, **kwargs):
"""
Returns a dictionary of common values to be passed as keyword
arguments to methods registered as 'hooks'.
"""
opt_vals = self._option_vals
hook_kwargs = self._contextual_vals._asdict()
hook_kwargs.update({
'menu_instance': self,
'menu_tag': self.related_templatetag_name,
'parent_page': None,
'max_levels': self.max_levels,
'use_specific': self.use_specific,
'apply_active_classes': opt_vals.apply_active_classes,
'allow_repeating_parents': opt_vals.allow_repeating_parents,
'use_absolute_page_urls': opt_vals.use_absolute_page_urls,
})
if hook_kwargs['original_menu_instance'] is None:
hook_kwargs['original_menu_instance'] = self
hook_kwargs.update(kwargs)
return hook_kwargs
|
[
"def",
"get_common_hook_kwargs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"opt_vals",
"=",
"self",
".",
"_option_vals",
"hook_kwargs",
"=",
"self",
".",
"_contextual_vals",
".",
"_asdict",
"(",
")",
"hook_kwargs",
".",
"update",
"(",
"{",
"'menu_instance'",
":",
"self",
",",
"'menu_tag'",
":",
"self",
".",
"related_templatetag_name",
",",
"'parent_page'",
":",
"None",
",",
"'max_levels'",
":",
"self",
".",
"max_levels",
",",
"'use_specific'",
":",
"self",
".",
"use_specific",
",",
"'apply_active_classes'",
":",
"opt_vals",
".",
"apply_active_classes",
",",
"'allow_repeating_parents'",
":",
"opt_vals",
".",
"allow_repeating_parents",
",",
"'use_absolute_page_urls'",
":",
"opt_vals",
".",
"use_absolute_page_urls",
",",
"}",
")",
"if",
"hook_kwargs",
"[",
"'original_menu_instance'",
"]",
"is",
"None",
":",
"hook_kwargs",
"[",
"'original_menu_instance'",
"]",
"=",
"self",
"hook_kwargs",
".",
"update",
"(",
"kwargs",
")",
"return",
"hook_kwargs"
] |
Returns a dictionary of common values to be passed as keyword
arguments to methods registered as 'hooks'.
|
[
"Returns",
"a",
"dictionary",
"of",
"common",
"values",
"to",
"be",
"passed",
"as",
"keyword",
"arguments",
"to",
"methods",
"registered",
"as",
"hooks",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L269-L289
|
17,531
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu.get_page_children_dict
|
def get_page_children_dict(self, page_qs=None):
"""
Returns a dictionary of lists, where the keys are 'path' values for
pages, and the value is a list of children pages for that page.
"""
children_dict = defaultdict(list)
for page in page_qs or self.pages_for_display:
children_dict[page.path[:-page.steplen]].append(page)
return children_dict
|
python
|
def get_page_children_dict(self, page_qs=None):
"""
Returns a dictionary of lists, where the keys are 'path' values for
pages, and the value is a list of children pages for that page.
"""
children_dict = defaultdict(list)
for page in page_qs or self.pages_for_display:
children_dict[page.path[:-page.steplen]].append(page)
return children_dict
|
[
"def",
"get_page_children_dict",
"(",
"self",
",",
"page_qs",
"=",
"None",
")",
":",
"children_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"page",
"in",
"page_qs",
"or",
"self",
".",
"pages_for_display",
":",
"children_dict",
"[",
"page",
".",
"path",
"[",
":",
"-",
"page",
".",
"steplen",
"]",
"]",
".",
"append",
"(",
"page",
")",
"return",
"children_dict"
] |
Returns a dictionary of lists, where the keys are 'path' values for
pages, and the value is a list of children pages for that page.
|
[
"Returns",
"a",
"dictionary",
"of",
"lists",
"where",
"the",
"keys",
"are",
"path",
"values",
"for",
"pages",
"and",
"the",
"value",
"is",
"a",
"list",
"of",
"children",
"pages",
"for",
"that",
"page",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L318-L326
|
17,532
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu.get_context_data
|
def get_context_data(self, **kwargs):
"""
Return a dictionary containing all of the values needed to render the
menu instance to a template, including values that might be used by
the 'sub_menu' tag to render any additional levels.
"""
ctx_vals = self._contextual_vals
opt_vals = self._option_vals
data = self.create_dict_from_parent_context()
data.update(ctx_vals._asdict())
data.update({
'apply_active_classes': opt_vals.apply_active_classes,
'allow_repeating_parents': opt_vals.allow_repeating_parents,
'use_absolute_page_urls': opt_vals.use_absolute_page_urls,
'max_levels': self.max_levels,
'use_specific': self.use_specific,
'menu_instance': self,
self.menu_instance_context_name: self,
# Repeat some vals with backwards-compatible keys
'section_root': data['current_section_root_page'],
'current_ancestor_ids': data['current_page_ancestor_ids'],
})
if not ctx_vals.original_menu_instance and ctx_vals.current_level == 1:
data['original_menu_instance'] = self
if 'menu_items' not in kwargs:
data['menu_items'] = self.get_menu_items_for_rendering()
data.update(kwargs)
return data
|
python
|
def get_context_data(self, **kwargs):
"""
Return a dictionary containing all of the values needed to render the
menu instance to a template, including values that might be used by
the 'sub_menu' tag to render any additional levels.
"""
ctx_vals = self._contextual_vals
opt_vals = self._option_vals
data = self.create_dict_from_parent_context()
data.update(ctx_vals._asdict())
data.update({
'apply_active_classes': opt_vals.apply_active_classes,
'allow_repeating_parents': opt_vals.allow_repeating_parents,
'use_absolute_page_urls': opt_vals.use_absolute_page_urls,
'max_levels': self.max_levels,
'use_specific': self.use_specific,
'menu_instance': self,
self.menu_instance_context_name: self,
# Repeat some vals with backwards-compatible keys
'section_root': data['current_section_root_page'],
'current_ancestor_ids': data['current_page_ancestor_ids'],
})
if not ctx_vals.original_menu_instance and ctx_vals.current_level == 1:
data['original_menu_instance'] = self
if 'menu_items' not in kwargs:
data['menu_items'] = self.get_menu_items_for_rendering()
data.update(kwargs)
return data
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx_vals",
"=",
"self",
".",
"_contextual_vals",
"opt_vals",
"=",
"self",
".",
"_option_vals",
"data",
"=",
"self",
".",
"create_dict_from_parent_context",
"(",
")",
"data",
".",
"update",
"(",
"ctx_vals",
".",
"_asdict",
"(",
")",
")",
"data",
".",
"update",
"(",
"{",
"'apply_active_classes'",
":",
"opt_vals",
".",
"apply_active_classes",
",",
"'allow_repeating_parents'",
":",
"opt_vals",
".",
"allow_repeating_parents",
",",
"'use_absolute_page_urls'",
":",
"opt_vals",
".",
"use_absolute_page_urls",
",",
"'max_levels'",
":",
"self",
".",
"max_levels",
",",
"'use_specific'",
":",
"self",
".",
"use_specific",
",",
"'menu_instance'",
":",
"self",
",",
"self",
".",
"menu_instance_context_name",
":",
"self",
",",
"# Repeat some vals with backwards-compatible keys",
"'section_root'",
":",
"data",
"[",
"'current_section_root_page'",
"]",
",",
"'current_ancestor_ids'",
":",
"data",
"[",
"'current_page_ancestor_ids'",
"]",
",",
"}",
")",
"if",
"not",
"ctx_vals",
".",
"original_menu_instance",
"and",
"ctx_vals",
".",
"current_level",
"==",
"1",
":",
"data",
"[",
"'original_menu_instance'",
"]",
"=",
"self",
"if",
"'menu_items'",
"not",
"in",
"kwargs",
":",
"data",
"[",
"'menu_items'",
"]",
"=",
"self",
".",
"get_menu_items_for_rendering",
"(",
")",
"data",
".",
"update",
"(",
"kwargs",
")",
"return",
"data"
] |
Return a dictionary containing all of the values needed to render the
menu instance to a template, including values that might be used by
the 'sub_menu' tag to render any additional levels.
|
[
"Return",
"a",
"dictionary",
"containing",
"all",
"of",
"the",
"values",
"needed",
"to",
"render",
"the",
"menu",
"instance",
"to",
"a",
"template",
"including",
"values",
"that",
"might",
"be",
"used",
"by",
"the",
"sub_menu",
"tag",
"to",
"render",
"any",
"additional",
"levels",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L385-L412
|
17,533
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu.get_menu_items_for_rendering
|
def get_menu_items_for_rendering(self):
"""
Return a list of 'menu items' to be included in the context for
rendering the current level of the menu.
The responsibility for sourcing, priming, and modifying menu items is
split between three methods: ``get_raw_menu_items()``,
``prime_menu_items()`` and ``modify_menu_items()``, respectively.
"""
items = self.get_raw_menu_items()
# Allow hooks to modify the raw list
for hook in hooks.get_hooks('menus_modify_raw_menu_items'):
items = hook(items, **self.common_hook_kwargs)
# Prime and modify the menu items accordingly
items = self.modify_menu_items(self.prime_menu_items(items))
if isinstance(items, GeneratorType):
items = list(items)
# Allow hooks to modify the primed/modified list
hook_methods = hooks.get_hooks('menus_modify_primed_menu_items')
for hook in hook_methods:
items = hook(items, **self.common_hook_kwargs)
return items
|
python
|
def get_menu_items_for_rendering(self):
"""
Return a list of 'menu items' to be included in the context for
rendering the current level of the menu.
The responsibility for sourcing, priming, and modifying menu items is
split between three methods: ``get_raw_menu_items()``,
``prime_menu_items()`` and ``modify_menu_items()``, respectively.
"""
items = self.get_raw_menu_items()
# Allow hooks to modify the raw list
for hook in hooks.get_hooks('menus_modify_raw_menu_items'):
items = hook(items, **self.common_hook_kwargs)
# Prime and modify the menu items accordingly
items = self.modify_menu_items(self.prime_menu_items(items))
if isinstance(items, GeneratorType):
items = list(items)
# Allow hooks to modify the primed/modified list
hook_methods = hooks.get_hooks('menus_modify_primed_menu_items')
for hook in hook_methods:
items = hook(items, **self.common_hook_kwargs)
return items
|
[
"def",
"get_menu_items_for_rendering",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"get_raw_menu_items",
"(",
")",
"# Allow hooks to modify the raw list",
"for",
"hook",
"in",
"hooks",
".",
"get_hooks",
"(",
"'menus_modify_raw_menu_items'",
")",
":",
"items",
"=",
"hook",
"(",
"items",
",",
"*",
"*",
"self",
".",
"common_hook_kwargs",
")",
"# Prime and modify the menu items accordingly",
"items",
"=",
"self",
".",
"modify_menu_items",
"(",
"self",
".",
"prime_menu_items",
"(",
"items",
")",
")",
"if",
"isinstance",
"(",
"items",
",",
"GeneratorType",
")",
":",
"items",
"=",
"list",
"(",
"items",
")",
"# Allow hooks to modify the primed/modified list",
"hook_methods",
"=",
"hooks",
".",
"get_hooks",
"(",
"'menus_modify_primed_menu_items'",
")",
"for",
"hook",
"in",
"hook_methods",
":",
"items",
"=",
"hook",
"(",
"items",
",",
"*",
"*",
"self",
".",
"common_hook_kwargs",
")",
"return",
"items"
] |
Return a list of 'menu items' to be included in the context for
rendering the current level of the menu.
The responsibility for sourcing, priming, and modifying menu items is
split between three methods: ``get_raw_menu_items()``,
``prime_menu_items()`` and ``modify_menu_items()``, respectively.
|
[
"Return",
"a",
"list",
"of",
"menu",
"items",
"to",
"be",
"included",
"in",
"the",
"context",
"for",
"rendering",
"the",
"current",
"level",
"of",
"the",
"menu",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L414-L438
|
17,534
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu._replace_with_specific_page
|
def _replace_with_specific_page(page, menu_item):
"""
If ``page`` is a vanilla ``Page` object, replace it with a 'specific'
version of itself. Also update ``menu_item``, depending on whether it's
a ``MenuItem`` object or a ``Page`` object.
"""
if type(page) is Page:
page = page.specific
if isinstance(menu_item, MenuItem):
menu_item.link_page = page
else:
menu_item = page
return page, menu_item
|
python
|
def _replace_with_specific_page(page, menu_item):
"""
If ``page`` is a vanilla ``Page` object, replace it with a 'specific'
version of itself. Also update ``menu_item``, depending on whether it's
a ``MenuItem`` object or a ``Page`` object.
"""
if type(page) is Page:
page = page.specific
if isinstance(menu_item, MenuItem):
menu_item.link_page = page
else:
menu_item = page
return page, menu_item
|
[
"def",
"_replace_with_specific_page",
"(",
"page",
",",
"menu_item",
")",
":",
"if",
"type",
"(",
"page",
")",
"is",
"Page",
":",
"page",
"=",
"page",
".",
"specific",
"if",
"isinstance",
"(",
"menu_item",
",",
"MenuItem",
")",
":",
"menu_item",
".",
"link_page",
"=",
"page",
"else",
":",
"menu_item",
"=",
"page",
"return",
"page",
",",
"menu_item"
] |
If ``page`` is a vanilla ``Page` object, replace it with a 'specific'
version of itself. Also update ``menu_item``, depending on whether it's
a ``MenuItem`` object or a ``Page`` object.
|
[
"If",
"page",
"is",
"a",
"vanilla",
"Page",
"object",
"replace",
"it",
"with",
"a",
"specific",
"version",
"of",
"itself",
".",
"Also",
"update",
"menu_item",
"depending",
"on",
"whether",
"it",
"s",
"a",
"MenuItem",
"object",
"or",
"a",
"Page",
"object",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L451-L463
|
17,535
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
Menu.prime_menu_items
|
def prime_menu_items(self, menu_items):
"""
A generator method that takes a list of ``MenuItem`` or ``Page``
objects and sets a number of additional attributes on each item that
are useful in menu templates.
"""
for item in menu_items:
item = self._prime_menu_item(item)
if item is not None:
yield item
|
python
|
def prime_menu_items(self, menu_items):
"""
A generator method that takes a list of ``MenuItem`` or ``Page``
objects and sets a number of additional attributes on each item that
are useful in menu templates.
"""
for item in menu_items:
item = self._prime_menu_item(item)
if item is not None:
yield item
|
[
"def",
"prime_menu_items",
"(",
"self",
",",
"menu_items",
")",
":",
"for",
"item",
"in",
"menu_items",
":",
"item",
"=",
"self",
".",
"_prime_menu_item",
"(",
"item",
")",
"if",
"item",
"is",
"not",
"None",
":",
"yield",
"item"
] |
A generator method that takes a list of ``MenuItem`` or ``Page``
objects and sets a number of additional attributes on each item that
are useful in menu templates.
|
[
"A",
"generator",
"method",
"that",
"takes",
"a",
"list",
"of",
"MenuItem",
"or",
"Page",
"objects",
"and",
"sets",
"a",
"number",
"of",
"additional",
"attributes",
"on",
"each",
"item",
"that",
"are",
"useful",
"in",
"menu",
"templates",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L603-L612
|
17,536
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
MenuFromPage.get_children_for_page
|
def get_children_for_page(self, page):
"""Return a list of relevant child pages for a given page"""
if self.max_levels == 1:
# If there's only a single level of pages to display, skip the
# dict creation / lookup and just return the QuerySet result
return self.pages_for_display
return super().get_children_for_page(page)
|
python
|
def get_children_for_page(self, page):
"""Return a list of relevant child pages for a given page"""
if self.max_levels == 1:
# If there's only a single level of pages to display, skip the
# dict creation / lookup and just return the QuerySet result
return self.pages_for_display
return super().get_children_for_page(page)
|
[
"def",
"get_children_for_page",
"(",
"self",
",",
"page",
")",
":",
"if",
"self",
".",
"max_levels",
"==",
"1",
":",
"# If there's only a single level of pages to display, skip the",
"# dict creation / lookup and just return the QuerySet result",
"return",
"self",
".",
"pages_for_display",
"return",
"super",
"(",
")",
".",
"get_children_for_page",
"(",
"page",
")"
] |
Return a list of relevant child pages for a given page
|
[
"Return",
"a",
"list",
"of",
"relevant",
"child",
"pages",
"for",
"a",
"given",
"page"
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L705-L711
|
17,537
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
MenuWithMenuItems.get_top_level_items
|
def get_top_level_items(self):
"""Return a list of menu items with link_page objects supplemented with
'specific' pages where appropriate."""
menu_items = self.get_base_menuitem_queryset()
# Identify which pages to fetch for the top level items
page_ids = tuple(
obj.link_page_id for obj in menu_items if obj.link_page_id
)
page_dict = {}
if page_ids:
# We use 'get_base_page_queryset' here, because if hooks are being
# used to modify page querysets, that should affect the top level
# items also
top_level_pages = self.get_base_page_queryset().filter(
id__in=page_ids
)
if self.use_specific >= constants.USE_SPECIFIC_TOP_LEVEL:
"""
The menu is being generated with a specificity level of
TOP_LEVEL or ALWAYS, so we use PageQuerySet.specific() to fetch
specific page instances as efficiently as possible
"""
top_level_pages = top_level_pages.specific()
# Evaluate the above queryset to a dictionary, using IDs as keys
page_dict = {p.id: p for p in top_level_pages}
# Now build a list to return
menu_item_list = []
for item in menu_items:
if not item.link_page_id:
menu_item_list.append(item)
continue # skip to next
if item.link_page_id in page_dict.keys():
# Only return menu items for pages where the page was included
# in the 'get_base_page_queryset' result
item.link_page = page_dict.get(item.link_page_id)
menu_item_list.append(item)
return menu_item_list
|
python
|
def get_top_level_items(self):
"""Return a list of menu items with link_page objects supplemented with
'specific' pages where appropriate."""
menu_items = self.get_base_menuitem_queryset()
# Identify which pages to fetch for the top level items
page_ids = tuple(
obj.link_page_id for obj in menu_items if obj.link_page_id
)
page_dict = {}
if page_ids:
# We use 'get_base_page_queryset' here, because if hooks are being
# used to modify page querysets, that should affect the top level
# items also
top_level_pages = self.get_base_page_queryset().filter(
id__in=page_ids
)
if self.use_specific >= constants.USE_SPECIFIC_TOP_LEVEL:
"""
The menu is being generated with a specificity level of
TOP_LEVEL or ALWAYS, so we use PageQuerySet.specific() to fetch
specific page instances as efficiently as possible
"""
top_level_pages = top_level_pages.specific()
# Evaluate the above queryset to a dictionary, using IDs as keys
page_dict = {p.id: p for p in top_level_pages}
# Now build a list to return
menu_item_list = []
for item in menu_items:
if not item.link_page_id:
menu_item_list.append(item)
continue # skip to next
if item.link_page_id in page_dict.keys():
# Only return menu items for pages where the page was included
# in the 'get_base_page_queryset' result
item.link_page = page_dict.get(item.link_page_id)
menu_item_list.append(item)
return menu_item_list
|
[
"def",
"get_top_level_items",
"(",
"self",
")",
":",
"menu_items",
"=",
"self",
".",
"get_base_menuitem_queryset",
"(",
")",
"# Identify which pages to fetch for the top level items",
"page_ids",
"=",
"tuple",
"(",
"obj",
".",
"link_page_id",
"for",
"obj",
"in",
"menu_items",
"if",
"obj",
".",
"link_page_id",
")",
"page_dict",
"=",
"{",
"}",
"if",
"page_ids",
":",
"# We use 'get_base_page_queryset' here, because if hooks are being",
"# used to modify page querysets, that should affect the top level",
"# items also",
"top_level_pages",
"=",
"self",
".",
"get_base_page_queryset",
"(",
")",
".",
"filter",
"(",
"id__in",
"=",
"page_ids",
")",
"if",
"self",
".",
"use_specific",
">=",
"constants",
".",
"USE_SPECIFIC_TOP_LEVEL",
":",
"\"\"\"\n The menu is being generated with a specificity level of\n TOP_LEVEL or ALWAYS, so we use PageQuerySet.specific() to fetch\n specific page instances as efficiently as possible\n \"\"\"",
"top_level_pages",
"=",
"top_level_pages",
".",
"specific",
"(",
")",
"# Evaluate the above queryset to a dictionary, using IDs as keys",
"page_dict",
"=",
"{",
"p",
".",
"id",
":",
"p",
"for",
"p",
"in",
"top_level_pages",
"}",
"# Now build a list to return",
"menu_item_list",
"=",
"[",
"]",
"for",
"item",
"in",
"menu_items",
":",
"if",
"not",
"item",
".",
"link_page_id",
":",
"menu_item_list",
".",
"append",
"(",
"item",
")",
"continue",
"# skip to next",
"if",
"item",
".",
"link_page_id",
"in",
"page_dict",
".",
"keys",
"(",
")",
":",
"# Only return menu items for pages where the page was included",
"# in the 'get_base_page_queryset' result",
"item",
".",
"link_page",
"=",
"page_dict",
".",
"get",
"(",
"item",
".",
"link_page_id",
")",
"menu_item_list",
".",
"append",
"(",
"item",
")",
"return",
"menu_item_list"
] |
Return a list of menu items with link_page objects supplemented with
'specific' pages where appropriate.
|
[
"Return",
"a",
"list",
"of",
"menu",
"items",
"with",
"link_page",
"objects",
"supplemented",
"with",
"specific",
"pages",
"where",
"appropriate",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L1015-L1054
|
17,538
|
rkhleics/wagtailmenus
|
wagtailmenus/models/menus.py
|
AbstractMainMenu.get_for_site
|
def get_for_site(cls, site):
"""Return the 'main menu' instance for the provided site"""
instance, created = cls.objects.get_or_create(site=site)
return instance
|
python
|
def get_for_site(cls, site):
"""Return the 'main menu' instance for the provided site"""
instance, created = cls.objects.get_or_create(site=site)
return instance
|
[
"def",
"get_for_site",
"(",
"cls",
",",
"site",
")",
":",
"instance",
",",
"created",
"=",
"cls",
".",
"objects",
".",
"get_or_create",
"(",
"site",
"=",
"site",
")",
"return",
"instance"
] |
Return the 'main menu' instance for the provided site
|
[
"Return",
"the",
"main",
"menu",
"instance",
"for",
"the",
"provided",
"site"
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/menus.py#L1207-L1210
|
17,539
|
rkhleics/wagtailmenus
|
wagtailmenus/views.py
|
FlatMenuCopyView.get_form_kwargs
|
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
"""
When the form is posted, don't pass an instance to the form. It should
create a new one out of the posted data. We also need to nullify any
IDs posted for inline menu items, so that new instances of those are
created too.
"""
if self.request.method == 'POST':
data = copy(self.request.POST)
i = 0
while(data.get('%s-%s-id' % (
settings.FLAT_MENU_ITEMS_RELATED_NAME, i
))):
data['%s-%s-id' % (
settings.FLAT_MENU_ITEMS_RELATED_NAME, i
)] = None
i += 1
kwargs.update({
'data': data,
'instance': self.model()
})
return kwargs
|
python
|
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
"""
When the form is posted, don't pass an instance to the form. It should
create a new one out of the posted data. We also need to nullify any
IDs posted for inline menu items, so that new instances of those are
created too.
"""
if self.request.method == 'POST':
data = copy(self.request.POST)
i = 0
while(data.get('%s-%s-id' % (
settings.FLAT_MENU_ITEMS_RELATED_NAME, i
))):
data['%s-%s-id' % (
settings.FLAT_MENU_ITEMS_RELATED_NAME, i
)] = None
i += 1
kwargs.update({
'data': data,
'instance': self.model()
})
return kwargs
|
[
"def",
"get_form_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"super",
"(",
")",
".",
"get_form_kwargs",
"(",
")",
"if",
"self",
".",
"request",
".",
"method",
"==",
"'POST'",
":",
"data",
"=",
"copy",
"(",
"self",
".",
"request",
".",
"POST",
")",
"i",
"=",
"0",
"while",
"(",
"data",
".",
"get",
"(",
"'%s-%s-id'",
"%",
"(",
"settings",
".",
"FLAT_MENU_ITEMS_RELATED_NAME",
",",
"i",
")",
")",
")",
":",
"data",
"[",
"'%s-%s-id'",
"%",
"(",
"settings",
".",
"FLAT_MENU_ITEMS_RELATED_NAME",
",",
"i",
")",
"]",
"=",
"None",
"i",
"+=",
"1",
"kwargs",
".",
"update",
"(",
"{",
"'data'",
":",
"data",
",",
"'instance'",
":",
"self",
".",
"model",
"(",
")",
"}",
")",
"return",
"kwargs"
] |
When the form is posted, don't pass an instance to the form. It should
create a new one out of the posted data. We also need to nullify any
IDs posted for inline menu items, so that new instances of those are
created too.
|
[
"When",
"the",
"form",
"is",
"posted",
"don",
"t",
"pass",
"an",
"instance",
"to",
"the",
"form",
".",
"It",
"should",
"create",
"a",
"new",
"one",
"out",
"of",
"the",
"posted",
"data",
".",
"We",
"also",
"need",
"to",
"nullify",
"any",
"IDs",
"posted",
"for",
"inline",
"menu",
"items",
"so",
"that",
"new",
"instances",
"of",
"those",
"are",
"created",
"too",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/views.py#L156-L178
|
17,540
|
rkhleics/wagtailmenus
|
wagtailmenus/models/pages.py
|
MenuPageMixin.modify_submenu_items
|
def modify_submenu_items(
self, menu_items, current_page, current_ancestor_ids, current_site,
allow_repeating_parents, apply_active_classes, original_menu_tag,
menu_instance=None, request=None, use_absolute_page_urls=False,
):
"""
Make any necessary modifications to `menu_items` and return the list
back to the calling menu tag to render in templates. Any additional
items added should have a `text` and `href` attribute as a minimum.
`original_menu_tag` should be one of 'main_menu', 'section_menu' or
'children_menu', which should be useful when extending/overriding.
"""
if (allow_repeating_parents and menu_items and self.repeat_in_subnav):
"""
This page should have a version of itself repeated alongside
children in the subnav, so we create a new item and prepend it to
menu_items.
"""
repeated_item = self.get_repeated_menu_item(
current_page=current_page,
current_site=current_site,
apply_active_classes=apply_active_classes,
original_menu_tag=original_menu_tag,
use_absolute_page_urls=use_absolute_page_urls,
request=request,
)
menu_items.insert(0, repeated_item)
return menu_items
|
python
|
def modify_submenu_items(
self, menu_items, current_page, current_ancestor_ids, current_site,
allow_repeating_parents, apply_active_classes, original_menu_tag,
menu_instance=None, request=None, use_absolute_page_urls=False,
):
"""
Make any necessary modifications to `menu_items` and return the list
back to the calling menu tag to render in templates. Any additional
items added should have a `text` and `href` attribute as a minimum.
`original_menu_tag` should be one of 'main_menu', 'section_menu' or
'children_menu', which should be useful when extending/overriding.
"""
if (allow_repeating_parents and menu_items and self.repeat_in_subnav):
"""
This page should have a version of itself repeated alongside
children in the subnav, so we create a new item and prepend it to
menu_items.
"""
repeated_item = self.get_repeated_menu_item(
current_page=current_page,
current_site=current_site,
apply_active_classes=apply_active_classes,
original_menu_tag=original_menu_tag,
use_absolute_page_urls=use_absolute_page_urls,
request=request,
)
menu_items.insert(0, repeated_item)
return menu_items
|
[
"def",
"modify_submenu_items",
"(",
"self",
",",
"menu_items",
",",
"current_page",
",",
"current_ancestor_ids",
",",
"current_site",
",",
"allow_repeating_parents",
",",
"apply_active_classes",
",",
"original_menu_tag",
",",
"menu_instance",
"=",
"None",
",",
"request",
"=",
"None",
",",
"use_absolute_page_urls",
"=",
"False",
",",
")",
":",
"if",
"(",
"allow_repeating_parents",
"and",
"menu_items",
"and",
"self",
".",
"repeat_in_subnav",
")",
":",
"\"\"\"\n This page should have a version of itself repeated alongside\n children in the subnav, so we create a new item and prepend it to\n menu_items.\n \"\"\"",
"repeated_item",
"=",
"self",
".",
"get_repeated_menu_item",
"(",
"current_page",
"=",
"current_page",
",",
"current_site",
"=",
"current_site",
",",
"apply_active_classes",
"=",
"apply_active_classes",
",",
"original_menu_tag",
"=",
"original_menu_tag",
",",
"use_absolute_page_urls",
"=",
"use_absolute_page_urls",
",",
"request",
"=",
"request",
",",
")",
"menu_items",
".",
"insert",
"(",
"0",
",",
"repeated_item",
")",
"return",
"menu_items"
] |
Make any necessary modifications to `menu_items` and return the list
back to the calling menu tag to render in templates. Any additional
items added should have a `text` and `href` attribute as a minimum.
`original_menu_tag` should be one of 'main_menu', 'section_menu' or
'children_menu', which should be useful when extending/overriding.
|
[
"Make",
"any",
"necessary",
"modifications",
"to",
"menu_items",
"and",
"return",
"the",
"list",
"back",
"to",
"the",
"calling",
"menu",
"tag",
"to",
"render",
"in",
"templates",
".",
"Any",
"additional",
"items",
"added",
"should",
"have",
"a",
"text",
"and",
"href",
"attribute",
"as",
"a",
"minimum",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L37-L65
|
17,541
|
rkhleics/wagtailmenus
|
wagtailmenus/models/pages.py
|
MenuPageMixin.has_submenu_items
|
def has_submenu_items(self, current_page, allow_repeating_parents,
original_menu_tag, menu_instance=None, request=None):
"""
When rendering pages in a menu template a `has_children_in_menu`
attribute is added to each page, letting template developers know
whether or not the item has a submenu that must be rendered.
By default, we return a boolean indicating whether the page has
suitable child pages to include in such a menu. But, if you are
overriding the `modify_submenu_items` method to programatically add
items that aren't child pages, you'll likely need to alter this method
too, so the template knows there are sub items to be rendered.
"""
return menu_instance.page_has_children(self)
|
python
|
def has_submenu_items(self, current_page, allow_repeating_parents,
original_menu_tag, menu_instance=None, request=None):
"""
When rendering pages in a menu template a `has_children_in_menu`
attribute is added to each page, letting template developers know
whether or not the item has a submenu that must be rendered.
By default, we return a boolean indicating whether the page has
suitable child pages to include in such a menu. But, if you are
overriding the `modify_submenu_items` method to programatically add
items that aren't child pages, you'll likely need to alter this method
too, so the template knows there are sub items to be rendered.
"""
return menu_instance.page_has_children(self)
|
[
"def",
"has_submenu_items",
"(",
"self",
",",
"current_page",
",",
"allow_repeating_parents",
",",
"original_menu_tag",
",",
"menu_instance",
"=",
"None",
",",
"request",
"=",
"None",
")",
":",
"return",
"menu_instance",
".",
"page_has_children",
"(",
"self",
")"
] |
When rendering pages in a menu template a `has_children_in_menu`
attribute is added to each page, letting template developers know
whether or not the item has a submenu that must be rendered.
By default, we return a boolean indicating whether the page has
suitable child pages to include in such a menu. But, if you are
overriding the `modify_submenu_items` method to programatically add
items that aren't child pages, you'll likely need to alter this method
too, so the template knows there are sub items to be rendered.
|
[
"When",
"rendering",
"pages",
"in",
"a",
"menu",
"template",
"a",
"has_children_in_menu",
"attribute",
"is",
"added",
"to",
"each",
"page",
"letting",
"template",
"developers",
"know",
"whether",
"or",
"not",
"the",
"item",
"has",
"a",
"submenu",
"that",
"must",
"be",
"rendered",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L67-L80
|
17,542
|
rkhleics/wagtailmenus
|
wagtailmenus/models/pages.py
|
MenuPageMixin.get_text_for_repeated_menu_item
|
def get_text_for_repeated_menu_item(
self, request=None, current_site=None, original_menu_tag='', **kwargs
):
"""Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating a multilingual site and you
have different translations of 'repeated_item_text' that you wish to
surface."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
return self.repeated_item_text or getattr(
self, source_field_name, self.title
)
|
python
|
def get_text_for_repeated_menu_item(
self, request=None, current_site=None, original_menu_tag='', **kwargs
):
"""Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating a multilingual site and you
have different translations of 'repeated_item_text' that you wish to
surface."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
return self.repeated_item_text or getattr(
self, source_field_name, self.title
)
|
[
"def",
"get_text_for_repeated_menu_item",
"(",
"self",
",",
"request",
"=",
"None",
",",
"current_site",
"=",
"None",
",",
"original_menu_tag",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"source_field_name",
"=",
"settings",
".",
"PAGE_FIELD_FOR_MENU_ITEM_TEXT",
"return",
"self",
".",
"repeated_item_text",
"or",
"getattr",
"(",
"self",
",",
"source_field_name",
",",
"self",
".",
"title",
")"
] |
Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating a multilingual site and you
have different translations of 'repeated_item_text' that you wish to
surface.
|
[
"Return",
"the",
"a",
"string",
"to",
"use",
"as",
"text",
"for",
"this",
"page",
"when",
"it",
"is",
"being",
"included",
"as",
"a",
"repeated",
"menu",
"item",
"in",
"a",
"menu",
".",
"You",
"might",
"want",
"to",
"override",
"this",
"method",
"if",
"you",
"re",
"creating",
"a",
"multilingual",
"site",
"and",
"you",
"have",
"different",
"translations",
"of",
"repeated_item_text",
"that",
"you",
"wish",
"to",
"surface",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L82-L93
|
17,543
|
rkhleics/wagtailmenus
|
wagtailmenus/models/pages.py
|
MenuPageMixin.get_repeated_menu_item
|
def get_repeated_menu_item(
self, current_page, current_site, apply_active_classes,
original_menu_tag, request=None, use_absolute_page_urls=False,
):
"""Return something that can be used to display a 'repeated' menu item
for this specific page."""
menuitem = copy(self)
# Set/reset 'text'
menuitem.text = self.get_text_for_repeated_menu_item(
request, current_site, original_menu_tag
)
# Set/reset 'href'
if use_absolute_page_urls:
url = self.get_full_url(request=request)
else:
url = self.relative_url(current_site)
menuitem.href = url
# Set/reset 'active_class'
if apply_active_classes and self == current_page:
menuitem.active_class = settings.ACTIVE_CLASS
else:
menuitem.active_class = ''
# Set/reset 'has_children_in_menu' and 'sub_menu'
menuitem.has_children_in_menu = False
menuitem.sub_menu = None
return menuitem
|
python
|
def get_repeated_menu_item(
self, current_page, current_site, apply_active_classes,
original_menu_tag, request=None, use_absolute_page_urls=False,
):
"""Return something that can be used to display a 'repeated' menu item
for this specific page."""
menuitem = copy(self)
# Set/reset 'text'
menuitem.text = self.get_text_for_repeated_menu_item(
request, current_site, original_menu_tag
)
# Set/reset 'href'
if use_absolute_page_urls:
url = self.get_full_url(request=request)
else:
url = self.relative_url(current_site)
menuitem.href = url
# Set/reset 'active_class'
if apply_active_classes and self == current_page:
menuitem.active_class = settings.ACTIVE_CLASS
else:
menuitem.active_class = ''
# Set/reset 'has_children_in_menu' and 'sub_menu'
menuitem.has_children_in_menu = False
menuitem.sub_menu = None
return menuitem
|
[
"def",
"get_repeated_menu_item",
"(",
"self",
",",
"current_page",
",",
"current_site",
",",
"apply_active_classes",
",",
"original_menu_tag",
",",
"request",
"=",
"None",
",",
"use_absolute_page_urls",
"=",
"False",
",",
")",
":",
"menuitem",
"=",
"copy",
"(",
"self",
")",
"# Set/reset 'text'",
"menuitem",
".",
"text",
"=",
"self",
".",
"get_text_for_repeated_menu_item",
"(",
"request",
",",
"current_site",
",",
"original_menu_tag",
")",
"# Set/reset 'href'",
"if",
"use_absolute_page_urls",
":",
"url",
"=",
"self",
".",
"get_full_url",
"(",
"request",
"=",
"request",
")",
"else",
":",
"url",
"=",
"self",
".",
"relative_url",
"(",
"current_site",
")",
"menuitem",
".",
"href",
"=",
"url",
"# Set/reset 'active_class'",
"if",
"apply_active_classes",
"and",
"self",
"==",
"current_page",
":",
"menuitem",
".",
"active_class",
"=",
"settings",
".",
"ACTIVE_CLASS",
"else",
":",
"menuitem",
".",
"active_class",
"=",
"''",
"# Set/reset 'has_children_in_menu' and 'sub_menu'",
"menuitem",
".",
"has_children_in_menu",
"=",
"False",
"menuitem",
".",
"sub_menu",
"=",
"None",
"return",
"menuitem"
] |
Return something that can be used to display a 'repeated' menu item
for this specific page.
|
[
"Return",
"something",
"that",
"can",
"be",
"used",
"to",
"display",
"a",
"repeated",
"menu",
"item",
"for",
"this",
"specific",
"page",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L95-L126
|
17,544
|
rkhleics/wagtailmenus
|
wagtailmenus/models/pages.py
|
AbstractLinkPage.menu_text
|
def menu_text(self, request=None):
"""Return a string to use as link text when this page appears in
menus."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
if(
source_field_name != 'menu_text' and
hasattr(self, source_field_name)
):
return getattr(self, source_field_name)
return self.title
|
python
|
def menu_text(self, request=None):
"""Return a string to use as link text when this page appears in
menus."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
if(
source_field_name != 'menu_text' and
hasattr(self, source_field_name)
):
return getattr(self, source_field_name)
return self.title
|
[
"def",
"menu_text",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"source_field_name",
"=",
"settings",
".",
"PAGE_FIELD_FOR_MENU_ITEM_TEXT",
"if",
"(",
"source_field_name",
"!=",
"'menu_text'",
"and",
"hasattr",
"(",
"self",
",",
"source_field_name",
")",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"source_field_name",
")",
"return",
"self",
".",
"title"
] |
Return a string to use as link text when this page appears in
menus.
|
[
"Return",
"a",
"string",
"to",
"use",
"as",
"link",
"text",
"when",
"this",
"page",
"appears",
"in",
"menus",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L184-L193
|
17,545
|
rkhleics/wagtailmenus
|
wagtailmenus/models/pages.py
|
AbstractLinkPage.link_page_is_suitable_for_display
|
def link_page_is_suitable_for_display(
self, request=None, current_site=None, menu_instance=None,
original_menu_tag=''
):
"""
Like menu items, link pages linking to pages should only be included
in menus when the target page is live and is itself configured to
appear in menus. Returns a boolean indicating as much
"""
if self.link_page:
if(
not self.link_page.show_in_menus or
not self.link_page.live or
self.link_page.expired
):
return False
return True
|
python
|
def link_page_is_suitable_for_display(
self, request=None, current_site=None, menu_instance=None,
original_menu_tag=''
):
"""
Like menu items, link pages linking to pages should only be included
in menus when the target page is live and is itself configured to
appear in menus. Returns a boolean indicating as much
"""
if self.link_page:
if(
not self.link_page.show_in_menus or
not self.link_page.live or
self.link_page.expired
):
return False
return True
|
[
"def",
"link_page_is_suitable_for_display",
"(",
"self",
",",
"request",
"=",
"None",
",",
"current_site",
"=",
"None",
",",
"menu_instance",
"=",
"None",
",",
"original_menu_tag",
"=",
"''",
")",
":",
"if",
"self",
".",
"link_page",
":",
"if",
"(",
"not",
"self",
".",
"link_page",
".",
"show_in_menus",
"or",
"not",
"self",
".",
"link_page",
".",
"live",
"or",
"self",
".",
"link_page",
".",
"expired",
")",
":",
"return",
"False",
"return",
"True"
] |
Like menu items, link pages linking to pages should only be included
in menus when the target page is live and is itself configured to
appear in menus. Returns a boolean indicating as much
|
[
"Like",
"menu",
"items",
"link",
"pages",
"linking",
"to",
"pages",
"should",
"only",
"be",
"included",
"in",
"menus",
"when",
"the",
"target",
"page",
"is",
"live",
"and",
"is",
"itself",
"configured",
"to",
"appear",
"in",
"menus",
".",
"Returns",
"a",
"boolean",
"indicating",
"as",
"much"
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L217-L233
|
17,546
|
rkhleics/wagtailmenus
|
wagtailmenus/models/pages.py
|
AbstractLinkPage.show_in_menus_custom
|
def show_in_menus_custom(self, request=None, current_site=None,
menu_instance=None, original_menu_tag=''):
"""
Return a boolean indicating whether this page should be included in
menus being rendered.
"""
if not self.show_in_menus:
return False
if self.link_page:
return self.link_page_is_suitable_for_display()
return True
|
python
|
def show_in_menus_custom(self, request=None, current_site=None,
menu_instance=None, original_menu_tag=''):
"""
Return a boolean indicating whether this page should be included in
menus being rendered.
"""
if not self.show_in_menus:
return False
if self.link_page:
return self.link_page_is_suitable_for_display()
return True
|
[
"def",
"show_in_menus_custom",
"(",
"self",
",",
"request",
"=",
"None",
",",
"current_site",
"=",
"None",
",",
"menu_instance",
"=",
"None",
",",
"original_menu_tag",
"=",
"''",
")",
":",
"if",
"not",
"self",
".",
"show_in_menus",
":",
"return",
"False",
"if",
"self",
".",
"link_page",
":",
"return",
"self",
".",
"link_page_is_suitable_for_display",
"(",
")",
"return",
"True"
] |
Return a boolean indicating whether this page should be included in
menus being rendered.
|
[
"Return",
"a",
"boolean",
"indicating",
"whether",
"this",
"page",
"should",
"be",
"included",
"in",
"menus",
"being",
"rendered",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L235-L245
|
17,547
|
rkhleics/wagtailmenus
|
wagtailmenus/utils/inspection.py
|
accepts_kwarg
|
def accepts_kwarg(func, kwarg):
"""
Determine whether the callable `func` has a signature that accepts the
keyword argument `kwarg`
"""
signature = inspect.signature(func)
try:
signature.bind_partial(**{kwarg: None})
return True
except TypeError:
return False
|
python
|
def accepts_kwarg(func, kwarg):
"""
Determine whether the callable `func` has a signature that accepts the
keyword argument `kwarg`
"""
signature = inspect.signature(func)
try:
signature.bind_partial(**{kwarg: None})
return True
except TypeError:
return False
|
[
"def",
"accepts_kwarg",
"(",
"func",
",",
"kwarg",
")",
":",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"try",
":",
"signature",
".",
"bind_partial",
"(",
"*",
"*",
"{",
"kwarg",
":",
"None",
"}",
")",
"return",
"True",
"except",
"TypeError",
":",
"return",
"False"
] |
Determine whether the callable `func` has a signature that accepts the
keyword argument `kwarg`
|
[
"Determine",
"whether",
"the",
"callable",
"func",
"has",
"a",
"signature",
"that",
"accepts",
"the",
"keyword",
"argument",
"kwarg"
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/utils/inspection.py#L10-L20
|
17,548
|
rkhleics/wagtailmenus
|
wagtailmenus/templatetags/menu_tags.py
|
section_menu
|
def section_menu(
context, show_section_root=True, show_multiple_levels=True,
apply_active_classes=True, allow_repeating_parents=True,
max_levels=settings.DEFAULT_SECTION_MENU_MAX_LEVELS,
template='', sub_menu_template='', sub_menu_templates=None,
use_specific=settings.DEFAULT_SECTION_MENU_USE_SPECIFIC,
use_absolute_page_urls=False, add_sub_menus_inline=None, **kwargs
):
"""Render a section menu for the current section."""
validate_supplied_values('section_menu', max_levels=max_levels,
use_specific=use_specific)
if not show_multiple_levels:
max_levels = 1
menu_class = settings.objects.SECTION_MENU_CLASS
return menu_class.render_from_tag(
context=context,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template,
sub_menu_template_name=sub_menu_template,
sub_menu_template_names=split_if_string(sub_menu_templates),
show_section_root=show_section_root,
**kwargs
)
|
python
|
def section_menu(
context, show_section_root=True, show_multiple_levels=True,
apply_active_classes=True, allow_repeating_parents=True,
max_levels=settings.DEFAULT_SECTION_MENU_MAX_LEVELS,
template='', sub_menu_template='', sub_menu_templates=None,
use_specific=settings.DEFAULT_SECTION_MENU_USE_SPECIFIC,
use_absolute_page_urls=False, add_sub_menus_inline=None, **kwargs
):
"""Render a section menu for the current section."""
validate_supplied_values('section_menu', max_levels=max_levels,
use_specific=use_specific)
if not show_multiple_levels:
max_levels = 1
menu_class = settings.objects.SECTION_MENU_CLASS
return menu_class.render_from_tag(
context=context,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template,
sub_menu_template_name=sub_menu_template,
sub_menu_template_names=split_if_string(sub_menu_templates),
show_section_root=show_section_root,
**kwargs
)
|
[
"def",
"section_menu",
"(",
"context",
",",
"show_section_root",
"=",
"True",
",",
"show_multiple_levels",
"=",
"True",
",",
"apply_active_classes",
"=",
"True",
",",
"allow_repeating_parents",
"=",
"True",
",",
"max_levels",
"=",
"settings",
".",
"DEFAULT_SECTION_MENU_MAX_LEVELS",
",",
"template",
"=",
"''",
",",
"sub_menu_template",
"=",
"''",
",",
"sub_menu_templates",
"=",
"None",
",",
"use_specific",
"=",
"settings",
".",
"DEFAULT_SECTION_MENU_USE_SPECIFIC",
",",
"use_absolute_page_urls",
"=",
"False",
",",
"add_sub_menus_inline",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"validate_supplied_values",
"(",
"'section_menu'",
",",
"max_levels",
"=",
"max_levels",
",",
"use_specific",
"=",
"use_specific",
")",
"if",
"not",
"show_multiple_levels",
":",
"max_levels",
"=",
"1",
"menu_class",
"=",
"settings",
".",
"objects",
".",
"SECTION_MENU_CLASS",
"return",
"menu_class",
".",
"render_from_tag",
"(",
"context",
"=",
"context",
",",
"max_levels",
"=",
"max_levels",
",",
"use_specific",
"=",
"use_specific",
",",
"apply_active_classes",
"=",
"apply_active_classes",
",",
"allow_repeating_parents",
"=",
"allow_repeating_parents",
",",
"use_absolute_page_urls",
"=",
"use_absolute_page_urls",
",",
"add_sub_menus_inline",
"=",
"add_sub_menus_inline",
",",
"template_name",
"=",
"template",
",",
"sub_menu_template_name",
"=",
"sub_menu_template",
",",
"sub_menu_template_names",
"=",
"split_if_string",
"(",
"sub_menu_templates",
")",
",",
"show_section_root",
"=",
"show_section_root",
",",
"*",
"*",
"kwargs",
")"
] |
Render a section menu for the current section.
|
[
"Render",
"a",
"section",
"menu",
"for",
"the",
"current",
"section",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/templatetags/menu_tags.py#L84-L113
|
17,549
|
rkhleics/wagtailmenus
|
wagtailmenus/templatetags/menu_tags.py
|
sub_menu
|
def sub_menu(
context, menuitem_or_page, use_specific=None, allow_repeating_parents=None,
apply_active_classes=None, template='', use_absolute_page_urls=None,
add_sub_menus_inline=None, **kwargs
):
"""
Retrieve the children pages for the `menuitem_or_page` provided, turn them
into menu items, and render them to a template.
"""
validate_supplied_values('sub_menu', use_specific=use_specific,
menuitem_or_page=menuitem_or_page)
max_levels = context.get(
'max_levels', settings.DEFAULT_CHILDREN_MENU_MAX_LEVELS
)
if use_specific is None:
use_specific = context.get(
'use_specific', constants.USE_SPECIFIC_AUTO)
if apply_active_classes is None:
apply_active_classes = context.get('apply_active_classes', True)
if allow_repeating_parents is None:
allow_repeating_parents = context.get('allow_repeating_parents', True)
if use_absolute_page_urls is None:
use_absolute_page_urls = context.get('use_absolute_page_urls', False)
if add_sub_menus_inline is None:
add_sub_menus_inline = context.get('add_sub_menus_inline', False)
if isinstance(menuitem_or_page, Page):
parent_page = menuitem_or_page
else:
parent_page = menuitem_or_page.link_page
original_menu = context.get('original_menu_instance')
if original_menu is None:
raise SubMenuUsageError()
menu_class = original_menu.get_sub_menu_class()
return menu_class.render_from_tag(
context=context,
parent_page=parent_page,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template,
**kwargs
)
|
python
|
def sub_menu(
context, menuitem_or_page, use_specific=None, allow_repeating_parents=None,
apply_active_classes=None, template='', use_absolute_page_urls=None,
add_sub_menus_inline=None, **kwargs
):
"""
Retrieve the children pages for the `menuitem_or_page` provided, turn them
into menu items, and render them to a template.
"""
validate_supplied_values('sub_menu', use_specific=use_specific,
menuitem_or_page=menuitem_or_page)
max_levels = context.get(
'max_levels', settings.DEFAULT_CHILDREN_MENU_MAX_LEVELS
)
if use_specific is None:
use_specific = context.get(
'use_specific', constants.USE_SPECIFIC_AUTO)
if apply_active_classes is None:
apply_active_classes = context.get('apply_active_classes', True)
if allow_repeating_parents is None:
allow_repeating_parents = context.get('allow_repeating_parents', True)
if use_absolute_page_urls is None:
use_absolute_page_urls = context.get('use_absolute_page_urls', False)
if add_sub_menus_inline is None:
add_sub_menus_inline = context.get('add_sub_menus_inline', False)
if isinstance(menuitem_or_page, Page):
parent_page = menuitem_or_page
else:
parent_page = menuitem_or_page.link_page
original_menu = context.get('original_menu_instance')
if original_menu is None:
raise SubMenuUsageError()
menu_class = original_menu.get_sub_menu_class()
return menu_class.render_from_tag(
context=context,
parent_page=parent_page,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template,
**kwargs
)
|
[
"def",
"sub_menu",
"(",
"context",
",",
"menuitem_or_page",
",",
"use_specific",
"=",
"None",
",",
"allow_repeating_parents",
"=",
"None",
",",
"apply_active_classes",
"=",
"None",
",",
"template",
"=",
"''",
",",
"use_absolute_page_urls",
"=",
"None",
",",
"add_sub_menus_inline",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"validate_supplied_values",
"(",
"'sub_menu'",
",",
"use_specific",
"=",
"use_specific",
",",
"menuitem_or_page",
"=",
"menuitem_or_page",
")",
"max_levels",
"=",
"context",
".",
"get",
"(",
"'max_levels'",
",",
"settings",
".",
"DEFAULT_CHILDREN_MENU_MAX_LEVELS",
")",
"if",
"use_specific",
"is",
"None",
":",
"use_specific",
"=",
"context",
".",
"get",
"(",
"'use_specific'",
",",
"constants",
".",
"USE_SPECIFIC_AUTO",
")",
"if",
"apply_active_classes",
"is",
"None",
":",
"apply_active_classes",
"=",
"context",
".",
"get",
"(",
"'apply_active_classes'",
",",
"True",
")",
"if",
"allow_repeating_parents",
"is",
"None",
":",
"allow_repeating_parents",
"=",
"context",
".",
"get",
"(",
"'allow_repeating_parents'",
",",
"True",
")",
"if",
"use_absolute_page_urls",
"is",
"None",
":",
"use_absolute_page_urls",
"=",
"context",
".",
"get",
"(",
"'use_absolute_page_urls'",
",",
"False",
")",
"if",
"add_sub_menus_inline",
"is",
"None",
":",
"add_sub_menus_inline",
"=",
"context",
".",
"get",
"(",
"'add_sub_menus_inline'",
",",
"False",
")",
"if",
"isinstance",
"(",
"menuitem_or_page",
",",
"Page",
")",
":",
"parent_page",
"=",
"menuitem_or_page",
"else",
":",
"parent_page",
"=",
"menuitem_or_page",
".",
"link_page",
"original_menu",
"=",
"context",
".",
"get",
"(",
"'original_menu_instance'",
")",
"if",
"original_menu",
"is",
"None",
":",
"raise",
"SubMenuUsageError",
"(",
")",
"menu_class",
"=",
"original_menu",
".",
"get_sub_menu_class",
"(",
")",
"return",
"menu_class",
".",
"render_from_tag",
"(",
"context",
"=",
"context",
",",
"parent_page",
"=",
"parent_page",
",",
"max_levels",
"=",
"max_levels",
",",
"use_specific",
"=",
"use_specific",
",",
"apply_active_classes",
"=",
"apply_active_classes",
",",
"allow_repeating_parents",
"=",
"allow_repeating_parents",
",",
"use_absolute_page_urls",
"=",
"use_absolute_page_urls",
",",
"add_sub_menus_inline",
"=",
"add_sub_menus_inline",
",",
"template_name",
"=",
"template",
",",
"*",
"*",
"kwargs",
")"
] |
Retrieve the children pages for the `menuitem_or_page` provided, turn them
into menu items, and render them to a template.
|
[
"Retrieve",
"the",
"children",
"pages",
"for",
"the",
"menuitem_or_page",
"provided",
"turn",
"them",
"into",
"menu",
"items",
"and",
"render",
"them",
"to",
"a",
"template",
"."
] |
a41f240bed0d362e0d4dd4ef04a230f2b1827a93
|
https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/templatetags/menu_tags.py#L147-L200
|
17,550
|
opentracing-contrib/python-flask
|
flask_opentracing/tracing.py
|
FlaskTracing.trace
|
def trace(self, *attributes):
"""
Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span
"""
def decorator(f):
def wrapper(*args, **kwargs):
if self._trace_all_requests:
return f(*args, **kwargs)
self._before_request_fn(list(attributes))
try:
r = f(*args, **kwargs)
self._after_request_fn()
except Exception as e:
self._after_request_fn(error=e)
raise
self._after_request_fn()
return r
wrapper.__name__ = f.__name__
return wrapper
return decorator
|
python
|
def trace(self, *attributes):
"""
Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span
"""
def decorator(f):
def wrapper(*args, **kwargs):
if self._trace_all_requests:
return f(*args, **kwargs)
self._before_request_fn(list(attributes))
try:
r = f(*args, **kwargs)
self._after_request_fn()
except Exception as e:
self._after_request_fn(error=e)
raise
self._after_request_fn()
return r
wrapper.__name__ = f.__name__
return wrapper
return decorator
|
[
"def",
"trace",
"(",
"self",
",",
"*",
"attributes",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_trace_all_requests",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_before_request_fn",
"(",
"list",
"(",
"attributes",
")",
")",
"try",
":",
"r",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_after_request_fn",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_after_request_fn",
"(",
"error",
"=",
"e",
")",
"raise",
"self",
".",
"_after_request_fn",
"(",
")",
"return",
"r",
"wrapper",
".",
"__name__",
"=",
"f",
".",
"__name__",
"return",
"wrapper",
"return",
"decorator"
] |
Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span
|
[
"Function",
"decorator",
"that",
"traces",
"functions"
] |
74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca
|
https://github.com/opentracing-contrib/python-flask/blob/74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca/flask_opentracing/tracing.py#L66-L93
|
17,551
|
opentracing-contrib/python-flask
|
flask_opentracing/tracing.py
|
FlaskTracing.get_span
|
def get_span(self, request=None):
"""
Returns the span tracing `request`, or the current request if
`request==None`.
If there is no such span, get_span returns None.
@param request the request to get the span from
"""
if request is None and stack.top:
request = stack.top.request
scope = self._current_scopes.get(request, None)
return None if scope is None else scope.span
|
python
|
def get_span(self, request=None):
"""
Returns the span tracing `request`, or the current request if
`request==None`.
If there is no such span, get_span returns None.
@param request the request to get the span from
"""
if request is None and stack.top:
request = stack.top.request
scope = self._current_scopes.get(request, None)
return None if scope is None else scope.span
|
[
"def",
"get_span",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"if",
"request",
"is",
"None",
"and",
"stack",
".",
"top",
":",
"request",
"=",
"stack",
".",
"top",
".",
"request",
"scope",
"=",
"self",
".",
"_current_scopes",
".",
"get",
"(",
"request",
",",
"None",
")",
"return",
"None",
"if",
"scope",
"is",
"None",
"else",
"scope",
".",
"span"
] |
Returns the span tracing `request`, or the current request if
`request==None`.
If there is no such span, get_span returns None.
@param request the request to get the span from
|
[
"Returns",
"the",
"span",
"tracing",
"request",
"or",
"the",
"current",
"request",
"if",
"request",
"==",
"None",
"."
] |
74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca
|
https://github.com/opentracing-contrib/python-flask/blob/74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca/flask_opentracing/tracing.py#L95-L108
|
17,552
|
rsinger86/django-lifecycle
|
django_lifecycle/__init__.py
|
LifecycleModelMixin.initial_value
|
def initial_value(self, field_name: str = None):
"""
Get initial value of field when model was instantiated.
"""
if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':
if not field_name.endswith('_id'):
field_name = field_name+'_id'
attribute = self._diff_with_initial.get(field_name, None)
if not attribute:
return None
return attribute[0]
|
python
|
def initial_value(self, field_name: str = None):
"""
Get initial value of field when model was instantiated.
"""
if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':
if not field_name.endswith('_id'):
field_name = field_name+'_id'
attribute = self._diff_with_initial.get(field_name, None)
if not attribute:
return None
return attribute[0]
|
[
"def",
"initial_value",
"(",
"self",
",",
"field_name",
":",
"str",
"=",
"None",
")",
":",
"if",
"self",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
".",
"get_internal_type",
"(",
")",
"==",
"'ForeignKey'",
":",
"if",
"not",
"field_name",
".",
"endswith",
"(",
"'_id'",
")",
":",
"field_name",
"=",
"field_name",
"+",
"'_id'",
"attribute",
"=",
"self",
".",
"_diff_with_initial",
".",
"get",
"(",
"field_name",
",",
"None",
")",
"if",
"not",
"attribute",
":",
"return",
"None",
"return",
"attribute",
"[",
"0",
"]"
] |
Get initial value of field when model was instantiated.
|
[
"Get",
"initial",
"value",
"of",
"field",
"when",
"model",
"was",
"instantiated",
"."
] |
2196908ef0e242e52aab5bfaa3d337930700c106
|
https://github.com/rsinger86/django-lifecycle/blob/2196908ef0e242e52aab5bfaa3d337930700c106/django_lifecycle/__init__.py#L94-L107
|
17,553
|
rsinger86/django-lifecycle
|
django_lifecycle/__init__.py
|
LifecycleModelMixin.has_changed
|
def has_changed(self, field_name: str = None) -> bool:
"""
Check if a field has changed since the model was instantiated.
"""
changed = self._diff_with_initial.keys()
if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':
if not field_name.endswith('_id'):
field_name = field_name+'_id'
if field_name in changed:
return True
return False
|
python
|
def has_changed(self, field_name: str = None) -> bool:
"""
Check if a field has changed since the model was instantiated.
"""
changed = self._diff_with_initial.keys()
if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':
if not field_name.endswith('_id'):
field_name = field_name+'_id'
if field_name in changed:
return True
return False
|
[
"def",
"has_changed",
"(",
"self",
",",
"field_name",
":",
"str",
"=",
"None",
")",
"->",
"bool",
":",
"changed",
"=",
"self",
".",
"_diff_with_initial",
".",
"keys",
"(",
")",
"if",
"self",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
".",
"get_internal_type",
"(",
")",
"==",
"'ForeignKey'",
":",
"if",
"not",
"field_name",
".",
"endswith",
"(",
"'_id'",
")",
":",
"field_name",
"=",
"field_name",
"+",
"'_id'",
"if",
"field_name",
"in",
"changed",
":",
"return",
"True",
"return",
"False"
] |
Check if a field has changed since the model was instantiated.
|
[
"Check",
"if",
"a",
"field",
"has",
"changed",
"since",
"the",
"model",
"was",
"instantiated",
"."
] |
2196908ef0e242e52aab5bfaa3d337930700c106
|
https://github.com/rsinger86/django-lifecycle/blob/2196908ef0e242e52aab5bfaa3d337930700c106/django_lifecycle/__init__.py#L109-L122
|
17,554
|
rsinger86/django-lifecycle
|
django_lifecycle/__init__.py
|
LifecycleModelMixin._descriptor_names
|
def _descriptor_names(self):
"""
Attributes which are Django descriptors. These represent a field
which is a one-to-many or many-to-many relationship that is
potentially defined in another model, and doesn't otherwise appear
as a field on this model.
"""
descriptor_names = []
for name in dir(self):
try:
attr = getattr(type(self), name)
if isinstance(attr, DJANGO_RELATED_FIELD_DESCRIPTOR_CLASSES):
descriptor_names.append(name)
except AttributeError:
pass
return descriptor_names
|
python
|
def _descriptor_names(self):
"""
Attributes which are Django descriptors. These represent a field
which is a one-to-many or many-to-many relationship that is
potentially defined in another model, and doesn't otherwise appear
as a field on this model.
"""
descriptor_names = []
for name in dir(self):
try:
attr = getattr(type(self), name)
if isinstance(attr, DJANGO_RELATED_FIELD_DESCRIPTOR_CLASSES):
descriptor_names.append(name)
except AttributeError:
pass
return descriptor_names
|
[
"def",
"_descriptor_names",
"(",
"self",
")",
":",
"descriptor_names",
"=",
"[",
"]",
"for",
"name",
"in",
"dir",
"(",
"self",
")",
":",
"try",
":",
"attr",
"=",
"getattr",
"(",
"type",
"(",
"self",
")",
",",
"name",
")",
"if",
"isinstance",
"(",
"attr",
",",
"DJANGO_RELATED_FIELD_DESCRIPTOR_CLASSES",
")",
":",
"descriptor_names",
".",
"append",
"(",
"name",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"descriptor_names"
] |
Attributes which are Django descriptors. These represent a field
which is a one-to-many or many-to-many relationship that is
potentially defined in another model, and doesn't otherwise appear
as a field on this model.
|
[
"Attributes",
"which",
"are",
"Django",
"descriptors",
".",
"These",
"represent",
"a",
"field",
"which",
"is",
"a",
"one",
"-",
"to",
"-",
"many",
"or",
"many",
"-",
"to",
"-",
"many",
"relationship",
"that",
"is",
"potentially",
"defined",
"in",
"another",
"model",
"and",
"doesn",
"t",
"otherwise",
"appear",
"as",
"a",
"field",
"on",
"this",
"model",
"."
] |
2196908ef0e242e52aab5bfaa3d337930700c106
|
https://github.com/rsinger86/django-lifecycle/blob/2196908ef0e242e52aab5bfaa3d337930700c106/django_lifecycle/__init__.py#L181-L201
|
17,555
|
rsinger86/django-lifecycle
|
django_lifecycle/__init__.py
|
LifecycleModelMixin._run_hooked_methods
|
def _run_hooked_methods(self, hook: str):
"""
Iterate through decorated methods to find those that should be
triggered by the current hook. If conditions exist, check them before
running otherwise go ahead and run.
"""
for method in self._potentially_hooked_methods:
for callback_specs in method._hooked:
if callback_specs['hook'] != hook:
continue
when = callback_specs.get('when')
if when:
if self._check_callback_conditions(callback_specs):
method()
else:
method()
|
python
|
def _run_hooked_methods(self, hook: str):
"""
Iterate through decorated methods to find those that should be
triggered by the current hook. If conditions exist, check them before
running otherwise go ahead and run.
"""
for method in self._potentially_hooked_methods:
for callback_specs in method._hooked:
if callback_specs['hook'] != hook:
continue
when = callback_specs.get('when')
if when:
if self._check_callback_conditions(callback_specs):
method()
else:
method()
|
[
"def",
"_run_hooked_methods",
"(",
"self",
",",
"hook",
":",
"str",
")",
":",
"for",
"method",
"in",
"self",
".",
"_potentially_hooked_methods",
":",
"for",
"callback_specs",
"in",
"method",
".",
"_hooked",
":",
"if",
"callback_specs",
"[",
"'hook'",
"]",
"!=",
"hook",
":",
"continue",
"when",
"=",
"callback_specs",
".",
"get",
"(",
"'when'",
")",
"if",
"when",
":",
"if",
"self",
".",
"_check_callback_conditions",
"(",
"callback_specs",
")",
":",
"method",
"(",
")",
"else",
":",
"method",
"(",
")"
] |
Iterate through decorated methods to find those that should be
triggered by the current hook. If conditions exist, check them before
running otherwise go ahead and run.
|
[
"Iterate",
"through",
"decorated",
"methods",
"to",
"find",
"those",
"that",
"should",
"be",
"triggered",
"by",
"the",
"current",
"hook",
".",
"If",
"conditions",
"exist",
"check",
"them",
"before",
"running",
"otherwise",
"go",
"ahead",
"and",
"run",
"."
] |
2196908ef0e242e52aab5bfaa3d337930700c106
|
https://github.com/rsinger86/django-lifecycle/blob/2196908ef0e242e52aab5bfaa3d337930700c106/django_lifecycle/__init__.py#L228-L245
|
17,556
|
llimllib/limbo
|
limbo/limbo.py
|
loop
|
def loop(server, test_loop=None):
"""Run the main loop
server is a limbo Server object
test_loop, if present, is a number of times to run the loop
"""
try:
loops_without_activity = 0
while test_loop is None or test_loop > 0:
start = time.time()
loops_without_activity += 1
events = server.slack.rtm_read()
for event in events:
loops_without_activity = 0
logger.debug("got {0}".format(event))
response = handle_event(event, server)
# The docs (https://api.slack.com/docs/message-threading)
# suggest looking for messages where `thread_ts` != `ts`,
# but I can't see anywhere that it would make a practical
# difference. If a message is part of a thread, respond to
# that thread.
thread_ts = None
if 'thread_ts' in event:
thread_ts = event['thread_ts']
while response:
# The Slack API documentation says:
#
# Clients should limit messages sent to channels to 4000
# characters, which will always be under 16k bytes even
# with a message comprised solely of non-BMP Unicode
# characters at 4 bytes each.
#
# but empirical testing shows that I'm getting disconnected
# at 4000 characters and even quite a bit lower. Use 1000
# to be safe
server.slack.rtm_send_message(event["channel"],
response[:1000], thread_ts)
response = response[1000:]
# Run the loop hook. This doesn't send messages it receives,
# because it doesn't know where to send them. Use
# server.slack.post_message to send messages from a loop hook
run_hook(server.hooks, "loop", server)
# The Slack RTM API docs say:
#
# > When there is no other activity clients should send a ping
# > every few seconds
#
# So, if we've gone >5 seconds without any activity, send a ping.
# If the connection has broken, this will reveal it so slack can
# quit
if loops_without_activity > 5:
server.slack.ping()
loops_without_activity = 0
end = time.time()
runtime = start - end
time.sleep(max(1 - runtime, 0))
if test_loop:
test_loop -= 1
except KeyboardInterrupt:
if os.environ.get("LIMBO_DEBUG"):
import ipdb
ipdb.set_trace()
raise
|
python
|
def loop(server, test_loop=None):
"""Run the main loop
server is a limbo Server object
test_loop, if present, is a number of times to run the loop
"""
try:
loops_without_activity = 0
while test_loop is None or test_loop > 0:
start = time.time()
loops_without_activity += 1
events = server.slack.rtm_read()
for event in events:
loops_without_activity = 0
logger.debug("got {0}".format(event))
response = handle_event(event, server)
# The docs (https://api.slack.com/docs/message-threading)
# suggest looking for messages where `thread_ts` != `ts`,
# but I can't see anywhere that it would make a practical
# difference. If a message is part of a thread, respond to
# that thread.
thread_ts = None
if 'thread_ts' in event:
thread_ts = event['thread_ts']
while response:
# The Slack API documentation says:
#
# Clients should limit messages sent to channels to 4000
# characters, which will always be under 16k bytes even
# with a message comprised solely of non-BMP Unicode
# characters at 4 bytes each.
#
# but empirical testing shows that I'm getting disconnected
# at 4000 characters and even quite a bit lower. Use 1000
# to be safe
server.slack.rtm_send_message(event["channel"],
response[:1000], thread_ts)
response = response[1000:]
# Run the loop hook. This doesn't send messages it receives,
# because it doesn't know where to send them. Use
# server.slack.post_message to send messages from a loop hook
run_hook(server.hooks, "loop", server)
# The Slack RTM API docs say:
#
# > When there is no other activity clients should send a ping
# > every few seconds
#
# So, if we've gone >5 seconds without any activity, send a ping.
# If the connection has broken, this will reveal it so slack can
# quit
if loops_without_activity > 5:
server.slack.ping()
loops_without_activity = 0
end = time.time()
runtime = start - end
time.sleep(max(1 - runtime, 0))
if test_loop:
test_loop -= 1
except KeyboardInterrupt:
if os.environ.get("LIMBO_DEBUG"):
import ipdb
ipdb.set_trace()
raise
|
[
"def",
"loop",
"(",
"server",
",",
"test_loop",
"=",
"None",
")",
":",
"try",
":",
"loops_without_activity",
"=",
"0",
"while",
"test_loop",
"is",
"None",
"or",
"test_loop",
">",
"0",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"loops_without_activity",
"+=",
"1",
"events",
"=",
"server",
".",
"slack",
".",
"rtm_read",
"(",
")",
"for",
"event",
"in",
"events",
":",
"loops_without_activity",
"=",
"0",
"logger",
".",
"debug",
"(",
"\"got {0}\"",
".",
"format",
"(",
"event",
")",
")",
"response",
"=",
"handle_event",
"(",
"event",
",",
"server",
")",
"# The docs (https://api.slack.com/docs/message-threading)",
"# suggest looking for messages where `thread_ts` != `ts`,",
"# but I can't see anywhere that it would make a practical",
"# difference. If a message is part of a thread, respond to",
"# that thread.",
"thread_ts",
"=",
"None",
"if",
"'thread_ts'",
"in",
"event",
":",
"thread_ts",
"=",
"event",
"[",
"'thread_ts'",
"]",
"while",
"response",
":",
"# The Slack API documentation says:",
"#",
"# Clients should limit messages sent to channels to 4000",
"# characters, which will always be under 16k bytes even",
"# with a message comprised solely of non-BMP Unicode",
"# characters at 4 bytes each.",
"#",
"# but empirical testing shows that I'm getting disconnected",
"# at 4000 characters and even quite a bit lower. Use 1000",
"# to be safe",
"server",
".",
"slack",
".",
"rtm_send_message",
"(",
"event",
"[",
"\"channel\"",
"]",
",",
"response",
"[",
":",
"1000",
"]",
",",
"thread_ts",
")",
"response",
"=",
"response",
"[",
"1000",
":",
"]",
"# Run the loop hook. This doesn't send messages it receives,",
"# because it doesn't know where to send them. Use",
"# server.slack.post_message to send messages from a loop hook",
"run_hook",
"(",
"server",
".",
"hooks",
",",
"\"loop\"",
",",
"server",
")",
"# The Slack RTM API docs say:",
"#",
"# > When there is no other activity clients should send a ping",
"# > every few seconds",
"#",
"# So, if we've gone >5 seconds without any activity, send a ping.",
"# If the connection has broken, this will reveal it so slack can",
"# quit",
"if",
"loops_without_activity",
">",
"5",
":",
"server",
".",
"slack",
".",
"ping",
"(",
")",
"loops_without_activity",
"=",
"0",
"end",
"=",
"time",
".",
"time",
"(",
")",
"runtime",
"=",
"start",
"-",
"end",
"time",
".",
"sleep",
"(",
"max",
"(",
"1",
"-",
"runtime",
",",
"0",
")",
")",
"if",
"test_loop",
":",
"test_loop",
"-=",
"1",
"except",
"KeyboardInterrupt",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"LIMBO_DEBUG\"",
")",
":",
"import",
"ipdb",
"ipdb",
".",
"set_trace",
"(",
")",
"raise"
] |
Run the main loop
server is a limbo Server object
test_loop, if present, is a number of times to run the loop
|
[
"Run",
"the",
"main",
"loop"
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/limbo.py#L189-L258
|
17,557
|
llimllib/limbo
|
limbo/slack.py
|
SlackClient.post_message
|
def post_message(self, channel_id, message, **kwargs):
"""
Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your message.
When using the post_message API, to have your message look like it's sent from your bot
you'll need to include the `as_user` kwarg. Example of how to do this:
server.slack.post_message(msg['channel'], 'My message', as_user=server.slack.username)
"""
params = {
"post_data": {
"text": message,
"channel": channel_id,
}
}
params["post_data"].update(kwargs)
return self.api_call("chat.postMessage", **params)
|
python
|
def post_message(self, channel_id, message, **kwargs):
"""
Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your message.
When using the post_message API, to have your message look like it's sent from your bot
you'll need to include the `as_user` kwarg. Example of how to do this:
server.slack.post_message(msg['channel'], 'My message', as_user=server.slack.username)
"""
params = {
"post_data": {
"text": message,
"channel": channel_id,
}
}
params["post_data"].update(kwargs)
return self.api_call("chat.postMessage", **params)
|
[
"def",
"post_message",
"(",
"self",
",",
"channel_id",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"\"post_data\"",
":",
"{",
"\"text\"",
":",
"message",
",",
"\"channel\"",
":",
"channel_id",
",",
"}",
"}",
"params",
"[",
"\"post_data\"",
"]",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"api_call",
"(",
"\"chat.postMessage\"",
",",
"*",
"*",
"params",
")"
] |
Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your message.
When using the post_message API, to have your message look like it's sent from your bot
you'll need to include the `as_user` kwarg. Example of how to do this:
server.slack.post_message(msg['channel'], 'My message', as_user=server.slack.username)
|
[
"Send",
"a",
"message",
"using",
"the",
"slack",
"Event",
"API",
"."
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/slack.py#L99-L119
|
17,558
|
llimllib/limbo
|
limbo/slack.py
|
SlackClient.post_reaction
|
def post_reaction(self, channel_id, timestamp, reaction_name, **kwargs):
"""
Send a reaction to a message using slack Event API
"""
params = {
"post_data": {
"name": reaction_name,
"channel": channel_id,
"timestamp": timestamp,
}
}
params["post_data"].update(kwargs)
return self.api_call("reactions.add", **params)
|
python
|
def post_reaction(self, channel_id, timestamp, reaction_name, **kwargs):
"""
Send a reaction to a message using slack Event API
"""
params = {
"post_data": {
"name": reaction_name,
"channel": channel_id,
"timestamp": timestamp,
}
}
params["post_data"].update(kwargs)
return self.api_call("reactions.add", **params)
|
[
"def",
"post_reaction",
"(",
"self",
",",
"channel_id",
",",
"timestamp",
",",
"reaction_name",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"\"post_data\"",
":",
"{",
"\"name\"",
":",
"reaction_name",
",",
"\"channel\"",
":",
"channel_id",
",",
"\"timestamp\"",
":",
"timestamp",
",",
"}",
"}",
"params",
"[",
"\"post_data\"",
"]",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"api_call",
"(",
"\"reactions.add\"",
",",
"*",
"*",
"params",
")"
] |
Send a reaction to a message using slack Event API
|
[
"Send",
"a",
"reaction",
"to",
"a",
"message",
"using",
"slack",
"Event",
"API"
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/slack.py#L121-L134
|
17,559
|
llimllib/limbo
|
limbo/slack.py
|
SlackClient.get_all
|
def get_all(self, api_method, collection_name, **kwargs):
"""
Return all objects in an api_method, handle pagination, and pass
kwargs on to the method being called.
For example, "users.list" returns an object like:
{
"members": [{<member_obj>}, {<member_obj_2>}],
"response_metadata": {
"next_cursor": "cursor_id"
}
}
so if you call `get_all("users.list", "members")`, this function
will return all member objects to you while handling pagination
"""
objs = []
limit = 250
# if you don't provide a limit, the slack API won't return a cursor to you
page = json.loads(self.api_call(api_method, limit=limit, **kwargs))
while 1:
try:
for obj in page[collection_name]:
objs.append(obj)
except KeyError:
LOG.error("Unable to find key %s in page object: \n"
"%s", collection_name, page)
return objs
cursor = dig(page, "response_metadata", "next_cursor")
if cursor:
# In general we allow applications that integrate with Slack to send
# no more than one message per second
# https://api.slack.com/docs/rate-limits
time.sleep(1)
page = json.loads(
self.api_call(
api_method, cursor=cursor, limit=limit, **kwargs))
else:
break
return objs
|
python
|
def get_all(self, api_method, collection_name, **kwargs):
"""
Return all objects in an api_method, handle pagination, and pass
kwargs on to the method being called.
For example, "users.list" returns an object like:
{
"members": [{<member_obj>}, {<member_obj_2>}],
"response_metadata": {
"next_cursor": "cursor_id"
}
}
so if you call `get_all("users.list", "members")`, this function
will return all member objects to you while handling pagination
"""
objs = []
limit = 250
# if you don't provide a limit, the slack API won't return a cursor to you
page = json.loads(self.api_call(api_method, limit=limit, **kwargs))
while 1:
try:
for obj in page[collection_name]:
objs.append(obj)
except KeyError:
LOG.error("Unable to find key %s in page object: \n"
"%s", collection_name, page)
return objs
cursor = dig(page, "response_metadata", "next_cursor")
if cursor:
# In general we allow applications that integrate with Slack to send
# no more than one message per second
# https://api.slack.com/docs/rate-limits
time.sleep(1)
page = json.loads(
self.api_call(
api_method, cursor=cursor, limit=limit, **kwargs))
else:
break
return objs
|
[
"def",
"get_all",
"(",
"self",
",",
"api_method",
",",
"collection_name",
",",
"*",
"*",
"kwargs",
")",
":",
"objs",
"=",
"[",
"]",
"limit",
"=",
"250",
"# if you don't provide a limit, the slack API won't return a cursor to you",
"page",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"api_call",
"(",
"api_method",
",",
"limit",
"=",
"limit",
",",
"*",
"*",
"kwargs",
")",
")",
"while",
"1",
":",
"try",
":",
"for",
"obj",
"in",
"page",
"[",
"collection_name",
"]",
":",
"objs",
".",
"append",
"(",
"obj",
")",
"except",
"KeyError",
":",
"LOG",
".",
"error",
"(",
"\"Unable to find key %s in page object: \\n\"",
"\"%s\"",
",",
"collection_name",
",",
"page",
")",
"return",
"objs",
"cursor",
"=",
"dig",
"(",
"page",
",",
"\"response_metadata\"",
",",
"\"next_cursor\"",
")",
"if",
"cursor",
":",
"# In general we allow applications that integrate with Slack to send",
"# no more than one message per second",
"# https://api.slack.com/docs/rate-limits",
"time",
".",
"sleep",
"(",
"1",
")",
"page",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"api_call",
"(",
"api_method",
",",
"cursor",
"=",
"cursor",
",",
"limit",
"=",
"limit",
",",
"*",
"*",
"kwargs",
")",
")",
"else",
":",
"break",
"return",
"objs"
] |
Return all objects in an api_method, handle pagination, and pass
kwargs on to the method being called.
For example, "users.list" returns an object like:
{
"members": [{<member_obj>}, {<member_obj_2>}],
"response_metadata": {
"next_cursor": "cursor_id"
}
}
so if you call `get_all("users.list", "members")`, this function
will return all member objects to you while handling pagination
|
[
"Return",
"all",
"objects",
"in",
"an",
"api_method",
"handle",
"pagination",
"and",
"pass",
"kwargs",
"on",
"to",
"the",
"method",
"being",
"called",
"."
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/slack.py#L182-L225
|
17,560
|
llimllib/limbo
|
limbo/plugins/poll.py
|
poll
|
def poll(poll, msg, server):
"""Given a question and answers, present a poll"""
poll = remove_smart_quotes(poll.replace(u"\u2014", u"--"))
try:
args = ARGPARSE.parse_args(shlex.split(poll)).poll
except ValueError:
return ERROR_INVALID_FORMAT
if not 2 < len(args) < len(POLL_EMOJIS) + 1:
return ERROR_WRONG_NUMBER_OF_ARGUMENTS
result = ["Poll: {}\n".format(args[0])]
for emoji, answer in zip(POLL_EMOJIS, args[1:]):
result.append(":{}: {}\n".format(emoji, answer))
# for this we are going to need to post the message to Slack via Web API in order to
# get the TS and add reactions
msg_posted = server.slack.post_message(
msg['channel'], "".join(result), as_user=server.slack.username)
ts = json.loads(msg_posted)["ts"]
for i in range(len(args) - 1):
server.slack.post_reaction(msg['channel'], ts, POLL_EMOJIS[i])
|
python
|
def poll(poll, msg, server):
"""Given a question and answers, present a poll"""
poll = remove_smart_quotes(poll.replace(u"\u2014", u"--"))
try:
args = ARGPARSE.parse_args(shlex.split(poll)).poll
except ValueError:
return ERROR_INVALID_FORMAT
if not 2 < len(args) < len(POLL_EMOJIS) + 1:
return ERROR_WRONG_NUMBER_OF_ARGUMENTS
result = ["Poll: {}\n".format(args[0])]
for emoji, answer in zip(POLL_EMOJIS, args[1:]):
result.append(":{}: {}\n".format(emoji, answer))
# for this we are going to need to post the message to Slack via Web API in order to
# get the TS and add reactions
msg_posted = server.slack.post_message(
msg['channel'], "".join(result), as_user=server.slack.username)
ts = json.loads(msg_posted)["ts"]
for i in range(len(args) - 1):
server.slack.post_reaction(msg['channel'], ts, POLL_EMOJIS[i])
|
[
"def",
"poll",
"(",
"poll",
",",
"msg",
",",
"server",
")",
":",
"poll",
"=",
"remove_smart_quotes",
"(",
"poll",
".",
"replace",
"(",
"u\"\\u2014\"",
",",
"u\"--\"",
")",
")",
"try",
":",
"args",
"=",
"ARGPARSE",
".",
"parse_args",
"(",
"shlex",
".",
"split",
"(",
"poll",
")",
")",
".",
"poll",
"except",
"ValueError",
":",
"return",
"ERROR_INVALID_FORMAT",
"if",
"not",
"2",
"<",
"len",
"(",
"args",
")",
"<",
"len",
"(",
"POLL_EMOJIS",
")",
"+",
"1",
":",
"return",
"ERROR_WRONG_NUMBER_OF_ARGUMENTS",
"result",
"=",
"[",
"\"Poll: {}\\n\"",
".",
"format",
"(",
"args",
"[",
"0",
"]",
")",
"]",
"for",
"emoji",
",",
"answer",
"in",
"zip",
"(",
"POLL_EMOJIS",
",",
"args",
"[",
"1",
":",
"]",
")",
":",
"result",
".",
"append",
"(",
"\":{}: {}\\n\"",
".",
"format",
"(",
"emoji",
",",
"answer",
")",
")",
"# for this we are going to need to post the message to Slack via Web API in order to",
"# get the TS and add reactions",
"msg_posted",
"=",
"server",
".",
"slack",
".",
"post_message",
"(",
"msg",
"[",
"'channel'",
"]",
",",
"\"\"",
".",
"join",
"(",
"result",
")",
",",
"as_user",
"=",
"server",
".",
"slack",
".",
"username",
")",
"ts",
"=",
"json",
".",
"loads",
"(",
"msg_posted",
")",
"[",
"\"ts\"",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"args",
")",
"-",
"1",
")",
":",
"server",
".",
"slack",
".",
"post_reaction",
"(",
"msg",
"[",
"'channel'",
"]",
",",
"ts",
",",
"POLL_EMOJIS",
"[",
"i",
"]",
")"
] |
Given a question and answers, present a poll
|
[
"Given",
"a",
"question",
"and",
"answers",
"present",
"a",
"poll"
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/poll.py#L28-L50
|
17,561
|
llimllib/limbo
|
limbo/plugins/emoji.py
|
emoji_list
|
def emoji_list(server, n=1):
"""return a list of `n` random emoji"""
global EMOJI
if EMOJI is None:
EMOJI = EmojiCache(server)
return EMOJI.get(n)
|
python
|
def emoji_list(server, n=1):
"""return a list of `n` random emoji"""
global EMOJI
if EMOJI is None:
EMOJI = EmojiCache(server)
return EMOJI.get(n)
|
[
"def",
"emoji_list",
"(",
"server",
",",
"n",
"=",
"1",
")",
":",
"global",
"EMOJI",
"if",
"EMOJI",
"is",
"None",
":",
"EMOJI",
"=",
"EmojiCache",
"(",
"server",
")",
"return",
"EMOJI",
".",
"get",
"(",
"n",
")"
] |
return a list of `n` random emoji
|
[
"return",
"a",
"list",
"of",
"n",
"random",
"emoji"
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/emoji.py#L46-L51
|
17,562
|
llimllib/limbo
|
limbo/plugins/wiki.py
|
wiki
|
def wiki(searchterm):
"""return the top wiki search result for the term"""
searchterm = quote(searchterm)
url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json"
url = url.format(searchterm)
result = requests.get(url).json()
pages = result["query"]["search"]
# try to reject disambiguation pages
pages = [p for p in pages if 'may refer to' not in p["snippet"]]
if not pages:
return ""
page = quote(pages[0]["title"].encode("utf8"))
link = "http://en.wikipedia.org/wiki/{0}".format(page)
r = requests.get(
"http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}".
format(page)).json()
soup = BeautifulSoup(r["parse"]["text"]["*"], "html5lib")
p = soup.find('p').get_text()
p = p[:8000]
return u"{0}\n{1}".format(p, link)
|
python
|
def wiki(searchterm):
"""return the top wiki search result for the term"""
searchterm = quote(searchterm)
url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json"
url = url.format(searchterm)
result = requests.get(url).json()
pages = result["query"]["search"]
# try to reject disambiguation pages
pages = [p for p in pages if 'may refer to' not in p["snippet"]]
if not pages:
return ""
page = quote(pages[0]["title"].encode("utf8"))
link = "http://en.wikipedia.org/wiki/{0}".format(page)
r = requests.get(
"http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}".
format(page)).json()
soup = BeautifulSoup(r["parse"]["text"]["*"], "html5lib")
p = soup.find('p').get_text()
p = p[:8000]
return u"{0}\n{1}".format(p, link)
|
[
"def",
"wiki",
"(",
"searchterm",
")",
":",
"searchterm",
"=",
"quote",
"(",
"searchterm",
")",
"url",
"=",
"\"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json\"",
"url",
"=",
"url",
".",
"format",
"(",
"searchterm",
")",
"result",
"=",
"requests",
".",
"get",
"(",
"url",
")",
".",
"json",
"(",
")",
"pages",
"=",
"result",
"[",
"\"query\"",
"]",
"[",
"\"search\"",
"]",
"# try to reject disambiguation pages",
"pages",
"=",
"[",
"p",
"for",
"p",
"in",
"pages",
"if",
"'may refer to'",
"not",
"in",
"p",
"[",
"\"snippet\"",
"]",
"]",
"if",
"not",
"pages",
":",
"return",
"\"\"",
"page",
"=",
"quote",
"(",
"pages",
"[",
"0",
"]",
"[",
"\"title\"",
"]",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
"link",
"=",
"\"http://en.wikipedia.org/wiki/{0}\"",
".",
"format",
"(",
"page",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"\"http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}\"",
".",
"format",
"(",
"page",
")",
")",
".",
"json",
"(",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"r",
"[",
"\"parse\"",
"]",
"[",
"\"text\"",
"]",
"[",
"\"*\"",
"]",
",",
"\"html5lib\"",
")",
"p",
"=",
"soup",
".",
"find",
"(",
"'p'",
")",
".",
"get_text",
"(",
")",
"p",
"=",
"p",
"[",
":",
"8000",
"]",
"return",
"u\"{0}\\n{1}\"",
".",
"format",
"(",
"p",
",",
"link",
")"
] |
return the top wiki search result for the term
|
[
"return",
"the",
"top",
"wiki",
"search",
"result",
"for",
"the",
"term"
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/wiki.py#L12-L39
|
17,563
|
llimllib/limbo
|
limbo/plugins/gif.py
|
gif
|
def gif(search, unsafe=False):
"""given a search string, return a gif URL via google search"""
searchb = quote(search.encode("utf8"))
safe = "&safe=" if unsafe else "&safe=active"
searchurl = "https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}" \
.format(searchb, safe)
# this is an old iphone user agent. Seems to make google return good results.
useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)" \
" AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"
result = requests.get(searchurl, headers={"User-agent": useragent}).text
gifs = list(map(unescape, re.findall(r"var u='(.*?)'", result)))
shuffle(gifs)
if gifs:
return gifs[0]
return ""
|
python
|
def gif(search, unsafe=False):
"""given a search string, return a gif URL via google search"""
searchb = quote(search.encode("utf8"))
safe = "&safe=" if unsafe else "&safe=active"
searchurl = "https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}" \
.format(searchb, safe)
# this is an old iphone user agent. Seems to make google return good results.
useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)" \
" AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"
result = requests.get(searchurl, headers={"User-agent": useragent}).text
gifs = list(map(unescape, re.findall(r"var u='(.*?)'", result)))
shuffle(gifs)
if gifs:
return gifs[0]
return ""
|
[
"def",
"gif",
"(",
"search",
",",
"unsafe",
"=",
"False",
")",
":",
"searchb",
"=",
"quote",
"(",
"search",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
"safe",
"=",
"\"&safe=\"",
"if",
"unsafe",
"else",
"\"&safe=active\"",
"searchurl",
"=",
"\"https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}\"",
".",
"format",
"(",
"searchb",
",",
"safe",
")",
"# this is an old iphone user agent. Seems to make google return good results.",
"useragent",
"=",
"\"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)\"",
"\" AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7\"",
"result",
"=",
"requests",
".",
"get",
"(",
"searchurl",
",",
"headers",
"=",
"{",
"\"User-agent\"",
":",
"useragent",
"}",
")",
".",
"text",
"gifs",
"=",
"list",
"(",
"map",
"(",
"unescape",
",",
"re",
".",
"findall",
"(",
"r\"var u='(.*?)'\"",
",",
"result",
")",
")",
")",
"shuffle",
"(",
"gifs",
")",
"if",
"gifs",
":",
"return",
"gifs",
"[",
"0",
"]",
"return",
"\"\""
] |
given a search string, return a gif URL via google search
|
[
"given",
"a",
"search",
"string",
"return",
"a",
"gif",
"URL",
"via",
"google",
"search"
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/gif.py#L19-L38
|
17,564
|
llimllib/limbo
|
limbo/plugins/gif.py
|
on_message
|
def on_message(msg, server):
"""handle a message and return an gif"""
text = msg.get("text", "")
match = re.findall(r"!gif (.*)", text)
if not match:
return
res = gif(match[0])
if not res:
return
attachment = {
"fallback": match[0],
"title": match[0],
"title_link": res,
"image_url": res
}
server.slack.post_message(
msg['channel'],
'',
as_user=server.slack.username,
attachments=json.dumps([attachment]))
|
python
|
def on_message(msg, server):
"""handle a message and return an gif"""
text = msg.get("text", "")
match = re.findall(r"!gif (.*)", text)
if not match:
return
res = gif(match[0])
if not res:
return
attachment = {
"fallback": match[0],
"title": match[0],
"title_link": res,
"image_url": res
}
server.slack.post_message(
msg['channel'],
'',
as_user=server.slack.username,
attachments=json.dumps([attachment]))
|
[
"def",
"on_message",
"(",
"msg",
",",
"server",
")",
":",
"text",
"=",
"msg",
".",
"get",
"(",
"\"text\"",
",",
"\"\"",
")",
"match",
"=",
"re",
".",
"findall",
"(",
"r\"!gif (.*)\"",
",",
"text",
")",
"if",
"not",
"match",
":",
"return",
"res",
"=",
"gif",
"(",
"match",
"[",
"0",
"]",
")",
"if",
"not",
"res",
":",
"return",
"attachment",
"=",
"{",
"\"fallback\"",
":",
"match",
"[",
"0",
"]",
",",
"\"title\"",
":",
"match",
"[",
"0",
"]",
",",
"\"title_link\"",
":",
"res",
",",
"\"image_url\"",
":",
"res",
"}",
"server",
".",
"slack",
".",
"post_message",
"(",
"msg",
"[",
"'channel'",
"]",
",",
"''",
",",
"as_user",
"=",
"server",
".",
"slack",
".",
"username",
",",
"attachments",
"=",
"json",
".",
"dumps",
"(",
"[",
"attachment",
"]",
")",
")"
] |
handle a message and return an gif
|
[
"handle",
"a",
"message",
"and",
"return",
"an",
"gif"
] |
f0980f20f733b670debcae454b167da32c57a044
|
https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/gif.py#L41-L62
|
17,565
|
btel/svg_utils
|
src/svgutils/transform.py
|
fromfile
|
def fromfile(fname):
"""Open SVG figure from file.
Parameters
----------
fname : str
name of the SVG file
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the file content
"""
fig = SVGFigure()
with open(fname) as fid:
svg_file = etree.parse(fid)
fig.root = svg_file.getroot()
return fig
|
python
|
def fromfile(fname):
"""Open SVG figure from file.
Parameters
----------
fname : str
name of the SVG file
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the file content
"""
fig = SVGFigure()
with open(fname) as fid:
svg_file = etree.parse(fid)
fig.root = svg_file.getroot()
return fig
|
[
"def",
"fromfile",
"(",
"fname",
")",
":",
"fig",
"=",
"SVGFigure",
"(",
")",
"with",
"open",
"(",
"fname",
")",
"as",
"fid",
":",
"svg_file",
"=",
"etree",
".",
"parse",
"(",
"fid",
")",
"fig",
".",
"root",
"=",
"svg_file",
".",
"getroot",
"(",
")",
"return",
"fig"
] |
Open SVG figure from file.
Parameters
----------
fname : str
name of the SVG file
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the file content
|
[
"Open",
"SVG",
"figure",
"from",
"file",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L294-L312
|
17,566
|
btel/svg_utils
|
src/svgutils/transform.py
|
fromstring
|
def fromstring(text):
"""Create a SVG figure from a string.
Parameters
----------
text : str
string representing the SVG content. Must be valid SVG.
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
"""
fig = SVGFigure()
svg = etree.fromstring(text.encode())
fig.root = svg
return fig
|
python
|
def fromstring(text):
"""Create a SVG figure from a string.
Parameters
----------
text : str
string representing the SVG content. Must be valid SVG.
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
"""
fig = SVGFigure()
svg = etree.fromstring(text.encode())
fig.root = svg
return fig
|
[
"def",
"fromstring",
"(",
"text",
")",
":",
"fig",
"=",
"SVGFigure",
"(",
")",
"svg",
"=",
"etree",
".",
"fromstring",
"(",
"text",
".",
"encode",
"(",
")",
")",
"fig",
".",
"root",
"=",
"svg",
"return",
"fig"
] |
Create a SVG figure from a string.
Parameters
----------
text : str
string representing the SVG content. Must be valid SVG.
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
|
[
"Create",
"a",
"SVG",
"figure",
"from",
"a",
"string",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L315-L334
|
17,567
|
btel/svg_utils
|
src/svgutils/transform.py
|
from_mpl
|
def from_mpl(fig, savefig_kw=None):
"""Create a SVG figure from a ``matplotlib`` figure.
Parameters
----------
fig : matplotlib.Figure instance
savefig_kw : dict
keyword arguments to be passed to matplotlib's
`savefig`
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
Examples
--------
If you want to overlay the figure on another SVG, you may want to pass
the `transparent` option:
>>> from svgutils import transform
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> line, = plt.plot([1,2])
>>> svgfig = transform.from_mpl(fig,
... savefig_kw=dict(transparent=True))
>>> svgfig.getroot()
<svgutils.transform.GroupElement object at ...>
"""
fid = StringIO()
if savefig_kw is None:
savefig_kw = {}
try:
fig.savefig(fid, format='svg', **savefig_kw)
except ValueError:
raise(ValueError, "No matplotlib SVG backend")
fid.seek(0)
fig = fromstring(fid.read())
# workaround mpl units bug
w, h = fig.get_size()
fig.set_size((w.replace('pt', ''), h.replace('pt', '')))
return fig
|
python
|
def from_mpl(fig, savefig_kw=None):
"""Create a SVG figure from a ``matplotlib`` figure.
Parameters
----------
fig : matplotlib.Figure instance
savefig_kw : dict
keyword arguments to be passed to matplotlib's
`savefig`
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
Examples
--------
If you want to overlay the figure on another SVG, you may want to pass
the `transparent` option:
>>> from svgutils import transform
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> line, = plt.plot([1,2])
>>> svgfig = transform.from_mpl(fig,
... savefig_kw=dict(transparent=True))
>>> svgfig.getroot()
<svgutils.transform.GroupElement object at ...>
"""
fid = StringIO()
if savefig_kw is None:
savefig_kw = {}
try:
fig.savefig(fid, format='svg', **savefig_kw)
except ValueError:
raise(ValueError, "No matplotlib SVG backend")
fid.seek(0)
fig = fromstring(fid.read())
# workaround mpl units bug
w, h = fig.get_size()
fig.set_size((w.replace('pt', ''), h.replace('pt', '')))
return fig
|
[
"def",
"from_mpl",
"(",
"fig",
",",
"savefig_kw",
"=",
"None",
")",
":",
"fid",
"=",
"StringIO",
"(",
")",
"if",
"savefig_kw",
"is",
"None",
":",
"savefig_kw",
"=",
"{",
"}",
"try",
":",
"fig",
".",
"savefig",
"(",
"fid",
",",
"format",
"=",
"'svg'",
",",
"*",
"*",
"savefig_kw",
")",
"except",
"ValueError",
":",
"raise",
"(",
"ValueError",
",",
"\"No matplotlib SVG backend\"",
")",
"fid",
".",
"seek",
"(",
"0",
")",
"fig",
"=",
"fromstring",
"(",
"fid",
".",
"read",
"(",
")",
")",
"# workaround mpl units bug",
"w",
",",
"h",
"=",
"fig",
".",
"get_size",
"(",
")",
"fig",
".",
"set_size",
"(",
"(",
"w",
".",
"replace",
"(",
"'pt'",
",",
"''",
")",
",",
"h",
".",
"replace",
"(",
"'pt'",
",",
"''",
")",
")",
")",
"return",
"fig"
] |
Create a SVG figure from a ``matplotlib`` figure.
Parameters
----------
fig : matplotlib.Figure instance
savefig_kw : dict
keyword arguments to be passed to matplotlib's
`savefig`
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
Examples
--------
If you want to overlay the figure on another SVG, you may want to pass
the `transparent` option:
>>> from svgutils import transform
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> line, = plt.plot([1,2])
>>> svgfig = transform.from_mpl(fig,
... savefig_kw=dict(transparent=True))
>>> svgfig.getroot()
<svgutils.transform.GroupElement object at ...>
|
[
"Create",
"a",
"SVG",
"figure",
"from",
"a",
"matplotlib",
"figure",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L337-L390
|
17,568
|
btel/svg_utils
|
src/svgutils/transform.py
|
FigureElement.moveto
|
def moveto(self, x, y, scale=1):
"""Move and scale element.
Parameters
----------
x, y : float
displacement in x and y coordinates in user units ('px').
scale : float
scaling factor. To scale down scale < 1, scale up scale > 1.
For no scaling scale = 1.
"""
self.root.set("transform", "translate(%s, %s) scale(%s) %s" %
(x, y, scale, self.root.get("transform") or ''))
|
python
|
def moveto(self, x, y, scale=1):
"""Move and scale element.
Parameters
----------
x, y : float
displacement in x and y coordinates in user units ('px').
scale : float
scaling factor. To scale down scale < 1, scale up scale > 1.
For no scaling scale = 1.
"""
self.root.set("transform", "translate(%s, %s) scale(%s) %s" %
(x, y, scale, self.root.get("transform") or ''))
|
[
"def",
"moveto",
"(",
"self",
",",
"x",
",",
"y",
",",
"scale",
"=",
"1",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"translate(%s, %s) scale(%s) %s\"",
"%",
"(",
"x",
",",
"y",
",",
"scale",
",",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
")",
")"
] |
Move and scale element.
Parameters
----------
x, y : float
displacement in x and y coordinates in user units ('px').
scale : float
scaling factor. To scale down scale < 1, scale up scale > 1.
For no scaling scale = 1.
|
[
"Move",
"and",
"scale",
"element",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L24-L36
|
17,569
|
btel/svg_utils
|
src/svgutils/transform.py
|
FigureElement.rotate
|
def rotate(self, angle, x=0, y=0):
"""Rotate element by given angle around given pivot.
Parameters
----------
angle : float
rotation angle in degrees
x, y : float
pivot coordinates in user coordinate system (defaults to top-left
corner of the figure)
"""
self.root.set("transform", "%s rotate(%f %f %f)" %
(self.root.get("transform") or '', angle, x, y))
|
python
|
def rotate(self, angle, x=0, y=0):
"""Rotate element by given angle around given pivot.
Parameters
----------
angle : float
rotation angle in degrees
x, y : float
pivot coordinates in user coordinate system (defaults to top-left
corner of the figure)
"""
self.root.set("transform", "%s rotate(%f %f %f)" %
(self.root.get("transform") or '', angle, x, y))
|
[
"def",
"rotate",
"(",
"self",
",",
"angle",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s rotate(%f %f %f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
",",
"angle",
",",
"x",
",",
"y",
")",
")"
] |
Rotate element by given angle around given pivot.
Parameters
----------
angle : float
rotation angle in degrees
x, y : float
pivot coordinates in user coordinate system (defaults to top-left
corner of the figure)
|
[
"Rotate",
"element",
"by",
"given",
"angle",
"around",
"given",
"pivot",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L38-L50
|
17,570
|
btel/svg_utils
|
src/svgutils/transform.py
|
FigureElement.skew
|
def skew(self, x=0, y=0):
"""Skew the element by x and y degrees
Convenience function which calls skew_x and skew_y
Parameters
----------
x,y : float, float
skew angle in degrees (default 0)
If an x/y angle is given as zero degrees, that transformation is omitted.
"""
if x is not 0:
self.skew_x(x)
if y is not 0:
self.skew_y(y)
return self
|
python
|
def skew(self, x=0, y=0):
"""Skew the element by x and y degrees
Convenience function which calls skew_x and skew_y
Parameters
----------
x,y : float, float
skew angle in degrees (default 0)
If an x/y angle is given as zero degrees, that transformation is omitted.
"""
if x is not 0:
self.skew_x(x)
if y is not 0:
self.skew_y(y)
return self
|
[
"def",
"skew",
"(",
"self",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"if",
"x",
"is",
"not",
"0",
":",
"self",
".",
"skew_x",
"(",
"x",
")",
"if",
"y",
"is",
"not",
"0",
":",
"self",
".",
"skew_y",
"(",
"y",
")",
"return",
"self"
] |
Skew the element by x and y degrees
Convenience function which calls skew_x and skew_y
Parameters
----------
x,y : float, float
skew angle in degrees (default 0)
If an x/y angle is given as zero degrees, that transformation is omitted.
|
[
"Skew",
"the",
"element",
"by",
"x",
"and",
"y",
"degrees",
"Convenience",
"function",
"which",
"calls",
"skew_x",
"and",
"skew_y"
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L52-L68
|
17,571
|
btel/svg_utils
|
src/svgutils/transform.py
|
FigureElement.skew_x
|
def skew_x(self, x):
"""Skew element along the x-axis by the given angle.
Parameters
----------
x : float
x-axis skew angle in degrees
"""
self.root.set("transform", "%s skewX(%f)" %
(self.root.get("transform") or '', x))
return self
|
python
|
def skew_x(self, x):
"""Skew element along the x-axis by the given angle.
Parameters
----------
x : float
x-axis skew angle in degrees
"""
self.root.set("transform", "%s skewX(%f)" %
(self.root.get("transform") or '', x))
return self
|
[
"def",
"skew_x",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s skewX(%f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
",",
"x",
")",
")",
"return",
"self"
] |
Skew element along the x-axis by the given angle.
Parameters
----------
x : float
x-axis skew angle in degrees
|
[
"Skew",
"element",
"along",
"the",
"x",
"-",
"axis",
"by",
"the",
"given",
"angle",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L70-L80
|
17,572
|
btel/svg_utils
|
src/svgutils/transform.py
|
FigureElement.skew_y
|
def skew_y(self, y):
"""Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
"""
self.root.set("transform", "%s skewY(%f)" %
(self.root.get("transform") or '', y))
return self
|
python
|
def skew_y(self, y):
"""Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
"""
self.root.set("transform", "%s skewY(%f)" %
(self.root.get("transform") or '', y))
return self
|
[
"def",
"skew_y",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s skewY(%f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
",",
"y",
")",
")",
"return",
"self"
] |
Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
|
[
"Skew",
"element",
"along",
"the",
"y",
"-",
"axis",
"by",
"the",
"given",
"angle",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L82-L92
|
17,573
|
btel/svg_utils
|
src/svgutils/transform.py
|
FigureElement.find_id
|
def find_id(self, element_id):
"""Find element by its id.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
FigureElement
one of the children element with the given ID."""
find = etree.XPath("//*[@id=$id]")
return FigureElement(find(self.root, id=element_id)[0])
|
python
|
def find_id(self, element_id):
"""Find element by its id.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
FigureElement
one of the children element with the given ID."""
find = etree.XPath("//*[@id=$id]")
return FigureElement(find(self.root, id=element_id)[0])
|
[
"def",
"find_id",
"(",
"self",
",",
"element_id",
")",
":",
"find",
"=",
"etree",
".",
"XPath",
"(",
"\"//*[@id=$id]\"",
")",
"return",
"FigureElement",
"(",
"find",
"(",
"self",
".",
"root",
",",
"id",
"=",
"element_id",
")",
"[",
"0",
"]",
")"
] |
Find element by its id.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
FigureElement
one of the children element with the given ID.
|
[
"Find",
"element",
"by",
"its",
"id",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L122-L135
|
17,574
|
btel/svg_utils
|
src/svgutils/transform.py
|
SVGFigure.append
|
def append(self, element):
"""Append new element to the SVG figure"""
try:
self.root.append(element.root)
except AttributeError:
self.root.append(GroupElement(element).root)
|
python
|
def append(self, element):
"""Append new element to the SVG figure"""
try:
self.root.append(element.root)
except AttributeError:
self.root.append(GroupElement(element).root)
|
[
"def",
"append",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"self",
".",
"root",
".",
"append",
"(",
"element",
".",
"root",
")",
"except",
"AttributeError",
":",
"self",
".",
"root",
".",
"append",
"(",
"GroupElement",
"(",
"element",
")",
".",
"root",
")"
] |
Append new element to the SVG figure
|
[
"Append",
"new",
"element",
"to",
"the",
"SVG",
"figure"
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L238-L243
|
17,575
|
btel/svg_utils
|
src/svgutils/transform.py
|
SVGFigure.getroot
|
def getroot(self):
"""Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
"""
if 'class' in self.root.attrib:
attrib = {'class': self.root.attrib['class']}
else:
attrib = None
return GroupElement(self.root.getchildren(), attrib=attrib)
|
python
|
def getroot(self):
"""Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
"""
if 'class' in self.root.attrib:
attrib = {'class': self.root.attrib['class']}
else:
attrib = None
return GroupElement(self.root.getchildren(), attrib=attrib)
|
[
"def",
"getroot",
"(",
"self",
")",
":",
"if",
"'class'",
"in",
"self",
".",
"root",
".",
"attrib",
":",
"attrib",
"=",
"{",
"'class'",
":",
"self",
".",
"root",
".",
"attrib",
"[",
"'class'",
"]",
"}",
"else",
":",
"attrib",
"=",
"None",
"return",
"GroupElement",
"(",
"self",
".",
"root",
".",
"getchildren",
"(",
")",
",",
"attrib",
"=",
"attrib",
")"
] |
Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
|
[
"Return",
"the",
"root",
"element",
"of",
"the",
"figure",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L245-L260
|
17,576
|
btel/svg_utils
|
src/svgutils/transform.py
|
SVGFigure.to_str
|
def to_str(self):
"""
Returns a string of the SVG figure.
"""
return etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True)
|
python
|
def to_str(self):
"""
Returns a string of the SVG figure.
"""
return etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True)
|
[
"def",
"to_str",
"(",
"self",
")",
":",
"return",
"etree",
".",
"tostring",
"(",
"self",
".",
"root",
",",
"xml_declaration",
"=",
"True",
",",
"standalone",
"=",
"True",
",",
"pretty_print",
"=",
"True",
")"
] |
Returns a string of the SVG figure.
|
[
"Returns",
"a",
"string",
"of",
"the",
"SVG",
"figure",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L262-L268
|
17,577
|
btel/svg_utils
|
src/svgutils/transform.py
|
SVGFigure.save
|
def save(self, fname):
"""Save figure to a file"""
out = etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True)
with open(fname, 'wb') as fid:
fid.write(out)
|
python
|
def save(self, fname):
"""Save figure to a file"""
out = etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True)
with open(fname, 'wb') as fid:
fid.write(out)
|
[
"def",
"save",
"(",
"self",
",",
"fname",
")",
":",
"out",
"=",
"etree",
".",
"tostring",
"(",
"self",
".",
"root",
",",
"xml_declaration",
"=",
"True",
",",
"standalone",
"=",
"True",
",",
"pretty_print",
"=",
"True",
")",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"fid",
":",
"fid",
".",
"write",
"(",
"out",
")"
] |
Save figure to a file
|
[
"Save",
"figure",
"to",
"a",
"file"
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L270-L276
|
17,578
|
btel/svg_utils
|
src/svgutils/transform.py
|
SVGFigure.set_size
|
def set_size(self, size):
"""Set figure size"""
w, h = size
self.root.set('width', w)
self.root.set('height', h)
|
python
|
def set_size(self, size):
"""Set figure size"""
w, h = size
self.root.set('width', w)
self.root.set('height', h)
|
[
"def",
"set_size",
"(",
"self",
",",
"size",
")",
":",
"w",
",",
"h",
"=",
"size",
"self",
".",
"root",
".",
"set",
"(",
"'width'",
",",
"w",
")",
"self",
".",
"root",
".",
"set",
"(",
"'height'",
",",
"h",
")"
] |
Set figure size
|
[
"Set",
"figure",
"size"
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L287-L291
|
17,579
|
btel/svg_utils
|
src/svgutils/compose.py
|
Element.find_id
|
def find_id(self, element_id):
"""Find a single element with the given ID.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
found element
"""
element = _transform.FigureElement.find_id(self, element_id)
return Element(element.root)
|
python
|
def find_id(self, element_id):
"""Find a single element with the given ID.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
found element
"""
element = _transform.FigureElement.find_id(self, element_id)
return Element(element.root)
|
[
"def",
"find_id",
"(",
"self",
",",
"element_id",
")",
":",
"element",
"=",
"_transform",
".",
"FigureElement",
".",
"find_id",
"(",
"self",
",",
"element_id",
")",
"return",
"Element",
"(",
"element",
".",
"root",
")"
] |
Find a single element with the given ID.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
found element
|
[
"Find",
"a",
"single",
"element",
"with",
"the",
"given",
"ID",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L67-L80
|
17,580
|
btel/svg_utils
|
src/svgutils/compose.py
|
Element.find_ids
|
def find_ids(self, element_ids):
"""Find elements with given IDs.
Parameters
----------
element_ids : list of strings
list of IDs to find
Returns
-------
a new `Panel` object which contains all the found elements.
"""
elements = [_transform.FigureElement.find_id(self, eid)
for eid in element_ids]
return Panel(*elements)
|
python
|
def find_ids(self, element_ids):
"""Find elements with given IDs.
Parameters
----------
element_ids : list of strings
list of IDs to find
Returns
-------
a new `Panel` object which contains all the found elements.
"""
elements = [_transform.FigureElement.find_id(self, eid)
for eid in element_ids]
return Panel(*elements)
|
[
"def",
"find_ids",
"(",
"self",
",",
"element_ids",
")",
":",
"elements",
"=",
"[",
"_transform",
".",
"FigureElement",
".",
"find_id",
"(",
"self",
",",
"eid",
")",
"for",
"eid",
"in",
"element_ids",
"]",
"return",
"Panel",
"(",
"*",
"elements",
")"
] |
Find elements with given IDs.
Parameters
----------
element_ids : list of strings
list of IDs to find
Returns
-------
a new `Panel` object which contains all the found elements.
|
[
"Find",
"elements",
"with",
"given",
"IDs",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L82-L96
|
17,581
|
btel/svg_utils
|
src/svgutils/compose.py
|
Figure.save
|
def save(self, fname):
"""Save figure to SVG file.
Parameters
----------
fname : str
Full path to file.
"""
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
element.save(os.path.join(CONFIG['figure.save_path'], fname))
|
python
|
def save(self, fname):
"""Save figure to SVG file.
Parameters
----------
fname : str
Full path to file.
"""
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
element.save(os.path.join(CONFIG['figure.save_path'], fname))
|
[
"def",
"save",
"(",
"self",
",",
"fname",
")",
":",
"element",
"=",
"_transform",
".",
"SVGFigure",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
"element",
".",
"append",
"(",
"self",
")",
"element",
".",
"save",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CONFIG",
"[",
"'figure.save_path'",
"]",
",",
"fname",
")",
")"
] |
Save figure to SVG file.
Parameters
----------
fname : str
Full path to file.
|
[
"Save",
"figure",
"to",
"SVG",
"file",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L292-L302
|
17,582
|
btel/svg_utils
|
src/svgutils/compose.py
|
Figure.tostr
|
def tostr(self):
"""Export SVG as a string"""
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
svgstr = element.to_str()
return svgstr
|
python
|
def tostr(self):
"""Export SVG as a string"""
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
svgstr = element.to_str()
return svgstr
|
[
"def",
"tostr",
"(",
"self",
")",
":",
"element",
"=",
"_transform",
".",
"SVGFigure",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
"element",
".",
"append",
"(",
"self",
")",
"svgstr",
"=",
"element",
".",
"to_str",
"(",
")",
"return",
"svgstr"
] |
Export SVG as a string
|
[
"Export",
"SVG",
"as",
"a",
"string"
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L304-L309
|
17,583
|
btel/svg_utils
|
src/svgutils/compose.py
|
Figure.tile
|
def tile(self, ncols, nrows):
"""Automatically tile the panels of the figure.
This will re-arranged all elements of the figure (first in the
hierarchy) so that they will uniformly cover the figure area.
Parameters
----------
ncols, nrows : type
The number of columns and rows to arange the elements into.
Notes
-----
ncols * nrows must be larger or equal to number of
elements, otherwise some elements will go outside the figure borders.
"""
dx = (self.width/ncols).to('px').value
dy = (self.height/nrows).to('px').value
ix, iy = 0, 0
for el in self:
el.move(dx*ix, dy*iy)
ix += 1
if ix >= ncols:
ix = 0
iy += 1
if iy > nrows:
break
return self
|
python
|
def tile(self, ncols, nrows):
"""Automatically tile the panels of the figure.
This will re-arranged all elements of the figure (first in the
hierarchy) so that they will uniformly cover the figure area.
Parameters
----------
ncols, nrows : type
The number of columns and rows to arange the elements into.
Notes
-----
ncols * nrows must be larger or equal to number of
elements, otherwise some elements will go outside the figure borders.
"""
dx = (self.width/ncols).to('px').value
dy = (self.height/nrows).to('px').value
ix, iy = 0, 0
for el in self:
el.move(dx*ix, dy*iy)
ix += 1
if ix >= ncols:
ix = 0
iy += 1
if iy > nrows:
break
return self
|
[
"def",
"tile",
"(",
"self",
",",
"ncols",
",",
"nrows",
")",
":",
"dx",
"=",
"(",
"self",
".",
"width",
"/",
"ncols",
")",
".",
"to",
"(",
"'px'",
")",
".",
"value",
"dy",
"=",
"(",
"self",
".",
"height",
"/",
"nrows",
")",
".",
"to",
"(",
"'px'",
")",
".",
"value",
"ix",
",",
"iy",
"=",
"0",
",",
"0",
"for",
"el",
"in",
"self",
":",
"el",
".",
"move",
"(",
"dx",
"*",
"ix",
",",
"dy",
"*",
"iy",
")",
"ix",
"+=",
"1",
"if",
"ix",
">=",
"ncols",
":",
"ix",
"=",
"0",
"iy",
"+=",
"1",
"if",
"iy",
">",
"nrows",
":",
"break",
"return",
"self"
] |
Automatically tile the panels of the figure.
This will re-arranged all elements of the figure (first in the
hierarchy) so that they will uniformly cover the figure area.
Parameters
----------
ncols, nrows : type
The number of columns and rows to arange the elements into.
Notes
-----
ncols * nrows must be larger or equal to number of
elements, otherwise some elements will go outside the figure borders.
|
[
"Automatically",
"tile",
"the",
"panels",
"of",
"the",
"figure",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L314-L342
|
17,584
|
btel/svg_utils
|
src/svgutils/compose.py
|
Unit.to
|
def to(self, unit):
"""Convert to a given unit.
Parameters
----------
unit : str
Name of the unit to convert to.
Returns
-------
u : Unit
new Unit object with the requested unit and computed value.
"""
u = Unit("0cm")
u.value = self.value/self.per_inch[self.unit]*self.per_inch[unit]
u.unit = unit
return u
|
python
|
def to(self, unit):
"""Convert to a given unit.
Parameters
----------
unit : str
Name of the unit to convert to.
Returns
-------
u : Unit
new Unit object with the requested unit and computed value.
"""
u = Unit("0cm")
u.value = self.value/self.per_inch[self.unit]*self.per_inch[unit]
u.unit = unit
return u
|
[
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"u",
"=",
"Unit",
"(",
"\"0cm\"",
")",
"u",
".",
"value",
"=",
"self",
".",
"value",
"/",
"self",
".",
"per_inch",
"[",
"self",
".",
"unit",
"]",
"*",
"self",
".",
"per_inch",
"[",
"unit",
"]",
"u",
".",
"unit",
"=",
"unit",
"return",
"u"
] |
Convert to a given unit.
Parameters
----------
unit : str
Name of the unit to convert to.
Returns
-------
u : Unit
new Unit object with the requested unit and computed value.
|
[
"Convert",
"to",
"a",
"given",
"unit",
"."
] |
ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3
|
https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L369-L385
|
17,585
|
Kozea/cairocffi
|
cairocffi/__init__.py
|
dlopen
|
def dlopen(ffi, *names):
"""Try various names for the same library, for different platforms."""
for name in names:
for lib_name in (name, 'lib' + name):
try:
path = ctypes.util.find_library(lib_name)
lib = ffi.dlopen(path or lib_name)
if lib:
return lib
except OSError:
pass
raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names))
|
python
|
def dlopen(ffi, *names):
"""Try various names for the same library, for different platforms."""
for name in names:
for lib_name in (name, 'lib' + name):
try:
path = ctypes.util.find_library(lib_name)
lib = ffi.dlopen(path or lib_name)
if lib:
return lib
except OSError:
pass
raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names))
|
[
"def",
"dlopen",
"(",
"ffi",
",",
"*",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"for",
"lib_name",
"in",
"(",
"name",
",",
"'lib'",
"+",
"name",
")",
":",
"try",
":",
"path",
"=",
"ctypes",
".",
"util",
".",
"find_library",
"(",
"lib_name",
")",
"lib",
"=",
"ffi",
".",
"dlopen",
"(",
"path",
"or",
"lib_name",
")",
"if",
"lib",
":",
"return",
"lib",
"except",
"OSError",
":",
"pass",
"raise",
"OSError",
"(",
"\"dlopen() failed to load a library: %s\"",
"%",
"' / '",
".",
"join",
"(",
"names",
")",
")"
] |
Try various names for the same library, for different platforms.
|
[
"Try",
"various",
"names",
"for",
"the",
"same",
"library",
"for",
"different",
"platforms",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/__init__.py#L25-L36
|
17,586
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.set_source_rgba
|
def set_source_rgba(self, red, green, blue, alpha=1):
"""Sets the source pattern within this context to a solid color.
This color will then be used for any subsequent drawing operation
until a new source pattern is set.
The color and alpha components are
floating point numbers in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
The default source pattern is opaque black,
(that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``).
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type red: float
:type green: float
:type blue: float
:type alpha: float
"""
cairo.cairo_set_source_rgba(self._pointer, red, green, blue, alpha)
self._check_status()
|
python
|
def set_source_rgba(self, red, green, blue, alpha=1):
"""Sets the source pattern within this context to a solid color.
This color will then be used for any subsequent drawing operation
until a new source pattern is set.
The color and alpha components are
floating point numbers in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
The default source pattern is opaque black,
(that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``).
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type red: float
:type green: float
:type blue: float
:type alpha: float
"""
cairo.cairo_set_source_rgba(self._pointer, red, green, blue, alpha)
self._check_status()
|
[
"def",
"set_source_rgba",
"(",
"self",
",",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
"=",
"1",
")",
":",
"cairo",
".",
"cairo_set_source_rgba",
"(",
"self",
".",
"_pointer",
",",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
")",
"self",
".",
"_check_status",
"(",
")"
] |
Sets the source pattern within this context to a solid color.
This color will then be used for any subsequent drawing operation
until a new source pattern is set.
The color and alpha components are
floating point numbers in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
The default source pattern is opaque black,
(that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``).
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type red: float
:type green: float
:type blue: float
:type alpha: float
|
[
"Sets",
"the",
"source",
"pattern",
"within",
"this",
"context",
"to",
"a",
"solid",
"color",
".",
"This",
"color",
"will",
"then",
"be",
"used",
"for",
"any",
"subsequent",
"drawing",
"operation",
"until",
"a",
"new",
"source",
"pattern",
"is",
"set",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L306-L331
|
17,587
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.get_dash
|
def get_dash(self):
"""Return the current dash pattern.
:returns:
A ``(dashes, offset)`` tuple of a list and a float.
:obj:`dashes` is a list of floats,
empty if no dashing is in effect.
"""
dashes = ffi.new('double[]', cairo.cairo_get_dash_count(self._pointer))
offset = ffi.new('double *')
cairo.cairo_get_dash(self._pointer, dashes, offset)
self._check_status()
return list(dashes), offset[0]
|
python
|
def get_dash(self):
"""Return the current dash pattern.
:returns:
A ``(dashes, offset)`` tuple of a list and a float.
:obj:`dashes` is a list of floats,
empty if no dashing is in effect.
"""
dashes = ffi.new('double[]', cairo.cairo_get_dash_count(self._pointer))
offset = ffi.new('double *')
cairo.cairo_get_dash(self._pointer, dashes, offset)
self._check_status()
return list(dashes), offset[0]
|
[
"def",
"get_dash",
"(",
"self",
")",
":",
"dashes",
"=",
"ffi",
".",
"new",
"(",
"'double[]'",
",",
"cairo",
".",
"cairo_get_dash_count",
"(",
"self",
".",
"_pointer",
")",
")",
"offset",
"=",
"ffi",
".",
"new",
"(",
"'double *'",
")",
"cairo",
".",
"cairo_get_dash",
"(",
"self",
".",
"_pointer",
",",
"dashes",
",",
"offset",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"list",
"(",
"dashes",
")",
",",
"offset",
"[",
"0",
"]"
] |
Return the current dash pattern.
:returns:
A ``(dashes, offset)`` tuple of a list and a float.
:obj:`dashes` is a list of floats,
empty if no dashing is in effect.
|
[
"Return",
"the",
"current",
"dash",
"pattern",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L472-L485
|
17,588
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.set_miter_limit
|
def set_miter_limit(self, limit):
"""Sets the current miter limit within the cairo context.
If the current line join style is set to :obj:`MITER <LINE_JOIN_MITER>`
(see :meth:`set_line_join`),
the miter limit is used to determine
whether the lines should be joined with a bevel instead of a miter.
Cairo divides the length of the miter by the line width.
If the result is greater than the miter limit,
the style is converted to a bevel.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default miter limit value is 10.0,
which will convert joins with interior angles less than 11 degrees
to bevels instead of miters.
For reference,
a miter limit of 2.0 makes the miter cutoff at 60 degrees,
and a miter limit of 1.414 makes the cutoff at 90 degrees.
A miter limit for a desired angle can be computed as:
``miter_limit = 1. / sin(angle / 2.)``
:param limit: The miter limit to set.
:type limit: float
"""
cairo.cairo_set_miter_limit(self._pointer, limit)
self._check_status()
|
python
|
def set_miter_limit(self, limit):
"""Sets the current miter limit within the cairo context.
If the current line join style is set to :obj:`MITER <LINE_JOIN_MITER>`
(see :meth:`set_line_join`),
the miter limit is used to determine
whether the lines should be joined with a bevel instead of a miter.
Cairo divides the length of the miter by the line width.
If the result is greater than the miter limit,
the style is converted to a bevel.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default miter limit value is 10.0,
which will convert joins with interior angles less than 11 degrees
to bevels instead of miters.
For reference,
a miter limit of 2.0 makes the miter cutoff at 60 degrees,
and a miter limit of 1.414 makes the cutoff at 90 degrees.
A miter limit for a desired angle can be computed as:
``miter_limit = 1. / sin(angle / 2.)``
:param limit: The miter limit to set.
:type limit: float
"""
cairo.cairo_set_miter_limit(self._pointer, limit)
self._check_status()
|
[
"def",
"set_miter_limit",
"(",
"self",
",",
"limit",
")",
":",
"cairo",
".",
"cairo_set_miter_limit",
"(",
"self",
".",
"_pointer",
",",
"limit",
")",
"self",
".",
"_check_status",
"(",
")"
] |
Sets the current miter limit within the cairo context.
If the current line join style is set to :obj:`MITER <LINE_JOIN_MITER>`
(see :meth:`set_line_join`),
the miter limit is used to determine
whether the lines should be joined with a bevel instead of a miter.
Cairo divides the length of the miter by the line width.
If the result is greater than the miter limit,
the style is converted to a bevel.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default miter limit value is 10.0,
which will convert joins with interior angles less than 11 degrees
to bevels instead of miters.
For reference,
a miter limit of 2.0 makes the miter cutoff at 60 degrees,
and a miter limit of 1.414 makes the cutoff at 90 degrees.
A miter limit for a desired angle can be computed as:
``miter_limit = 1. / sin(angle / 2.)``
:param limit: The miter limit to set.
:type limit: float
|
[
"Sets",
"the",
"current",
"miter",
"limit",
"within",
"the",
"cairo",
"context",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L587-L618
|
17,589
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.get_current_point
|
def get_current_point(self):
"""Return the current point of the current path,
which is conceptually the final point reached by the path so far.
The current point is returned in the user-space coordinate system.
If there is no defined current point
or if the context is in an error status,
``(0, 0)`` is returned.
It is possible to check this in advance with :meth:`has_current_point`.
Most path construction methods alter the current point.
See the following for details on how they affect the current point:
:meth:`new_path`,
:meth:`new_sub_path`,
:meth:`append_path`,
:meth:`close_path`,
:meth:`move_to`,
:meth:`line_to`,
:meth:`curve_to`,
:meth:`rel_move_to`,
:meth:`rel_line_to`,
:meth:`rel_curve_to`,
:meth:`arc`,
:meth:`arc_negative`,
:meth:`rectangle`,
:meth:`text_path`,
:meth:`glyph_path`,
:meth:`stroke_to_path`.
Some methods use and alter the current point
but do not otherwise change current path:
:meth:`show_text`,
:meth:`show_glyphs`,
:meth:`show_text_glyphs`.
Some methods unset the current path and as a result, current point:
:meth:`fill`,
:meth:`stroke`.
:returns:
A ``(x, y)`` tuple of floats, the coordinates of the current point.
"""
# I’d prefer returning None if self.has_current_point() is False
# But keep (0, 0) for compat with pycairo.
xy = ffi.new('double[2]')
cairo.cairo_get_current_point(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy)
|
python
|
def get_current_point(self):
"""Return the current point of the current path,
which is conceptually the final point reached by the path so far.
The current point is returned in the user-space coordinate system.
If there is no defined current point
or if the context is in an error status,
``(0, 0)`` is returned.
It is possible to check this in advance with :meth:`has_current_point`.
Most path construction methods alter the current point.
See the following for details on how they affect the current point:
:meth:`new_path`,
:meth:`new_sub_path`,
:meth:`append_path`,
:meth:`close_path`,
:meth:`move_to`,
:meth:`line_to`,
:meth:`curve_to`,
:meth:`rel_move_to`,
:meth:`rel_line_to`,
:meth:`rel_curve_to`,
:meth:`arc`,
:meth:`arc_negative`,
:meth:`rectangle`,
:meth:`text_path`,
:meth:`glyph_path`,
:meth:`stroke_to_path`.
Some methods use and alter the current point
but do not otherwise change current path:
:meth:`show_text`,
:meth:`show_glyphs`,
:meth:`show_text_glyphs`.
Some methods unset the current path and as a result, current point:
:meth:`fill`,
:meth:`stroke`.
:returns:
A ``(x, y)`` tuple of floats, the coordinates of the current point.
"""
# I’d prefer returning None if self.has_current_point() is False
# But keep (0, 0) for compat with pycairo.
xy = ffi.new('double[2]')
cairo.cairo_get_current_point(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy)
|
[
"def",
"get_current_point",
"(",
"self",
")",
":",
"# I’d prefer returning None if self.has_current_point() is False",
"# But keep (0, 0) for compat with pycairo.",
"xy",
"=",
"ffi",
".",
"new",
"(",
"'double[2]'",
")",
"cairo",
".",
"cairo_get_current_point",
"(",
"self",
".",
"_pointer",
",",
"xy",
"+",
"0",
",",
"xy",
"+",
"1",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"tuple",
"(",
"xy",
")"
] |
Return the current point of the current path,
which is conceptually the final point reached by the path so far.
The current point is returned in the user-space coordinate system.
If there is no defined current point
or if the context is in an error status,
``(0, 0)`` is returned.
It is possible to check this in advance with :meth:`has_current_point`.
Most path construction methods alter the current point.
See the following for details on how they affect the current point:
:meth:`new_path`,
:meth:`new_sub_path`,
:meth:`append_path`,
:meth:`close_path`,
:meth:`move_to`,
:meth:`line_to`,
:meth:`curve_to`,
:meth:`rel_move_to`,
:meth:`rel_line_to`,
:meth:`rel_curve_to`,
:meth:`arc`,
:meth:`arc_negative`,
:meth:`rectangle`,
:meth:`text_path`,
:meth:`glyph_path`,
:meth:`stroke_to_path`.
Some methods use and alter the current point
but do not otherwise change current path:
:meth:`show_text`,
:meth:`show_glyphs`,
:meth:`show_text_glyphs`.
Some methods unset the current path and as a result, current point:
:meth:`fill`,
:meth:`stroke`.
:returns:
A ``(x, y)`` tuple of floats, the coordinates of the current point.
|
[
"Return",
"the",
"current",
"point",
"of",
"the",
"current",
"path",
"which",
"is",
"conceptually",
"the",
"final",
"point",
"reached",
"by",
"the",
"path",
"so",
"far",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L850-L898
|
17,590
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.copy_path
|
def copy_path(self):
"""Return a copy of the current path.
:returns:
A list of ``(path_operation, coordinates)`` tuples
of a :ref:`PATH_OPERATION` string
and a tuple of floats coordinates
whose content depends on the operation type:
* :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ``(x, y)``
* :obj:`LINE_TO <PATH_LINE_TO>`: 1 point ``(x, y)``
* :obj:`CURVE_TO <PATH_CURVE_TO>`: 3 points
``(x1, y1, x2, y2, x3, y3)``
* :obj:`CLOSE_PATH <PATH_CLOSE_PATH>` 0 points ``()`` (empty tuple)
"""
path = cairo.cairo_copy_path(self._pointer)
result = list(_iter_path(path))
cairo.cairo_path_destroy(path)
return result
|
python
|
def copy_path(self):
"""Return a copy of the current path.
:returns:
A list of ``(path_operation, coordinates)`` tuples
of a :ref:`PATH_OPERATION` string
and a tuple of floats coordinates
whose content depends on the operation type:
* :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ``(x, y)``
* :obj:`LINE_TO <PATH_LINE_TO>`: 1 point ``(x, y)``
* :obj:`CURVE_TO <PATH_CURVE_TO>`: 3 points
``(x1, y1, x2, y2, x3, y3)``
* :obj:`CLOSE_PATH <PATH_CLOSE_PATH>` 0 points ``()`` (empty tuple)
"""
path = cairo.cairo_copy_path(self._pointer)
result = list(_iter_path(path))
cairo.cairo_path_destroy(path)
return result
|
[
"def",
"copy_path",
"(",
"self",
")",
":",
"path",
"=",
"cairo",
".",
"cairo_copy_path",
"(",
"self",
".",
"_pointer",
")",
"result",
"=",
"list",
"(",
"_iter_path",
"(",
"path",
")",
")",
"cairo",
".",
"cairo_path_destroy",
"(",
"path",
")",
"return",
"result"
] |
Return a copy of the current path.
:returns:
A list of ``(path_operation, coordinates)`` tuples
of a :ref:`PATH_OPERATION` string
and a tuple of floats coordinates
whose content depends on the operation type:
* :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ``(x, y)``
* :obj:`LINE_TO <PATH_LINE_TO>`: 1 point ``(x, y)``
* :obj:`CURVE_TO <PATH_CURVE_TO>`: 3 points
``(x1, y1, x2, y2, x3, y3)``
* :obj:`CLOSE_PATH <PATH_CLOSE_PATH>` 0 points ``()`` (empty tuple)
|
[
"Return",
"a",
"copy",
"of",
"the",
"current",
"path",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1245-L1264
|
17,591
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.copy_path_flat
|
def copy_path_flat(self):
"""Return a flattened copy of the current path
This method is like :meth:`copy_path`
except that any curves in the path will be approximated
with piecewise-linear approximations,
(accurate to within the current tolerance value,
see :meth:`set_tolerance`).
That is,
the result is guaranteed to not have any elements
of type :obj:`CURVE_TO <PATH_CURVE_TO>`
which will instead be replaced by
a series of :obj:`LINE_TO <PATH_LINE_TO>` elements.
:returns:
A list of ``(path_operation, coordinates)`` tuples.
See :meth:`copy_path` for the data structure.
"""
path = cairo.cairo_copy_path_flat(self._pointer)
result = list(_iter_path(path))
cairo.cairo_path_destroy(path)
return result
|
python
|
def copy_path_flat(self):
"""Return a flattened copy of the current path
This method is like :meth:`copy_path`
except that any curves in the path will be approximated
with piecewise-linear approximations,
(accurate to within the current tolerance value,
see :meth:`set_tolerance`).
That is,
the result is guaranteed to not have any elements
of type :obj:`CURVE_TO <PATH_CURVE_TO>`
which will instead be replaced by
a series of :obj:`LINE_TO <PATH_LINE_TO>` elements.
:returns:
A list of ``(path_operation, coordinates)`` tuples.
See :meth:`copy_path` for the data structure.
"""
path = cairo.cairo_copy_path_flat(self._pointer)
result = list(_iter_path(path))
cairo.cairo_path_destroy(path)
return result
|
[
"def",
"copy_path_flat",
"(",
"self",
")",
":",
"path",
"=",
"cairo",
".",
"cairo_copy_path_flat",
"(",
"self",
".",
"_pointer",
")",
"result",
"=",
"list",
"(",
"_iter_path",
"(",
"path",
")",
")",
"cairo",
".",
"cairo_path_destroy",
"(",
"path",
")",
"return",
"result"
] |
Return a flattened copy of the current path
This method is like :meth:`copy_path`
except that any curves in the path will be approximated
with piecewise-linear approximations,
(accurate to within the current tolerance value,
see :meth:`set_tolerance`).
That is,
the result is guaranteed to not have any elements
of type :obj:`CURVE_TO <PATH_CURVE_TO>`
which will instead be replaced by
a series of :obj:`LINE_TO <PATH_LINE_TO>` elements.
:returns:
A list of ``(path_operation, coordinates)`` tuples.
See :meth:`copy_path` for the data structure.
|
[
"Return",
"a",
"flattened",
"copy",
"of",
"the",
"current",
"path"
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1266-L1288
|
17,592
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.clip_extents
|
def clip_extents(self):
"""Computes a bounding box in user coordinates
covering the area inside the current clip.
:return:
A ``(x1, y1, x2, y2)`` tuple of floats:
the left, top, right and bottom of the resulting extents,
respectively.
"""
extents = ffi.new('double[4]')
cairo.cairo_clip_extents(
self._pointer, extents + 0, extents + 1, extents + 2, extents + 3)
self._check_status()
return tuple(extents)
|
python
|
def clip_extents(self):
"""Computes a bounding box in user coordinates
covering the area inside the current clip.
:return:
A ``(x1, y1, x2, y2)`` tuple of floats:
the left, top, right and bottom of the resulting extents,
respectively.
"""
extents = ffi.new('double[4]')
cairo.cairo_clip_extents(
self._pointer, extents + 0, extents + 1, extents + 2, extents + 3)
self._check_status()
return tuple(extents)
|
[
"def",
"clip_extents",
"(",
"self",
")",
":",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'double[4]'",
")",
"cairo",
".",
"cairo_clip_extents",
"(",
"self",
".",
"_pointer",
",",
"extents",
"+",
"0",
",",
"extents",
"+",
"1",
",",
"extents",
"+",
"2",
",",
"extents",
"+",
"3",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"tuple",
"(",
"extents",
")"
] |
Computes a bounding box in user coordinates
covering the area inside the current clip.
:return:
A ``(x1, y1, x2, y2)`` tuple of floats:
the left, top, right and bottom of the resulting extents,
respectively.
|
[
"Computes",
"a",
"bounding",
"box",
"in",
"user",
"coordinates",
"covering",
"the",
"area",
"inside",
"the",
"current",
"clip",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1629-L1643
|
17,593
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.copy_clip_rectangle_list
|
def copy_clip_rectangle_list(self):
"""Return the current clip region as a list of rectangles
in user coordinates.
:return:
A list of rectangles,
as ``(x, y, width, height)`` tuples of floats.
:raises:
:exc:`CairoError`
if the clip region cannot be represented as a list
of user-space rectangles.
"""
rectangle_list = cairo.cairo_copy_clip_rectangle_list(self._pointer)
_check_status(rectangle_list.status)
rectangles = rectangle_list.rectangles
result = []
for i in range(rectangle_list.num_rectangles):
rect = rectangles[i]
result.append((rect.x, rect.y, rect.width, rect.height))
cairo.cairo_rectangle_list_destroy(rectangle_list)
return result
|
python
|
def copy_clip_rectangle_list(self):
"""Return the current clip region as a list of rectangles
in user coordinates.
:return:
A list of rectangles,
as ``(x, y, width, height)`` tuples of floats.
:raises:
:exc:`CairoError`
if the clip region cannot be represented as a list
of user-space rectangles.
"""
rectangle_list = cairo.cairo_copy_clip_rectangle_list(self._pointer)
_check_status(rectangle_list.status)
rectangles = rectangle_list.rectangles
result = []
for i in range(rectangle_list.num_rectangles):
rect = rectangles[i]
result.append((rect.x, rect.y, rect.width, rect.height))
cairo.cairo_rectangle_list_destroy(rectangle_list)
return result
|
[
"def",
"copy_clip_rectangle_list",
"(",
"self",
")",
":",
"rectangle_list",
"=",
"cairo",
".",
"cairo_copy_clip_rectangle_list",
"(",
"self",
".",
"_pointer",
")",
"_check_status",
"(",
"rectangle_list",
".",
"status",
")",
"rectangles",
"=",
"rectangle_list",
".",
"rectangles",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"rectangle_list",
".",
"num_rectangles",
")",
":",
"rect",
"=",
"rectangles",
"[",
"i",
"]",
"result",
".",
"append",
"(",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
",",
"rect",
".",
"width",
",",
"rect",
".",
"height",
")",
")",
"cairo",
".",
"cairo_rectangle_list_destroy",
"(",
"rectangle_list",
")",
"return",
"result"
] |
Return the current clip region as a list of rectangles
in user coordinates.
:return:
A list of rectangles,
as ``(x, y, width, height)`` tuples of floats.
:raises:
:exc:`CairoError`
if the clip region cannot be represented as a list
of user-space rectangles.
|
[
"Return",
"the",
"current",
"clip",
"region",
"as",
"a",
"list",
"of",
"rectangles",
"in",
"user",
"coordinates",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1645-L1666
|
17,594
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.select_font_face
|
def select_font_face(self, family='', slant=constants.FONT_SLANT_NORMAL,
weight=constants.FONT_WEIGHT_NORMAL):
"""Selects a family and style of font from a simplified description
as a family name, slant and weight.
.. note::
The :meth:`select_font_face` method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details.
Cairo provides no operation to list available family names
on the system (this is a "toy", remember),
but the standard CSS2 generic family names,
(``"serif"``, ``"sans-serif"``, ``"cursive"``, ``"fantasy"``,
``"monospace"``),
are likely to work as expected.
If family starts with the string ``"cairo:"``,
or if no native font backends are compiled in,
cairo will use an internal font family.
The internal font family recognizes many modifiers
in the family string,
most notably, it recognizes the string ``"monospace"``.
That is, the family name ``"cairo:monospace"``
will use the monospace version of the internal font family.
If text is drawn without a call to :meth:`select_font_face`,
(nor :meth:`set_font_face` nor :meth:`set_scaled_font`),
the default family is platform-specific,
but is essentially ``"sans-serif"``.
Default slant is :obj:`NORMAL <FONT_SLANT_NORMAL>`,
and default weight is :obj:`NORMAL <FONT_WEIGHT_NORMAL>`.
This method is equivalent to a call to :class:`ToyFontFace`
followed by :meth:`set_font_face`.
"""
cairo.cairo_select_font_face(
self._pointer, _encode_string(family), slant, weight)
self._check_status()
|
python
|
def select_font_face(self, family='', slant=constants.FONT_SLANT_NORMAL,
weight=constants.FONT_WEIGHT_NORMAL):
"""Selects a family and style of font from a simplified description
as a family name, slant and weight.
.. note::
The :meth:`select_font_face` method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details.
Cairo provides no operation to list available family names
on the system (this is a "toy", remember),
but the standard CSS2 generic family names,
(``"serif"``, ``"sans-serif"``, ``"cursive"``, ``"fantasy"``,
``"monospace"``),
are likely to work as expected.
If family starts with the string ``"cairo:"``,
or if no native font backends are compiled in,
cairo will use an internal font family.
The internal font family recognizes many modifiers
in the family string,
most notably, it recognizes the string ``"monospace"``.
That is, the family name ``"cairo:monospace"``
will use the monospace version of the internal font family.
If text is drawn without a call to :meth:`select_font_face`,
(nor :meth:`set_font_face` nor :meth:`set_scaled_font`),
the default family is platform-specific,
but is essentially ``"sans-serif"``.
Default slant is :obj:`NORMAL <FONT_SLANT_NORMAL>`,
and default weight is :obj:`NORMAL <FONT_WEIGHT_NORMAL>`.
This method is equivalent to a call to :class:`ToyFontFace`
followed by :meth:`set_font_face`.
"""
cairo.cairo_select_font_face(
self._pointer, _encode_string(family), slant, weight)
self._check_status()
|
[
"def",
"select_font_face",
"(",
"self",
",",
"family",
"=",
"''",
",",
"slant",
"=",
"constants",
".",
"FONT_SLANT_NORMAL",
",",
"weight",
"=",
"constants",
".",
"FONT_WEIGHT_NORMAL",
")",
":",
"cairo",
".",
"cairo_select_font_face",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"family",
")",
",",
"slant",
",",
"weight",
")",
"self",
".",
"_check_status",
"(",
")"
] |
Selects a family and style of font from a simplified description
as a family name, slant and weight.
.. note::
The :meth:`select_font_face` method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details.
Cairo provides no operation to list available family names
on the system (this is a "toy", remember),
but the standard CSS2 generic family names,
(``"serif"``, ``"sans-serif"``, ``"cursive"``, ``"fantasy"``,
``"monospace"``),
are likely to work as expected.
If family starts with the string ``"cairo:"``,
or if no native font backends are compiled in,
cairo will use an internal font family.
The internal font family recognizes many modifiers
in the family string,
most notably, it recognizes the string ``"monospace"``.
That is, the family name ``"cairo:monospace"``
will use the monospace version of the internal font family.
If text is drawn without a call to :meth:`select_font_face`,
(nor :meth:`set_font_face` nor :meth:`set_scaled_font`),
the default family is platform-specific,
but is essentially ``"sans-serif"``.
Default slant is :obj:`NORMAL <FONT_SLANT_NORMAL>`,
and default weight is :obj:`NORMAL <FONT_WEIGHT_NORMAL>`.
This method is equivalent to a call to :class:`ToyFontFace`
followed by :meth:`set_font_face`.
|
[
"Selects",
"a",
"family",
"and",
"style",
"of",
"font",
"from",
"a",
"simplified",
"description",
"as",
"a",
"family",
"name",
"slant",
"and",
"weight",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1709-L1752
|
17,595
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.get_font_face
|
def get_font_face(self):
"""Return the current font face.
:param font_face:
A new :class:`FontFace` object
wrapping an existing cairo object.
"""
return FontFace._from_pointer(
cairo.cairo_get_font_face(self._pointer), incref=True)
|
python
|
def get_font_face(self):
"""Return the current font face.
:param font_face:
A new :class:`FontFace` object
wrapping an existing cairo object.
"""
return FontFace._from_pointer(
cairo.cairo_get_font_face(self._pointer), incref=True)
|
[
"def",
"get_font_face",
"(",
"self",
")",
":",
"return",
"FontFace",
".",
"_from_pointer",
"(",
"cairo",
".",
"cairo_get_font_face",
"(",
"self",
".",
"_pointer",
")",
",",
"incref",
"=",
"True",
")"
] |
Return the current font face.
:param font_face:
A new :class:`FontFace` object
wrapping an existing cairo object.
|
[
"Return",
"the",
"current",
"font",
"face",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1766-L1775
|
17,596
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.get_scaled_font
|
def get_scaled_font(self):
"""Return the current scaled font.
:return:
A new :class:`ScaledFont` object,
wrapping an existing cairo object.
"""
return ScaledFont._from_pointer(
cairo.cairo_get_scaled_font(self._pointer), incref=True)
|
python
|
def get_scaled_font(self):
"""Return the current scaled font.
:return:
A new :class:`ScaledFont` object,
wrapping an existing cairo object.
"""
return ScaledFont._from_pointer(
cairo.cairo_get_scaled_font(self._pointer), incref=True)
|
[
"def",
"get_scaled_font",
"(",
"self",
")",
":",
"return",
"ScaledFont",
".",
"_from_pointer",
"(",
"cairo",
".",
"cairo_get_scaled_font",
"(",
"self",
".",
"_pointer",
")",
",",
"incref",
"=",
"True",
")"
] |
Return the current scaled font.
:return:
A new :class:`ScaledFont` object,
wrapping an existing cairo object.
|
[
"Return",
"the",
"current",
"scaled",
"font",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1865-L1874
|
17,597
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.font_extents
|
def font_extents(self):
"""Return the extents of the currently selected font.
Values are given in the current user-space coordinate system.
Because font metrics are in user-space coordinates, they are mostly,
but not entirely, independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:returns:
A ``(ascent, descent, height, max_x_advance, max_y_advance)``
tuple of floats.
:obj:`ascent`
The distance that the font extends above the baseline.
Note that this is not always exactly equal to
the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements above it.
:obj:`descent`
The distance that the font extends below the baseline.
This value is positive for typical fonts
that include portions below the baseline.
Note that this is not always exactly equal
to the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements below it.
:obj:`height`
The recommended vertical distance between baselines
when setting consecutive lines of text with the font.
This is greater than ``ascent + descent``
by a quantity known as the line spacing or external leading.
When space is at a premium, most fonts can be set
with only a distance of ``ascent + descent`` between lines.
:obj:`max_x_advance`
The maximum distance in the X direction
that the origin is advanced for any glyph in the font.
:obj:`max_y_advance`
The maximum distance in the Y direction
that the origin is advanced for any glyph in the font.
This will be zero for normal fonts used for horizontal writing.
(The scripts of East Asia are sometimes written vertically.)
"""
extents = ffi.new('cairo_font_extents_t *')
cairo.cairo_font_extents(self._pointer, extents)
self._check_status()
# returning extents as is would be a nice API,
# but return a tuple for compat with pycairo.
return (
extents.ascent, extents.descent, extents.height,
extents.max_x_advance, extents.max_y_advance)
|
python
|
def font_extents(self):
"""Return the extents of the currently selected font.
Values are given in the current user-space coordinate system.
Because font metrics are in user-space coordinates, they are mostly,
but not entirely, independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:returns:
A ``(ascent, descent, height, max_x_advance, max_y_advance)``
tuple of floats.
:obj:`ascent`
The distance that the font extends above the baseline.
Note that this is not always exactly equal to
the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements above it.
:obj:`descent`
The distance that the font extends below the baseline.
This value is positive for typical fonts
that include portions below the baseline.
Note that this is not always exactly equal
to the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements below it.
:obj:`height`
The recommended vertical distance between baselines
when setting consecutive lines of text with the font.
This is greater than ``ascent + descent``
by a quantity known as the line spacing or external leading.
When space is at a premium, most fonts can be set
with only a distance of ``ascent + descent`` between lines.
:obj:`max_x_advance`
The maximum distance in the X direction
that the origin is advanced for any glyph in the font.
:obj:`max_y_advance`
The maximum distance in the Y direction
that the origin is advanced for any glyph in the font.
This will be zero for normal fonts used for horizontal writing.
(The scripts of East Asia are sometimes written vertically.)
"""
extents = ffi.new('cairo_font_extents_t *')
cairo.cairo_font_extents(self._pointer, extents)
self._check_status()
# returning extents as is would be a nice API,
# but return a tuple for compat with pycairo.
return (
extents.ascent, extents.descent, extents.height,
extents.max_x_advance, extents.max_y_advance)
|
[
"def",
"font_extents",
"(",
"self",
")",
":",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'cairo_font_extents_t *'",
")",
"cairo",
".",
"cairo_font_extents",
"(",
"self",
".",
"_pointer",
",",
"extents",
")",
"self",
".",
"_check_status",
"(",
")",
"# returning extents as is would be a nice API,",
"# but return a tuple for compat with pycairo.",
"return",
"(",
"extents",
".",
"ascent",
",",
"extents",
".",
"descent",
",",
"extents",
".",
"height",
",",
"extents",
".",
"max_x_advance",
",",
"extents",
".",
"max_y_advance",
")"
] |
Return the extents of the currently selected font.
Values are given in the current user-space coordinate system.
Because font metrics are in user-space coordinates, they are mostly,
but not entirely, independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:returns:
A ``(ascent, descent, height, max_x_advance, max_y_advance)``
tuple of floats.
:obj:`ascent`
The distance that the font extends above the baseline.
Note that this is not always exactly equal to
the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements above it.
:obj:`descent`
The distance that the font extends below the baseline.
This value is positive for typical fonts
that include portions below the baseline.
Note that this is not always exactly equal
to the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements below it.
:obj:`height`
The recommended vertical distance between baselines
when setting consecutive lines of text with the font.
This is greater than ``ascent + descent``
by a quantity known as the line spacing or external leading.
When space is at a premium, most fonts can be set
with only a distance of ``ascent + descent`` between lines.
:obj:`max_x_advance`
The maximum distance in the X direction
that the origin is advanced for any glyph in the font.
:obj:`max_y_advance`
The maximum distance in the Y direction
that the origin is advanced for any glyph in the font.
This will be zero for normal fonts used for horizontal writing.
(The scripts of East Asia are sometimes written vertically.)
|
[
"Return",
"the",
"extents",
"of",
"the",
"currently",
"selected",
"font",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1876-L1933
|
17,598
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.text_extents
|
def text_extents(self, text):
"""Returns the extents for a string of text.
The extents describe a user-space rectangle
that encloses the "inked" portion of the text,
(as it would be drawn by :meth:`show_text`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_text`.
Note that whitespace characters do not directly contribute
to the size of the rectangle (:obj:`width` and :obj:`height`).
They do contribute indirectly by changing the position
of non-whitespace characters.
In particular, trailing whitespace characters are likely
to not affect the size of the rectangle,
though they will affect the x_advance and y_advance values.
Because text extents are in user-space coordinates,
they are mostly, but not entirely,
independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:param text: The text to measure, as an Unicode or UTF-8 string.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
:obj:`x_bearing`
The horizontal distance
from the origin to the leftmost part of the glyphs as drawn.
Positive if the glyphs lie entirely to the right of the origin.
:obj:`y_bearing`
The vertical distance
from the origin to the topmost part of the glyphs as drawn.
Positive only if the glyphs lie completely below the origin;
will usually be negative.
:obj:`width`
Width of the glyphs as drawn.
:obj:`height`
Height of the glyphs as drawn.
:obj:`x_advance`
Distance to advance in the X direction
after drawing these glyphs.
:obj:`y_advance`
Distance to advance in the Y direction
after drawing these glyphs.
Will typically be zero except for vertical text layout
as found in East-Asian languages.
"""
extents = ffi.new('cairo_text_extents_t *')
cairo.cairo_text_extents(self._pointer, _encode_string(text), extents)
self._check_status()
# returning extents as is would be a nice API,
# but return a tuple for compat with pycairo.
return (
extents.x_bearing, extents.y_bearing,
extents.width, extents.height,
extents.x_advance, extents.y_advance)
|
python
|
def text_extents(self, text):
"""Returns the extents for a string of text.
The extents describe a user-space rectangle
that encloses the "inked" portion of the text,
(as it would be drawn by :meth:`show_text`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_text`.
Note that whitespace characters do not directly contribute
to the size of the rectangle (:obj:`width` and :obj:`height`).
They do contribute indirectly by changing the position
of non-whitespace characters.
In particular, trailing whitespace characters are likely
to not affect the size of the rectangle,
though they will affect the x_advance and y_advance values.
Because text extents are in user-space coordinates,
they are mostly, but not entirely,
independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:param text: The text to measure, as an Unicode or UTF-8 string.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
:obj:`x_bearing`
The horizontal distance
from the origin to the leftmost part of the glyphs as drawn.
Positive if the glyphs lie entirely to the right of the origin.
:obj:`y_bearing`
The vertical distance
from the origin to the topmost part of the glyphs as drawn.
Positive only if the glyphs lie completely below the origin;
will usually be negative.
:obj:`width`
Width of the glyphs as drawn.
:obj:`height`
Height of the glyphs as drawn.
:obj:`x_advance`
Distance to advance in the X direction
after drawing these glyphs.
:obj:`y_advance`
Distance to advance in the Y direction
after drawing these glyphs.
Will typically be zero except for vertical text layout
as found in East-Asian languages.
"""
extents = ffi.new('cairo_text_extents_t *')
cairo.cairo_text_extents(self._pointer, _encode_string(text), extents)
self._check_status()
# returning extents as is would be a nice API,
# but return a tuple for compat with pycairo.
return (
extents.x_bearing, extents.y_bearing,
extents.width, extents.height,
extents.x_advance, extents.y_advance)
|
[
"def",
"text_extents",
"(",
"self",
",",
"text",
")",
":",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'cairo_text_extents_t *'",
")",
"cairo",
".",
"cairo_text_extents",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"text",
")",
",",
"extents",
")",
"self",
".",
"_check_status",
"(",
")",
"# returning extents as is would be a nice API,",
"# but return a tuple for compat with pycairo.",
"return",
"(",
"extents",
".",
"x_bearing",
",",
"extents",
".",
"y_bearing",
",",
"extents",
".",
"width",
",",
"extents",
".",
"height",
",",
"extents",
".",
"x_advance",
",",
"extents",
".",
"y_advance",
")"
] |
Returns the extents for a string of text.
The extents describe a user-space rectangle
that encloses the "inked" portion of the text,
(as it would be drawn by :meth:`show_text`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_text`.
Note that whitespace characters do not directly contribute
to the size of the rectangle (:obj:`width` and :obj:`height`).
They do contribute indirectly by changing the position
of non-whitespace characters.
In particular, trailing whitespace characters are likely
to not affect the size of the rectangle,
though they will affect the x_advance and y_advance values.
Because text extents are in user-space coordinates,
they are mostly, but not entirely,
independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:param text: The text to measure, as an Unicode or UTF-8 string.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
:obj:`x_bearing`
The horizontal distance
from the origin to the leftmost part of the glyphs as drawn.
Positive if the glyphs lie entirely to the right of the origin.
:obj:`y_bearing`
The vertical distance
from the origin to the topmost part of the glyphs as drawn.
Positive only if the glyphs lie completely below the origin;
will usually be negative.
:obj:`width`
Width of the glyphs as drawn.
:obj:`height`
Height of the glyphs as drawn.
:obj:`x_advance`
Distance to advance in the X direction
after drawing these glyphs.
:obj:`y_advance`
Distance to advance in the Y direction
after drawing these glyphs.
Will typically be zero except for vertical text layout
as found in East-Asian languages.
|
[
"Returns",
"the",
"extents",
"for",
"a",
"string",
"of",
"text",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1939-L2009
|
17,599
|
Kozea/cairocffi
|
cairocffi/context.py
|
Context.glyph_extents
|
def glyph_extents(self, glyphs):
"""Returns the extents for a list of glyphs.
The extents describe a user-space rectangle
that encloses the "inked" portion of the glyphs,
(as it would be drawn by :meth:`show_glyphs`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_glyphs`.
:param glyphs:
A list of glyphs.
See :meth:`show_text_glyphs` for the data structure.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
See :meth:`text_extents` for details.
"""
glyphs = ffi.new('cairo_glyph_t[]', glyphs)
extents = ffi.new('cairo_text_extents_t *')
cairo.cairo_glyph_extents(
self._pointer, glyphs, len(glyphs), extents)
self._check_status()
return (
extents.x_bearing, extents.y_bearing,
extents.width, extents.height,
extents.x_advance, extents.y_advance)
|
python
|
def glyph_extents(self, glyphs):
"""Returns the extents for a list of glyphs.
The extents describe a user-space rectangle
that encloses the "inked" portion of the glyphs,
(as it would be drawn by :meth:`show_glyphs`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_glyphs`.
:param glyphs:
A list of glyphs.
See :meth:`show_text_glyphs` for the data structure.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
See :meth:`text_extents` for details.
"""
glyphs = ffi.new('cairo_glyph_t[]', glyphs)
extents = ffi.new('cairo_text_extents_t *')
cairo.cairo_glyph_extents(
self._pointer, glyphs, len(glyphs), extents)
self._check_status()
return (
extents.x_bearing, extents.y_bearing,
extents.width, extents.height,
extents.x_advance, extents.y_advance)
|
[
"def",
"glyph_extents",
"(",
"self",
",",
"glyphs",
")",
":",
"glyphs",
"=",
"ffi",
".",
"new",
"(",
"'cairo_glyph_t[]'",
",",
"glyphs",
")",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'cairo_text_extents_t *'",
")",
"cairo",
".",
"cairo_glyph_extents",
"(",
"self",
".",
"_pointer",
",",
"glyphs",
",",
"len",
"(",
"glyphs",
")",
",",
"extents",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"(",
"extents",
".",
"x_bearing",
",",
"extents",
".",
"y_bearing",
",",
"extents",
".",
"width",
",",
"extents",
".",
"height",
",",
"extents",
".",
"x_advance",
",",
"extents",
".",
"y_advance",
")"
] |
Returns the extents for a list of glyphs.
The extents describe a user-space rectangle
that encloses the "inked" portion of the glyphs,
(as it would be drawn by :meth:`show_glyphs`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_glyphs`.
:param glyphs:
A list of glyphs.
See :meth:`show_text_glyphs` for the data structure.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
See :meth:`text_extents` for details.
|
[
"Returns",
"the",
"extents",
"for",
"a",
"list",
"of",
"glyphs",
"."
] |
450853add7e32eea20985b6aa5f54d9cb3cd04fe
|
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L2011-L2038
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.