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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
239,300 | ethereum/web3.py | web3/datastructures.py | NamedElementOnion.inject | def inject(self, element, name=None, layer=None):
"""
Inject a named element to an arbitrary layer in the onion.
The current implementation only supports insertion at the innermost layer,
or at the outermost layer. Note that inserting to the outermost is equivalent
to calling :meth:`add` .
"""
if not is_integer(layer):
raise TypeError("The layer for insertion must be an int.")
elif layer != 0 and layer != len(self._queue):
raise NotImplementedError(
"You can only insert to the beginning or end of a %s, currently. "
"You tried to insert to %d, but only 0 and %d are permitted. " % (
type(self),
layer,
len(self._queue),
)
)
self.add(element, name=name)
if layer == 0:
if name is None:
name = element
self._queue.move_to_end(name, last=False)
elif layer == len(self._queue):
return
else:
raise AssertionError("Impossible to reach: earlier validation raises an error") | python | def inject(self, element, name=None, layer=None):
if not is_integer(layer):
raise TypeError("The layer for insertion must be an int.")
elif layer != 0 and layer != len(self._queue):
raise NotImplementedError(
"You can only insert to the beginning or end of a %s, currently. "
"You tried to insert to %d, but only 0 and %d are permitted. " % (
type(self),
layer,
len(self._queue),
)
)
self.add(element, name=name)
if layer == 0:
if name is None:
name = element
self._queue.move_to_end(name, last=False)
elif layer == len(self._queue):
return
else:
raise AssertionError("Impossible to reach: earlier validation raises an error") | [
"def",
"inject",
"(",
"self",
",",
"element",
",",
"name",
"=",
"None",
",",
"layer",
"=",
"None",
")",
":",
"if",
"not",
"is_integer",
"(",
"layer",
")",
":",
"raise",
"TypeError",
"(",
"\"The layer for insertion must be an int.\"",
")",
"elif",
"layer",
... | Inject a named element to an arbitrary layer in the onion.
The current implementation only supports insertion at the innermost layer,
or at the outermost layer. Note that inserting to the outermost is equivalent
to calling :meth:`add` . | [
"Inject",
"a",
"named",
"element",
"to",
"an",
"arbitrary",
"layer",
"in",
"the",
"onion",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/datastructures.py#L127-L156 |
239,301 | ethereum/web3.py | web3/middleware/signing.py | construct_sign_and_send_raw_middleware | def construct_sign_and_send_raw_middleware(private_key_or_account):
"""Capture transactions sign and send as raw transactions
Keyword arguments:
private_key_or_account -- A single private key or a tuple,
list or set of private keys. Keys can be any of the following formats:
- An eth_account.LocalAccount object
- An eth_keys.PrivateKey object
- A raw private key as a hex string or byte string
"""
accounts = gen_normalized_accounts(private_key_or_account)
def sign_and_send_raw_middleware(make_request, w3):
format_and_fill_tx = compose(
format_transaction,
fill_transaction_defaults(w3),
fill_nonce(w3))
def middleware(method, params):
if method != "eth_sendTransaction":
return make_request(method, params)
else:
transaction = format_and_fill_tx(params[0])
if 'from' not in transaction:
return make_request(method, params)
elif transaction.get('from') not in accounts:
return make_request(method, params)
account = accounts[transaction['from']]
raw_tx = account.signTransaction(transaction).rawTransaction
return make_request(
"eth_sendRawTransaction",
[raw_tx])
return middleware
return sign_and_send_raw_middleware | python | def construct_sign_and_send_raw_middleware(private_key_or_account):
accounts = gen_normalized_accounts(private_key_or_account)
def sign_and_send_raw_middleware(make_request, w3):
format_and_fill_tx = compose(
format_transaction,
fill_transaction_defaults(w3),
fill_nonce(w3))
def middleware(method, params):
if method != "eth_sendTransaction":
return make_request(method, params)
else:
transaction = format_and_fill_tx(params[0])
if 'from' not in transaction:
return make_request(method, params)
elif transaction.get('from') not in accounts:
return make_request(method, params)
account = accounts[transaction['from']]
raw_tx = account.signTransaction(transaction).rawTransaction
return make_request(
"eth_sendRawTransaction",
[raw_tx])
return middleware
return sign_and_send_raw_middleware | [
"def",
"construct_sign_and_send_raw_middleware",
"(",
"private_key_or_account",
")",
":",
"accounts",
"=",
"gen_normalized_accounts",
"(",
"private_key_or_account",
")",
"def",
"sign_and_send_raw_middleware",
"(",
"make_request",
",",
"w3",
")",
":",
"format_and_fill_tx",
"... | Capture transactions sign and send as raw transactions
Keyword arguments:
private_key_or_account -- A single private key or a tuple,
list or set of private keys. Keys can be any of the following formats:
- An eth_account.LocalAccount object
- An eth_keys.PrivateKey object
- A raw private key as a hex string or byte string | [
"Capture",
"transactions",
"sign",
"and",
"send",
"as",
"raw",
"transactions"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/signing.py#L95-L136 |
239,302 | ethereum/web3.py | web3/_utils/validation.py | validate_abi | def validate_abi(abi):
"""
Helper function for validating an ABI
"""
if not is_list_like(abi):
raise ValueError("'abi' is not a list")
if not all(is_dict(e) for e in abi):
raise ValueError("'abi' is not a list of dictionaries")
functions = filter_by_type('function', abi)
selectors = groupby(
compose(encode_hex, function_abi_to_4byte_selector),
functions
)
duplicates = valfilter(lambda funcs: len(funcs) > 1, selectors)
if duplicates:
raise ValueError(
'Abi contains functions with colliding selectors. '
'Functions {0}'.format(_prepare_selector_collision_msg(duplicates))
) | python | def validate_abi(abi):
if not is_list_like(abi):
raise ValueError("'abi' is not a list")
if not all(is_dict(e) for e in abi):
raise ValueError("'abi' is not a list of dictionaries")
functions = filter_by_type('function', abi)
selectors = groupby(
compose(encode_hex, function_abi_to_4byte_selector),
functions
)
duplicates = valfilter(lambda funcs: len(funcs) > 1, selectors)
if duplicates:
raise ValueError(
'Abi contains functions with colliding selectors. '
'Functions {0}'.format(_prepare_selector_collision_msg(duplicates))
) | [
"def",
"validate_abi",
"(",
"abi",
")",
":",
"if",
"not",
"is_list_like",
"(",
"abi",
")",
":",
"raise",
"ValueError",
"(",
"\"'abi' is not a list\"",
")",
"if",
"not",
"all",
"(",
"is_dict",
"(",
"e",
")",
"for",
"e",
"in",
"abi",
")",
":",
"raise",
... | Helper function for validating an ABI | [
"Helper",
"function",
"for",
"validating",
"an",
"ABI"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/validation.py#L55-L75 |
239,303 | ethereum/web3.py | web3/_utils/validation.py | validate_address | def validate_address(value):
"""
Helper function for validating an address
"""
if is_bytes(value):
if not is_binary_address(value):
raise InvalidAddress("Address must be 20 bytes when input type is bytes", value)
return
if not isinstance(value, str):
raise TypeError('Address {} must be provided as a string'.format(value))
if not is_hex_address(value):
raise InvalidAddress("Address must be 20 bytes, as a hex string with a 0x prefix", value)
if not is_checksum_address(value):
if value == value.lower():
raise InvalidAddress(
"Web3.py only accepts checksum addresses. "
"The software that gave you this non-checksum address should be considered unsafe, "
"please file it as a bug on their platform. "
"Try using an ENS name instead. Or, if you must accept lower safety, "
"use Web3.toChecksumAddress(lower_case_address).",
value,
)
else:
raise InvalidAddress(
"Address has an invalid EIP-55 checksum. "
"After looking up the address from the original source, try again.",
value,
) | python | def validate_address(value):
if is_bytes(value):
if not is_binary_address(value):
raise InvalidAddress("Address must be 20 bytes when input type is bytes", value)
return
if not isinstance(value, str):
raise TypeError('Address {} must be provided as a string'.format(value))
if not is_hex_address(value):
raise InvalidAddress("Address must be 20 bytes, as a hex string with a 0x prefix", value)
if not is_checksum_address(value):
if value == value.lower():
raise InvalidAddress(
"Web3.py only accepts checksum addresses. "
"The software that gave you this non-checksum address should be considered unsafe, "
"please file it as a bug on their platform. "
"Try using an ENS name instead. Or, if you must accept lower safety, "
"use Web3.toChecksumAddress(lower_case_address).",
value,
)
else:
raise InvalidAddress(
"Address has an invalid EIP-55 checksum. "
"After looking up the address from the original source, try again.",
value,
) | [
"def",
"validate_address",
"(",
"value",
")",
":",
"if",
"is_bytes",
"(",
"value",
")",
":",
"if",
"not",
"is_binary_address",
"(",
"value",
")",
":",
"raise",
"InvalidAddress",
"(",
"\"Address must be 20 bytes when input type is bytes\"",
",",
"value",
")",
"retu... | Helper function for validating an address | [
"Helper",
"function",
"for",
"validating",
"an",
"address"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/validation.py#L142-L170 |
239,304 | ethereum/web3.py | web3/middleware/cache.py | construct_simple_cache_middleware | def construct_simple_cache_middleware(
cache_class,
rpc_whitelist=SIMPLE_CACHE_RPC_WHITELIST,
should_cache_fn=_should_cache):
"""
Constructs a middleware which caches responses based on the request
``method`` and ``params``
:param cache: Any dictionary-like object
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached.
"""
def simple_cache_middleware(make_request, web3):
cache = cache_class()
lock = threading.Lock()
def middleware(method, params):
lock_acquired = lock.acquire(blocking=False)
try:
if lock_acquired and method in rpc_whitelist:
cache_key = generate_cache_key((method, params))
if cache_key not in cache:
response = make_request(method, params)
if should_cache_fn(method, params, response):
cache[cache_key] = response
return response
return cache[cache_key]
else:
return make_request(method, params)
finally:
if lock_acquired:
lock.release()
return middleware
return simple_cache_middleware | python | def construct_simple_cache_middleware(
cache_class,
rpc_whitelist=SIMPLE_CACHE_RPC_WHITELIST,
should_cache_fn=_should_cache):
def simple_cache_middleware(make_request, web3):
cache = cache_class()
lock = threading.Lock()
def middleware(method, params):
lock_acquired = lock.acquire(blocking=False)
try:
if lock_acquired and method in rpc_whitelist:
cache_key = generate_cache_key((method, params))
if cache_key not in cache:
response = make_request(method, params)
if should_cache_fn(method, params, response):
cache[cache_key] = response
return response
return cache[cache_key]
else:
return make_request(method, params)
finally:
if lock_acquired:
lock.release()
return middleware
return simple_cache_middleware | [
"def",
"construct_simple_cache_middleware",
"(",
"cache_class",
",",
"rpc_whitelist",
"=",
"SIMPLE_CACHE_RPC_WHITELIST",
",",
"should_cache_fn",
"=",
"_should_cache",
")",
":",
"def",
"simple_cache_middleware",
"(",
"make_request",
",",
"web3",
")",
":",
"cache",
"=",
... | Constructs a middleware which caches responses based on the request
``method`` and ``params``
:param cache: Any dictionary-like object
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached. | [
"Constructs",
"a",
"middleware",
"which",
"caches",
"responses",
"based",
"on",
"the",
"request",
"method",
"and",
"params"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/cache.py#L74-L110 |
239,305 | ethereum/web3.py | web3/middleware/cache.py | construct_time_based_cache_middleware | def construct_time_based_cache_middleware(
cache_class,
cache_expire_seconds=15,
rpc_whitelist=TIME_BASED_CACHE_RPC_WHITELIST,
should_cache_fn=_should_cache):
"""
Constructs a middleware which caches responses based on the request
``method`` and ``params`` for a maximum amount of time as specified
:param cache: Any dictionary-like object
:param cache_expire_seconds: The number of seconds an item may be cached
before it should expire.
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached.
"""
def time_based_cache_middleware(make_request, web3):
cache = cache_class()
lock = threading.Lock()
def middleware(method, params):
lock_acquired = lock.acquire(blocking=False)
try:
if lock_acquired and method in rpc_whitelist:
cache_key = generate_cache_key((method, params))
if cache_key in cache:
# check that the cached response is not expired.
cached_at, cached_response = cache[cache_key]
cached_for = time.time() - cached_at
if cached_for <= cache_expire_seconds:
return cached_response
else:
del cache[cache_key]
# cache either missed or expired so make the request.
response = make_request(method, params)
if should_cache_fn(method, params, response):
cache[cache_key] = (time.time(), response)
return response
else:
return make_request(method, params)
finally:
if lock_acquired:
lock.release()
return middleware
return time_based_cache_middleware | python | def construct_time_based_cache_middleware(
cache_class,
cache_expire_seconds=15,
rpc_whitelist=TIME_BASED_CACHE_RPC_WHITELIST,
should_cache_fn=_should_cache):
def time_based_cache_middleware(make_request, web3):
cache = cache_class()
lock = threading.Lock()
def middleware(method, params):
lock_acquired = lock.acquire(blocking=False)
try:
if lock_acquired and method in rpc_whitelist:
cache_key = generate_cache_key((method, params))
if cache_key in cache:
# check that the cached response is not expired.
cached_at, cached_response = cache[cache_key]
cached_for = time.time() - cached_at
if cached_for <= cache_expire_seconds:
return cached_response
else:
del cache[cache_key]
# cache either missed or expired so make the request.
response = make_request(method, params)
if should_cache_fn(method, params, response):
cache[cache_key] = (time.time(), response)
return response
else:
return make_request(method, params)
finally:
if lock_acquired:
lock.release()
return middleware
return time_based_cache_middleware | [
"def",
"construct_time_based_cache_middleware",
"(",
"cache_class",
",",
"cache_expire_seconds",
"=",
"15",
",",
"rpc_whitelist",
"=",
"TIME_BASED_CACHE_RPC_WHITELIST",
",",
"should_cache_fn",
"=",
"_should_cache",
")",
":",
"def",
"time_based_cache_middleware",
"(",
"make_... | Constructs a middleware which caches responses based on the request
``method`` and ``params`` for a maximum amount of time as specified
:param cache: Any dictionary-like object
:param cache_expire_seconds: The number of seconds an item may be cached
before it should expire.
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached. | [
"Constructs",
"a",
"middleware",
"which",
"caches",
"responses",
"based",
"on",
"the",
"request",
"method",
"and",
"params",
"for",
"a",
"maximum",
"amount",
"of",
"time",
"as",
"specified"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/cache.py#L170-L220 |
239,306 | ethereum/web3.py | web3/_utils/decorators.py | reject_recursive_repeats | def reject_recursive_repeats(to_wrap):
"""
Prevent simple cycles by returning None when called recursively with same instance
"""
to_wrap.__already_called = {}
@functools.wraps(to_wrap)
def wrapped(*args):
arg_instances = tuple(map(id, args))
thread_id = threading.get_ident()
thread_local_args = (thread_id,) + arg_instances
if thread_local_args in to_wrap.__already_called:
raise ValueError('Recursively called %s with %r' % (to_wrap, args))
to_wrap.__already_called[thread_local_args] = True
try:
wrapped_val = to_wrap(*args)
finally:
del to_wrap.__already_called[thread_local_args]
return wrapped_val
return wrapped | python | def reject_recursive_repeats(to_wrap):
to_wrap.__already_called = {}
@functools.wraps(to_wrap)
def wrapped(*args):
arg_instances = tuple(map(id, args))
thread_id = threading.get_ident()
thread_local_args = (thread_id,) + arg_instances
if thread_local_args in to_wrap.__already_called:
raise ValueError('Recursively called %s with %r' % (to_wrap, args))
to_wrap.__already_called[thread_local_args] = True
try:
wrapped_val = to_wrap(*args)
finally:
del to_wrap.__already_called[thread_local_args]
return wrapped_val
return wrapped | [
"def",
"reject_recursive_repeats",
"(",
"to_wrap",
")",
":",
"to_wrap",
".",
"__already_called",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"to_wrap",
")",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"arg_instances",
"=",
"tuple",
"(",
"map",
... | Prevent simple cycles by returning None when called recursively with same instance | [
"Prevent",
"simple",
"cycles",
"by",
"returning",
"None",
"when",
"called",
"recursively",
"with",
"same",
"instance"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/decorators.py#L20-L39 |
239,307 | ethereum/web3.py | web3/_utils/abi.py | get_tuple_type_str_parts | def get_tuple_type_str_parts(s: str) -> Optional[Tuple[str, Optional[str]]]:
"""
Takes a JSON ABI type string. For tuple type strings, returns the separated
prefix and array dimension parts. For all other strings, returns ``None``.
"""
match = TUPLE_TYPE_STR_RE.match(s)
if match is not None:
tuple_prefix = match.group(1)
tuple_dims = match.group(2)
return tuple_prefix, tuple_dims
return None | python | def get_tuple_type_str_parts(s: str) -> Optional[Tuple[str, Optional[str]]]:
match = TUPLE_TYPE_STR_RE.match(s)
if match is not None:
tuple_prefix = match.group(1)
tuple_dims = match.group(2)
return tuple_prefix, tuple_dims
return None | [
"def",
"get_tuple_type_str_parts",
"(",
"s",
":",
"str",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"str",
",",
"Optional",
"[",
"str",
"]",
"]",
"]",
":",
"match",
"=",
"TUPLE_TYPE_STR_RE",
".",
"match",
"(",
"s",
")",
"if",
"match",
"is",
"not",
"No... | Takes a JSON ABI type string. For tuple type strings, returns the separated
prefix and array dimension parts. For all other strings, returns ``None``. | [
"Takes",
"a",
"JSON",
"ABI",
"type",
"string",
".",
"For",
"tuple",
"type",
"strings",
"returns",
"the",
"separated",
"prefix",
"and",
"array",
"dimension",
"parts",
".",
"For",
"all",
"other",
"strings",
"returns",
"None",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/abi.py#L319-L332 |
239,308 | ethereum/web3.py | web3/_utils/abi.py | _align_abi_input | def _align_abi_input(arg_abi, arg):
"""
Aligns the values of any mapping at any level of nesting in ``arg``
according to the layout of the corresponding abi spec.
"""
tuple_parts = get_tuple_type_str_parts(arg_abi['type'])
if tuple_parts is None:
# Arg is non-tuple. Just return value.
return arg
tuple_prefix, tuple_dims = tuple_parts
if tuple_dims is None:
# Arg is non-list tuple. Each sub arg in `arg` will be aligned
# according to its corresponding abi.
sub_abis = arg_abi['components']
else:
# Arg is list tuple. A non-list version of its abi will be used to
# align each element in `arg`.
new_abi = copy.copy(arg_abi)
new_abi['type'] = tuple_prefix
sub_abis = itertools.repeat(new_abi)
if isinstance(arg, abc.Mapping):
# Arg is mapping. Align values according to abi order.
aligned_arg = tuple(arg[abi['name']] for abi in sub_abis)
else:
aligned_arg = arg
if not is_list_like(aligned_arg):
raise TypeError(
'Expected non-string sequence for "{}" component type: got {}'.format(
arg_abi['type'],
aligned_arg,
),
)
return type(aligned_arg)(
_align_abi_input(sub_abi, sub_arg)
for sub_abi, sub_arg in zip(sub_abis, aligned_arg)
) | python | def _align_abi_input(arg_abi, arg):
tuple_parts = get_tuple_type_str_parts(arg_abi['type'])
if tuple_parts is None:
# Arg is non-tuple. Just return value.
return arg
tuple_prefix, tuple_dims = tuple_parts
if tuple_dims is None:
# Arg is non-list tuple. Each sub arg in `arg` will be aligned
# according to its corresponding abi.
sub_abis = arg_abi['components']
else:
# Arg is list tuple. A non-list version of its abi will be used to
# align each element in `arg`.
new_abi = copy.copy(arg_abi)
new_abi['type'] = tuple_prefix
sub_abis = itertools.repeat(new_abi)
if isinstance(arg, abc.Mapping):
# Arg is mapping. Align values according to abi order.
aligned_arg = tuple(arg[abi['name']] for abi in sub_abis)
else:
aligned_arg = arg
if not is_list_like(aligned_arg):
raise TypeError(
'Expected non-string sequence for "{}" component type: got {}'.format(
arg_abi['type'],
aligned_arg,
),
)
return type(aligned_arg)(
_align_abi_input(sub_abi, sub_arg)
for sub_abi, sub_arg in zip(sub_abis, aligned_arg)
) | [
"def",
"_align_abi_input",
"(",
"arg_abi",
",",
"arg",
")",
":",
"tuple_parts",
"=",
"get_tuple_type_str_parts",
"(",
"arg_abi",
"[",
"'type'",
"]",
")",
"if",
"tuple_parts",
"is",
"None",
":",
"# Arg is non-tuple. Just return value.",
"return",
"arg",
"tuple_prefi... | Aligns the values of any mapping at any level of nesting in ``arg``
according to the layout of the corresponding abi spec. | [
"Aligns",
"the",
"values",
"of",
"any",
"mapping",
"at",
"any",
"level",
"of",
"nesting",
"in",
"arg",
"according",
"to",
"the",
"layout",
"of",
"the",
"corresponding",
"abi",
"spec",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/abi.py#L335-L376 |
239,309 | ethereum/web3.py | web3/_utils/abi.py | size_of_type | def size_of_type(abi_type):
"""
Returns size in bits of abi_type
"""
if 'string' in abi_type:
return None
if 'byte' in abi_type:
return None
if '[' in abi_type:
return None
if abi_type == 'bool':
return 8
if abi_type == 'address':
return 160
return int(re.sub(r"\D", "", abi_type)) | python | def size_of_type(abi_type):
if 'string' in abi_type:
return None
if 'byte' in abi_type:
return None
if '[' in abi_type:
return None
if abi_type == 'bool':
return 8
if abi_type == 'address':
return 160
return int(re.sub(r"\D", "", abi_type)) | [
"def",
"size_of_type",
"(",
"abi_type",
")",
":",
"if",
"'string'",
"in",
"abi_type",
":",
"return",
"None",
"if",
"'byte'",
"in",
"abi_type",
":",
"return",
"None",
"if",
"'['",
"in",
"abi_type",
":",
"return",
"None",
"if",
"abi_type",
"==",
"'bool'",
... | Returns size in bits of abi_type | [
"Returns",
"size",
"in",
"bits",
"of",
"abi_type"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/abi.py#L485-L499 |
239,310 | danielfrg/word2vec | word2vec/wordclusters.py | WordClusters.ix | def ix(self, word):
"""
Returns the index on self.vocab and self.clusters for 'word'
"""
temp = np.where(self.vocab == word)[0]
if temp.size == 0:
raise KeyError("Word not in vocabulary")
else:
return temp[0] | python | def ix(self, word):
temp = np.where(self.vocab == word)[0]
if temp.size == 0:
raise KeyError("Word not in vocabulary")
else:
return temp[0] | [
"def",
"ix",
"(",
"self",
",",
"word",
")",
":",
"temp",
"=",
"np",
".",
"where",
"(",
"self",
".",
"vocab",
"==",
"word",
")",
"[",
"0",
"]",
"if",
"temp",
".",
"size",
"==",
"0",
":",
"raise",
"KeyError",
"(",
"\"Word not in vocabulary\"",
")",
... | Returns the index on self.vocab and self.clusters for 'word' | [
"Returns",
"the",
"index",
"on",
"self",
".",
"vocab",
"and",
"self",
".",
"clusters",
"for",
"word"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordclusters.py#L10-L18 |
239,311 | danielfrg/word2vec | word2vec/wordclusters.py | WordClusters.get_cluster | def get_cluster(self, word):
"""
Returns the cluster number for a word in the vocabulary
"""
idx = self.ix(word)
return self.clusters[idx] | python | def get_cluster(self, word):
idx = self.ix(word)
return self.clusters[idx] | [
"def",
"get_cluster",
"(",
"self",
",",
"word",
")",
":",
"idx",
"=",
"self",
".",
"ix",
"(",
"word",
")",
"return",
"self",
".",
"clusters",
"[",
"idx",
"]"
] | Returns the cluster number for a word in the vocabulary | [
"Returns",
"the",
"cluster",
"number",
"for",
"a",
"word",
"in",
"the",
"vocabulary"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordclusters.py#L23-L28 |
239,312 | danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.closest | def closest(self, vector, n=10, metric="cosine"):
"""Returns the closest n words to a vector
Parameters
-------
vector : numpy.array
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
"""
distances = distance(self.vectors, vector, metric=metric)
best = np.argsort(distances)[::-1][1:n + 1]
best_metrics = distances[best]
return best, best_metrics | python | def closest(self, vector, n=10, metric="cosine"):
distances = distance(self.vectors, vector, metric=metric)
best = np.argsort(distances)[::-1][1:n + 1]
best_metrics = distances[best]
return best, best_metrics | [
"def",
"closest",
"(",
"self",
",",
"vector",
",",
"n",
"=",
"10",
",",
"metric",
"=",
"\"cosine\"",
")",
":",
"distances",
"=",
"distance",
"(",
"self",
".",
"vectors",
",",
"vector",
",",
"metric",
"=",
"metric",
")",
"best",
"=",
"np",
".",
"arg... | Returns the closest n words to a vector
Parameters
-------
vector : numpy.array
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity | [
"Returns",
"the",
"closest",
"n",
"words",
"to",
"a",
"vector"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L90-L107 |
239,313 | danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.similar | def similar(self, word, n=10, metric="cosine"):
"""
Return similar words based on a metric
Parameters
----------
word : string
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
"""
return self.closest(self[word], n=n, metric=metric) | python | def similar(self, word, n=10, metric="cosine"):
return self.closest(self[word], n=n, metric=metric) | [
"def",
"similar",
"(",
"self",
",",
"word",
",",
"n",
"=",
"10",
",",
"metric",
"=",
"\"cosine\"",
")",
":",
"return",
"self",
".",
"closest",
"(",
"self",
"[",
"word",
"]",
",",
"n",
"=",
"n",
",",
"metric",
"=",
"metric",
")"
] | Return similar words based on a metric
Parameters
----------
word : string
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity | [
"Return",
"similar",
"words",
"based",
"on",
"a",
"metric"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L109-L124 |
239,314 | danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.analogy | def analogy(self, pos, neg, n=10, metric="cosine"):
"""
Analogy similarity.
Parameters
----------
pos : list
neg : list
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
Example
-------
`king - man + woman = queen` will be: `pos=['king', 'woman'], neg=['man']`
"""
exclude = pos + neg
pos = [(word, 1.0) for word in pos]
neg = [(word, -1.0) for word in neg]
mean = []
for word, direction in pos + neg:
mean.append(direction * self[word])
mean = np.array(mean).mean(axis=0)
metrics = distance(self.vectors, mean, metric=metric)
best = metrics.argsort()[::-1][:n + len(exclude)]
exclude_idx = [np.where(best == self.ix(word)) for word in exclude if self.ix(word) in best]
new_best = np.delete(best, exclude_idx)
best_metrics = metrics[new_best]
return new_best[:n], best_metrics[:n] | python | def analogy(self, pos, neg, n=10, metric="cosine"):
exclude = pos + neg
pos = [(word, 1.0) for word in pos]
neg = [(word, -1.0) for word in neg]
mean = []
for word, direction in pos + neg:
mean.append(direction * self[word])
mean = np.array(mean).mean(axis=0)
metrics = distance(self.vectors, mean, metric=metric)
best = metrics.argsort()[::-1][:n + len(exclude)]
exclude_idx = [np.where(best == self.ix(word)) for word in exclude if self.ix(word) in best]
new_best = np.delete(best, exclude_idx)
best_metrics = metrics[new_best]
return new_best[:n], best_metrics[:n] | [
"def",
"analogy",
"(",
"self",
",",
"pos",
",",
"neg",
",",
"n",
"=",
"10",
",",
"metric",
"=",
"\"cosine\"",
")",
":",
"exclude",
"=",
"pos",
"+",
"neg",
"pos",
"=",
"[",
"(",
"word",
",",
"1.0",
")",
"for",
"word",
"in",
"pos",
"]",
"neg",
... | Analogy similarity.
Parameters
----------
pos : list
neg : list
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
Example
-------
`king - man + woman = queen` will be: `pos=['king', 'woman'], neg=['man']` | [
"Analogy",
"similarity",
"."
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L126-L160 |
239,315 | danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.from_binary | def from_binary(
cls,
fname,
vocab_unicode_size=78,
desired_vocab=None,
encoding="utf-8",
new_lines=True,
):
"""
Create a WordVectors class based on a word2vec binary file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set any words that don't fall into this vocab will be droped
Returns
-------
WordVectors instance
"""
with open(fname, "rb") as fin:
# The first line has the vocab_size and the vector_size as text
header = fin.readline()
vocab_size, vector_size = list(map(int, header.split()))
vocab = np.empty(vocab_size, dtype="<U%s" % vocab_unicode_size)
vectors = np.empty((vocab_size, vector_size), dtype=np.float)
binary_len = np.dtype(np.float32).itemsize * vector_size
for i in range(vocab_size):
# read word
word = b""
while True:
ch = fin.read(1)
if ch == b" ":
break
word += ch
include = desired_vocab is None or word in desired_vocab
if include:
vocab[i] = word.decode(encoding)
# read vector
vector = np.fromstring(fin.read(binary_len), dtype=np.float32)
if include:
vectors[i] = unitvec(vector)
if new_lines:
fin.read(1) # newline char
if desired_vocab is not None:
vectors = vectors[vocab != "", :]
vocab = vocab[vocab != ""]
return cls(vocab=vocab, vectors=vectors) | python | def from_binary(
cls,
fname,
vocab_unicode_size=78,
desired_vocab=None,
encoding="utf-8",
new_lines=True,
):
with open(fname, "rb") as fin:
# The first line has the vocab_size and the vector_size as text
header = fin.readline()
vocab_size, vector_size = list(map(int, header.split()))
vocab = np.empty(vocab_size, dtype="<U%s" % vocab_unicode_size)
vectors = np.empty((vocab_size, vector_size), dtype=np.float)
binary_len = np.dtype(np.float32).itemsize * vector_size
for i in range(vocab_size):
# read word
word = b""
while True:
ch = fin.read(1)
if ch == b" ":
break
word += ch
include = desired_vocab is None or word in desired_vocab
if include:
vocab[i] = word.decode(encoding)
# read vector
vector = np.fromstring(fin.read(binary_len), dtype=np.float32)
if include:
vectors[i] = unitvec(vector)
if new_lines:
fin.read(1) # newline char
if desired_vocab is not None:
vectors = vectors[vocab != "", :]
vocab = vocab[vocab != ""]
return cls(vocab=vocab, vectors=vectors) | [
"def",
"from_binary",
"(",
"cls",
",",
"fname",
",",
"vocab_unicode_size",
"=",
"78",
",",
"desired_vocab",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"new_lines",
"=",
"True",
",",
")",
":",
"with",
"open",
"(",
"fname",
",",
"\"rb\"",
")",
... | Create a WordVectors class based on a word2vec binary file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set any words that don't fall into this vocab will be droped
Returns
-------
WordVectors instance | [
"Create",
"a",
"WordVectors",
"class",
"based",
"on",
"a",
"word2vec",
"binary",
"file"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L179-L230 |
239,316 | danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.from_text | def from_text(cls, fname, vocabUnicodeSize=78, desired_vocab=None, encoding="utf-8"):
"""
Create a WordVectors class based on a word2vec text file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set, this will ignore any word and vector that
doesn't fall inside desired_vocab.
Returns
-------
WordVectors instance
"""
with open(fname, "rb") as fin:
header = fin.readline()
vocab_size, vector_size = list(map(int, header.split()))
vocab = np.empty(vocab_size, dtype="<U%s" % vocabUnicodeSize)
vectors = np.empty((vocab_size, vector_size), dtype=np.float)
for i, line in enumerate(fin):
line = line.decode(encoding).rstrip()
parts = line.split(" ")
word = parts[0]
include = desired_vocab is None or word in desired_vocab
if include:
vector = np.array(parts[1:], dtype=np.float)
vocab[i] = word
vectors[i] = unitvec(vector)
if desired_vocab is not None:
vectors = vectors[vocab != "", :]
vocab = vocab[vocab != ""]
return cls(vocab=vocab, vectors=vectors) | python | def from_text(cls, fname, vocabUnicodeSize=78, desired_vocab=None, encoding="utf-8"):
with open(fname, "rb") as fin:
header = fin.readline()
vocab_size, vector_size = list(map(int, header.split()))
vocab = np.empty(vocab_size, dtype="<U%s" % vocabUnicodeSize)
vectors = np.empty((vocab_size, vector_size), dtype=np.float)
for i, line in enumerate(fin):
line = line.decode(encoding).rstrip()
parts = line.split(" ")
word = parts[0]
include = desired_vocab is None or word in desired_vocab
if include:
vector = np.array(parts[1:], dtype=np.float)
vocab[i] = word
vectors[i] = unitvec(vector)
if desired_vocab is not None:
vectors = vectors[vocab != "", :]
vocab = vocab[vocab != ""]
return cls(vocab=vocab, vectors=vectors) | [
"def",
"from_text",
"(",
"cls",
",",
"fname",
",",
"vocabUnicodeSize",
"=",
"78",
",",
"desired_vocab",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"with",
"open",
"(",
"fname",
",",
"\"rb\"",
")",
"as",
"fin",
":",
"header",
"=",
"fin",
... | Create a WordVectors class based on a word2vec text file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set, this will ignore any word and vector that
doesn't fall inside desired_vocab.
Returns
-------
WordVectors instance | [
"Create",
"a",
"WordVectors",
"class",
"based",
"on",
"a",
"word2vec",
"text",
"file"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L233-L267 |
239,317 | danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.from_mmap | def from_mmap(cls, fname):
"""
Create a WordVectors class from a memory map
Parameters
----------
fname : path to file
Returns
-------
WordVectors instance
"""
memmaped = joblib.load(fname, mmap_mode="r+")
return cls(vocab=memmaped.vocab, vectors=memmaped.vectors) | python | def from_mmap(cls, fname):
memmaped = joblib.load(fname, mmap_mode="r+")
return cls(vocab=memmaped.vocab, vectors=memmaped.vectors) | [
"def",
"from_mmap",
"(",
"cls",
",",
"fname",
")",
":",
"memmaped",
"=",
"joblib",
".",
"load",
"(",
"fname",
",",
"mmap_mode",
"=",
"\"r+\"",
")",
"return",
"cls",
"(",
"vocab",
"=",
"memmaped",
".",
"vocab",
",",
"vectors",
"=",
"memmaped",
".",
"v... | Create a WordVectors class from a memory map
Parameters
----------
fname : path to file
Returns
-------
WordVectors instance | [
"Create",
"a",
"WordVectors",
"class",
"from",
"a",
"memory",
"map"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L270-L283 |
239,318 | danielfrg/word2vec | word2vec/utils.py | distance | def distance(a, b, metric="cosine"):
"""
Calculate distance between two vectors based on a Metric
Metrics:
1. cosine distance. Note that in word2vec all the norms are 1 so the dot product is the same as cosine distance
"""
if metric == "cosine":
return np.dot(a, b.T)
raise Exception("Unknown metric '{metric}'".format(metric=metric)) | python | def distance(a, b, metric="cosine"):
if metric == "cosine":
return np.dot(a, b.T)
raise Exception("Unknown metric '{metric}'".format(metric=metric)) | [
"def",
"distance",
"(",
"a",
",",
"b",
",",
"metric",
"=",
"\"cosine\"",
")",
":",
"if",
"metric",
"==",
"\"cosine\"",
":",
"return",
"np",
".",
"dot",
"(",
"a",
",",
"b",
".",
"T",
")",
"raise",
"Exception",
"(",
"\"Unknown metric '{metric}'\"",
".",
... | Calculate distance between two vectors based on a Metric
Metrics:
1. cosine distance. Note that in word2vec all the norms are 1 so the dot product is the same as cosine distance | [
"Calculate",
"distance",
"between",
"two",
"vectors",
"based",
"on",
"a",
"Metric"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/utils.py#L8-L17 |
239,319 | danielfrg/word2vec | word2vec/io.py | load | def load(fname, kind="auto", *args, **kwargs):
"""
Loads a word vectors file
"""
if kind == "auto":
if fname.endswith(".bin"):
kind = "bin"
elif fname.endswith(".txt"):
kind = "txt"
else:
raise Exception("Could not identify kind")
if kind == "bin":
return word2vec.WordVectors.from_binary(fname, *args, **kwargs)
elif kind == "txt":
return word2vec.WordVectors.from_text(fname, *args, **kwargs)
elif kind == "mmap":
return word2vec.WordVectors.from_mmap(fname, *args, **kwargs)
else:
raise Exception("Unknown kind") | python | def load(fname, kind="auto", *args, **kwargs):
if kind == "auto":
if fname.endswith(".bin"):
kind = "bin"
elif fname.endswith(".txt"):
kind = "txt"
else:
raise Exception("Could not identify kind")
if kind == "bin":
return word2vec.WordVectors.from_binary(fname, *args, **kwargs)
elif kind == "txt":
return word2vec.WordVectors.from_text(fname, *args, **kwargs)
elif kind == "mmap":
return word2vec.WordVectors.from_mmap(fname, *args, **kwargs)
else:
raise Exception("Unknown kind") | [
"def",
"load",
"(",
"fname",
",",
"kind",
"=",
"\"auto\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kind",
"==",
"\"auto\"",
":",
"if",
"fname",
".",
"endswith",
"(",
"\".bin\"",
")",
":",
"kind",
"=",
"\"bin\"",
"elif",
"fname",... | Loads a word vectors file | [
"Loads",
"a",
"word",
"vectors",
"file"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/io.py#L4-L22 |
239,320 | django-crispy-forms/django-crispy-forms | crispy_forms/templatetags/crispy_forms_tags.py | ForLoopSimulator.iterate | def iterate(self):
"""
Updates values as if we had iterated over the for
"""
self.counter += 1
self.counter0 += 1
self.revcounter -= 1
self.revcounter0 -= 1
self.first = False
self.last = (self.revcounter0 == self.len_values - 1) | python | def iterate(self):
self.counter += 1
self.counter0 += 1
self.revcounter -= 1
self.revcounter0 -= 1
self.first = False
self.last = (self.revcounter0 == self.len_values - 1) | [
"def",
"iterate",
"(",
"self",
")",
":",
"self",
".",
"counter",
"+=",
"1",
"self",
".",
"counter0",
"+=",
"1",
"self",
".",
"revcounter",
"-=",
"1",
"self",
".",
"revcounter0",
"-=",
"1",
"self",
".",
"first",
"=",
"False",
"self",
".",
"last",
"=... | Updates values as if we had iterated over the for | [
"Updates",
"values",
"as",
"if",
"we",
"had",
"iterated",
"over",
"the",
"for"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/templatetags/crispy_forms_tags.py#L43-L52 |
239,321 | django-crispy-forms/django-crispy-forms | crispy_forms/templatetags/crispy_forms_tags.py | BasicNode.get_render | def get_render(self, context):
"""
Returns a `Context` object with all the necessary stuff for rendering the form
:param context: `django.template.Context` variable holding the context for the node
`self.form` and `self.helper` are resolved into real Python objects resolving them
from the `context`. The `actual_form` can be a form or a formset. If it's a formset
`is_formset` is set to True. If the helper has a layout we use it, for rendering the
form or the formset's forms.
"""
# Nodes are not thread safe in multithreaded environments
# https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#thread-safety-considerations
if self not in context.render_context:
context.render_context[self] = (
template.Variable(self.form),
template.Variable(self.helper) if self.helper else None
)
form, helper = context.render_context[self]
actual_form = form.resolve(context)
if self.helper is not None:
helper = helper.resolve(context)
else:
# If the user names the helper within the form `helper` (standard), we use it
# This allows us to have simplified tag syntax: {% crispy form %}
helper = FormHelper() if not hasattr(actual_form, 'helper') else actual_form.helper
# use template_pack from helper, if defined
try:
if helper.template_pack:
self.template_pack = helper.template_pack
except AttributeError:
pass
self.actual_helper = helper
# We get the response dictionary
is_formset = isinstance(actual_form, BaseFormSet)
response_dict = self.get_response_dict(helper, context, is_formset)
node_context = context.__copy__()
node_context.update(response_dict)
final_context = node_context.__copy__()
# If we have a helper's layout we use it, for the form or the formset's forms
if helper and helper.layout:
if not is_formset:
actual_form.form_html = helper.render_layout(actual_form, node_context, template_pack=self.template_pack)
else:
forloop = ForLoopSimulator(actual_form)
helper.render_hidden_fields = True
for form in actual_form:
node_context.update({'forloop': forloop})
node_context.update({'formset_form': form})
form.form_html = helper.render_layout(form, node_context, template_pack=self.template_pack)
forloop.iterate()
if is_formset:
final_context['formset'] = actual_form
else:
final_context['form'] = actual_form
return final_context | python | def get_render(self, context):
# Nodes are not thread safe in multithreaded environments
# https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#thread-safety-considerations
if self not in context.render_context:
context.render_context[self] = (
template.Variable(self.form),
template.Variable(self.helper) if self.helper else None
)
form, helper = context.render_context[self]
actual_form = form.resolve(context)
if self.helper is not None:
helper = helper.resolve(context)
else:
# If the user names the helper within the form `helper` (standard), we use it
# This allows us to have simplified tag syntax: {% crispy form %}
helper = FormHelper() if not hasattr(actual_form, 'helper') else actual_form.helper
# use template_pack from helper, if defined
try:
if helper.template_pack:
self.template_pack = helper.template_pack
except AttributeError:
pass
self.actual_helper = helper
# We get the response dictionary
is_formset = isinstance(actual_form, BaseFormSet)
response_dict = self.get_response_dict(helper, context, is_formset)
node_context = context.__copy__()
node_context.update(response_dict)
final_context = node_context.__copy__()
# If we have a helper's layout we use it, for the form or the formset's forms
if helper and helper.layout:
if not is_formset:
actual_form.form_html = helper.render_layout(actual_form, node_context, template_pack=self.template_pack)
else:
forloop = ForLoopSimulator(actual_form)
helper.render_hidden_fields = True
for form in actual_form:
node_context.update({'forloop': forloop})
node_context.update({'formset_form': form})
form.form_html = helper.render_layout(form, node_context, template_pack=self.template_pack)
forloop.iterate()
if is_formset:
final_context['formset'] = actual_form
else:
final_context['form'] = actual_form
return final_context | [
"def",
"get_render",
"(",
"self",
",",
"context",
")",
":",
"# Nodes are not thread safe in multithreaded environments",
"# https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#thread-safety-considerations",
"if",
"self",
"not",
"in",
"context",
".",
"render_context",
... | Returns a `Context` object with all the necessary stuff for rendering the form
:param context: `django.template.Context` variable holding the context for the node
`self.form` and `self.helper` are resolved into real Python objects resolving them
from the `context`. The `actual_form` can be a form or a formset. If it's a formset
`is_formset` is set to True. If the helper has a layout we use it, for rendering the
form or the formset's forms. | [
"Returns",
"a",
"Context",
"object",
"with",
"all",
"the",
"necessary",
"stuff",
"for",
"rendering",
"the",
"form"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/templatetags/crispy_forms_tags.py#L71-L133 |
239,322 | django-crispy-forms/django-crispy-forms | crispy_forms/templatetags/crispy_forms_utils.py | specialspaceless | def specialspaceless(parser, token):
"""
Removes whitespace between HTML tags, and introduces a whitespace
after buttons an inputs, necessary for Bootstrap to place them
correctly in the layout.
"""
nodelist = parser.parse(('endspecialspaceless',))
parser.delete_first_token()
return SpecialSpacelessNode(nodelist) | python | def specialspaceless(parser, token):
nodelist = parser.parse(('endspecialspaceless',))
parser.delete_first_token()
return SpecialSpacelessNode(nodelist) | [
"def",
"specialspaceless",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endspecialspaceless'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"SpecialSpacelessNode",
"(",
"nodelist",
")"
] | Removes whitespace between HTML tags, and introduces a whitespace
after buttons an inputs, necessary for Bootstrap to place them
correctly in the layout. | [
"Removes",
"whitespace",
"between",
"HTML",
"tags",
"and",
"introduces",
"a",
"whitespace",
"after",
"buttons",
"an",
"inputs",
"necessary",
"for",
"Bootstrap",
"to",
"place",
"them",
"correctly",
"in",
"the",
"layout",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/templatetags/crispy_forms_utils.py#L38-L47 |
239,323 | django-crispy-forms/django-crispy-forms | crispy_forms/bootstrap.py | ContainerHolder.first_container_with_errors | def first_container_with_errors(self, errors):
"""
Returns the first container with errors, otherwise returns None.
"""
for tab in self.fields:
errors_here = any(error in tab for error in errors)
if errors_here:
return tab
return None | python | def first_container_with_errors(self, errors):
for tab in self.fields:
errors_here = any(error in tab for error in errors)
if errors_here:
return tab
return None | [
"def",
"first_container_with_errors",
"(",
"self",
",",
"errors",
")",
":",
"for",
"tab",
"in",
"self",
".",
"fields",
":",
"errors_here",
"=",
"any",
"(",
"error",
"in",
"tab",
"for",
"error",
"in",
"errors",
")",
"if",
"errors_here",
":",
"return",
"ta... | Returns the first container with errors, otherwise returns None. | [
"Returns",
"the",
"first",
"container",
"with",
"errors",
"otherwise",
"returns",
"None",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/bootstrap.py#L230-L238 |
239,324 | django-crispy-forms/django-crispy-forms | crispy_forms/bootstrap.py | ContainerHolder.open_target_group_for_form | def open_target_group_for_form(self, form):
"""
Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False.
"""
target = self.first_container_with_errors(form.errors.keys())
if target is None:
target = self.fields[0]
if not getattr(target, '_active_originally_included', None):
target.active = True
return target
target.active = True
return target | python | def open_target_group_for_form(self, form):
target = self.first_container_with_errors(form.errors.keys())
if target is None:
target = self.fields[0]
if not getattr(target, '_active_originally_included', None):
target.active = True
return target
target.active = True
return target | [
"def",
"open_target_group_for_form",
"(",
"self",
",",
"form",
")",
":",
"target",
"=",
"self",
".",
"first_container_with_errors",
"(",
"form",
".",
"errors",
".",
"keys",
"(",
")",
")",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"self",
".",
"fi... | Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False. | [
"Makes",
"sure",
"that",
"the",
"first",
"group",
"that",
"should",
"be",
"open",
"is",
"open",
".",
"This",
"is",
"either",
"the",
"first",
"group",
"with",
"errors",
"or",
"the",
"first",
"group",
"in",
"the",
"container",
"unless",
"that",
"first",
"g... | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/bootstrap.py#L240-L255 |
239,325 | django-crispy-forms/django-crispy-forms | crispy_forms/bootstrap.py | Tab.render_link | def render_link(self, template_pack=TEMPLATE_PACK, **kwargs):
"""
Render the link for the tab-pane. It must be called after render so css_class is updated
with active if needed.
"""
link_template = self.link_template % template_pack
return render_to_string(link_template, {'link': self}) | python | def render_link(self, template_pack=TEMPLATE_PACK, **kwargs):
link_template = self.link_template % template_pack
return render_to_string(link_template, {'link': self}) | [
"def",
"render_link",
"(",
"self",
",",
"template_pack",
"=",
"TEMPLATE_PACK",
",",
"*",
"*",
"kwargs",
")",
":",
"link_template",
"=",
"self",
".",
"link_template",
"%",
"template_pack",
"return",
"render_to_string",
"(",
"link_template",
",",
"{",
"'link'",
... | Render the link for the tab-pane. It must be called after render so css_class is updated
with active if needed. | [
"Render",
"the",
"link",
"for",
"the",
"tab",
"-",
"pane",
".",
"It",
"must",
"be",
"called",
"after",
"render",
"so",
"css_class",
"is",
"updated",
"with",
"active",
"if",
"needed",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/bootstrap.py#L268-L274 |
239,326 | django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.wrapped_object | def wrapped_object(self, LayoutClass, fields, *args, **kwargs):
"""
Returns a layout object of type `LayoutClass` with `args` and `kwargs` that
wraps `fields` inside.
"""
if args:
if isinstance(fields, list):
fields = tuple(fields)
else:
fields = (fields,)
if LayoutClass in self.args_first:
arguments = args + fields
else:
arguments = fields + args
return LayoutClass(*arguments, **kwargs)
else:
if isinstance(fields, list):
return LayoutClass(*fields, **kwargs)
else:
return LayoutClass(fields, **kwargs) | python | def wrapped_object(self, LayoutClass, fields, *args, **kwargs):
if args:
if isinstance(fields, list):
fields = tuple(fields)
else:
fields = (fields,)
if LayoutClass in self.args_first:
arguments = args + fields
else:
arguments = fields + args
return LayoutClass(*arguments, **kwargs)
else:
if isinstance(fields, list):
return LayoutClass(*fields, **kwargs)
else:
return LayoutClass(fields, **kwargs) | [
"def",
"wrapped_object",
"(",
"self",
",",
"LayoutClass",
",",
"fields",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"if",
"isinstance",
"(",
"fields",
",",
"list",
")",
":",
"fields",
"=",
"tuple",
"(",
"fields",
")",
"... | Returns a layout object of type `LayoutClass` with `args` and `kwargs` that
wraps `fields` inside. | [
"Returns",
"a",
"layout",
"object",
"of",
"type",
"LayoutClass",
"with",
"args",
"and",
"kwargs",
"that",
"wraps",
"fields",
"inside",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L19-L40 |
239,327 | django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.pre_map | def pre_map(self, function):
"""
Iterates over layout objects pointed in `self.slice` executing `function` on them.
It passes `function` penultimate layout object and the position where to find last one
"""
if isinstance(self.slice, slice):
for i in range(*self.slice.indices(len(self.layout.fields))):
function(self.layout, i)
elif isinstance(self.slice, list):
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
for pointer in self.slice:
position = pointer[0]
# If it's pointing first level
if len(position) == 1:
function(self.layout, position[-1])
else:
layout_object = self.layout.fields[position[0]]
for i in position[1:-1]:
layout_object = layout_object.fields[i]
try:
function(layout_object, position[-1])
except IndexError:
# We could avoid this exception, recalculating pointers.
# However this case is most of the time an undesired behavior
raise DynamicError("Trying to wrap a field within an already wrapped field, \
recheck your filter or layout") | python | def pre_map(self, function):
if isinstance(self.slice, slice):
for i in range(*self.slice.indices(len(self.layout.fields))):
function(self.layout, i)
elif isinstance(self.slice, list):
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
for pointer in self.slice:
position = pointer[0]
# If it's pointing first level
if len(position) == 1:
function(self.layout, position[-1])
else:
layout_object = self.layout.fields[position[0]]
for i in position[1:-1]:
layout_object = layout_object.fields[i]
try:
function(layout_object, position[-1])
except IndexError:
# We could avoid this exception, recalculating pointers.
# However this case is most of the time an undesired behavior
raise DynamicError("Trying to wrap a field within an already wrapped field, \
recheck your filter or layout") | [
"def",
"pre_map",
"(",
"self",
",",
"function",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"slice",
",",
"slice",
")",
":",
"for",
"i",
"in",
"range",
"(",
"*",
"self",
".",
"slice",
".",
"indices",
"(",
"len",
"(",
"self",
".",
"layout",
".... | Iterates over layout objects pointed in `self.slice` executing `function` on them.
It passes `function` penultimate layout object and the position where to find last one | [
"Iterates",
"over",
"layout",
"objects",
"pointed",
"in",
"self",
".",
"slice",
"executing",
"function",
"on",
"them",
".",
"It",
"passes",
"function",
"penultimate",
"layout",
"object",
"and",
"the",
"position",
"where",
"to",
"find",
"last",
"one"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L42-L70 |
239,328 | django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.wrap | def wrap(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed.
"""
def wrap_object(layout_object, j):
layout_object.fields[j] = self.wrapped_object(
LayoutClass, layout_object.fields[j], *args, **kwargs
)
self.pre_map(wrap_object) | python | def wrap(self, LayoutClass, *args, **kwargs):
def wrap_object(layout_object, j):
layout_object.fields[j] = self.wrapped_object(
LayoutClass, layout_object.fields[j], *args, **kwargs
)
self.pre_map(wrap_object) | [
"def",
"wrap",
"(",
"self",
",",
"LayoutClass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap_object",
"(",
"layout_object",
",",
"j",
")",
":",
"layout_object",
".",
"fields",
"[",
"j",
"]",
"=",
"self",
".",
"wrapped_object",
"(... | Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed. | [
"Wraps",
"every",
"layout",
"object",
"pointed",
"in",
"self",
".",
"slice",
"under",
"a",
"LayoutClass",
"instance",
"with",
"args",
"and",
"kwargs",
"passed",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L72-L82 |
239,329 | django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.wrap_once | def wrap_once(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed, unless layout object's parent is already a subclass of
`LayoutClass`.
"""
def wrap_object_once(layout_object, j):
if not isinstance(layout_object, LayoutClass):
layout_object.fields[j] = self.wrapped_object(
LayoutClass, layout_object.fields[j], *args, **kwargs
)
self.pre_map(wrap_object_once) | python | def wrap_once(self, LayoutClass, *args, **kwargs):
def wrap_object_once(layout_object, j):
if not isinstance(layout_object, LayoutClass):
layout_object.fields[j] = self.wrapped_object(
LayoutClass, layout_object.fields[j], *args, **kwargs
)
self.pre_map(wrap_object_once) | [
"def",
"wrap_once",
"(",
"self",
",",
"LayoutClass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap_object_once",
"(",
"layout_object",
",",
"j",
")",
":",
"if",
"not",
"isinstance",
"(",
"layout_object",
",",
"LayoutClass",
")",
":",
... | Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed, unless layout object's parent is already a subclass of
`LayoutClass`. | [
"Wraps",
"every",
"layout",
"object",
"pointed",
"in",
"self",
".",
"slice",
"under",
"a",
"LayoutClass",
"instance",
"with",
"args",
"and",
"kwargs",
"passed",
"unless",
"layout",
"object",
"s",
"parent",
"is",
"already",
"a",
"subclass",
"of",
"LayoutClass",... | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L84-L96 |
239,330 | django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.wrap_together | def wrap_together(self, LayoutClass, *args, **kwargs):
"""
Wraps all layout objects pointed in `self.slice` together under a `LayoutClass`
instance with `args` and `kwargs` passed.
"""
if isinstance(self.slice, slice):
# The start of the slice is replaced
start = self.slice.start if self.slice.start is not None else 0
self.layout.fields[start] = self.wrapped_object(
LayoutClass, self.layout.fields[self.slice], *args, **kwargs
)
# The rest of places of the slice are removed, as they are included in the previous
for i in reversed(range(*self.slice.indices(len(self.layout.fields)))):
if i != start:
del self.layout.fields[i]
elif isinstance(self.slice, list):
raise DynamicError("wrap_together doesn't work with filter, only with [] operator") | python | def wrap_together(self, LayoutClass, *args, **kwargs):
if isinstance(self.slice, slice):
# The start of the slice is replaced
start = self.slice.start if self.slice.start is not None else 0
self.layout.fields[start] = self.wrapped_object(
LayoutClass, self.layout.fields[self.slice], *args, **kwargs
)
# The rest of places of the slice are removed, as they are included in the previous
for i in reversed(range(*self.slice.indices(len(self.layout.fields)))):
if i != start:
del self.layout.fields[i]
elif isinstance(self.slice, list):
raise DynamicError("wrap_together doesn't work with filter, only with [] operator") | [
"def",
"wrap_together",
"(",
"self",
",",
"LayoutClass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"slice",
",",
"slice",
")",
":",
"# The start of the slice is replaced",
"start",
"=",
"self",
".",
"slice",... | Wraps all layout objects pointed in `self.slice` together under a `LayoutClass`
instance with `args` and `kwargs` passed. | [
"Wraps",
"all",
"layout",
"objects",
"pointed",
"in",
"self",
".",
"slice",
"together",
"under",
"a",
"LayoutClass",
"instance",
"with",
"args",
"and",
"kwargs",
"passed",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L98-L116 |
239,331 | django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.map | def map(self, function):
"""
Iterates over layout objects pointed in `self.slice` executing `function` on them
It passes `function` last layout object
"""
if isinstance(self.slice, slice):
for i in range(*self.slice.indices(len(self.layout.fields))):
function(self.layout.fields[i])
elif isinstance(self.slice, list):
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
for pointer in self.slice:
position = pointer[0]
layout_object = self.layout.fields[position[0]]
for i in position[1:]:
previous_layout_object = layout_object
layout_object = layout_object.fields[i]
# If update_attrs is applied to a string, we call to its wrapping layout object
if (
function.__name__ == 'update_attrs'
and isinstance(layout_object, string_types)
):
function(previous_layout_object)
else:
function(layout_object) | python | def map(self, function):
if isinstance(self.slice, slice):
for i in range(*self.slice.indices(len(self.layout.fields))):
function(self.layout.fields[i])
elif isinstance(self.slice, list):
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
for pointer in self.slice:
position = pointer[0]
layout_object = self.layout.fields[position[0]]
for i in position[1:]:
previous_layout_object = layout_object
layout_object = layout_object.fields[i]
# If update_attrs is applied to a string, we call to its wrapping layout object
if (
function.__name__ == 'update_attrs'
and isinstance(layout_object, string_types)
):
function(previous_layout_object)
else:
function(layout_object) | [
"def",
"map",
"(",
"self",
",",
"function",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"slice",
",",
"slice",
")",
":",
"for",
"i",
"in",
"range",
"(",
"*",
"self",
".",
"slice",
".",
"indices",
"(",
"len",
"(",
"self",
".",
"layout",
".",
... | Iterates over layout objects pointed in `self.slice` executing `function` on them
It passes `function` last layout object | [
"Iterates",
"over",
"layout",
"objects",
"pointed",
"in",
"self",
".",
"slice",
"executing",
"function",
"on",
"them",
"It",
"passes",
"function",
"last",
"layout",
"object"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L118-L144 |
239,332 | django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.update_attributes | def update_attributes(self, **original_kwargs):
"""
Updates attributes of every layout object pointed in `self.slice` using kwargs
"""
def update_attrs(layout_object):
kwargs = original_kwargs.copy()
if hasattr(layout_object, 'attrs'):
if 'css_class' in kwargs:
if 'class' in layout_object.attrs:
layout_object.attrs['class'] += " %s" % kwargs.pop('css_class')
else:
layout_object.attrs['class'] = kwargs.pop('css_class')
layout_object.attrs.update(kwargs)
self.map(update_attrs) | python | def update_attributes(self, **original_kwargs):
def update_attrs(layout_object):
kwargs = original_kwargs.copy()
if hasattr(layout_object, 'attrs'):
if 'css_class' in kwargs:
if 'class' in layout_object.attrs:
layout_object.attrs['class'] += " %s" % kwargs.pop('css_class')
else:
layout_object.attrs['class'] = kwargs.pop('css_class')
layout_object.attrs.update(kwargs)
self.map(update_attrs) | [
"def",
"update_attributes",
"(",
"self",
",",
"*",
"*",
"original_kwargs",
")",
":",
"def",
"update_attrs",
"(",
"layout_object",
")",
":",
"kwargs",
"=",
"original_kwargs",
".",
"copy",
"(",
")",
"if",
"hasattr",
"(",
"layout_object",
",",
"'attrs'",
")",
... | Updates attributes of every layout object pointed in `self.slice` using kwargs | [
"Updates",
"attributes",
"of",
"every",
"layout",
"object",
"pointed",
"in",
"self",
".",
"slice",
"using",
"kwargs"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L146-L160 |
239,333 | django-crispy-forms/django-crispy-forms | crispy_forms/helper.py | DynamicLayoutHandler.all | def all(self):
"""
Returns all layout objects of first level of depth
"""
self._check_layout()
return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1)) | python | def all(self):
self._check_layout()
return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1)) | [
"def",
"all",
"(",
"self",
")",
":",
"self",
".",
"_check_layout",
"(",
")",
"return",
"LayoutSlice",
"(",
"self",
".",
"layout",
",",
"slice",
"(",
"0",
",",
"len",
"(",
"self",
".",
"layout",
".",
"fields",
")",
",",
"1",
")",
")"
] | Returns all layout objects of first level of depth | [
"Returns",
"all",
"layout",
"objects",
"of",
"first",
"level",
"of",
"depth"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/helper.py#L31-L36 |
239,334 | django-crispy-forms/django-crispy-forms | crispy_forms/helper.py | DynamicLayoutHandler.filter | def filter(self, *LayoutClasses, **kwargs):
"""
Returns a LayoutSlice pointing to layout objects of type `LayoutClass`
"""
self._check_layout()
max_level = kwargs.pop('max_level', 0)
greedy = kwargs.pop('greedy', False)
filtered_layout_objects = self.layout.get_layout_objects(LayoutClasses, max_level=max_level, greedy=greedy)
return LayoutSlice(self.layout, filtered_layout_objects) | python | def filter(self, *LayoutClasses, **kwargs):
self._check_layout()
max_level = kwargs.pop('max_level', 0)
greedy = kwargs.pop('greedy', False)
filtered_layout_objects = self.layout.get_layout_objects(LayoutClasses, max_level=max_level, greedy=greedy)
return LayoutSlice(self.layout, filtered_layout_objects) | [
"def",
"filter",
"(",
"self",
",",
"*",
"LayoutClasses",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_layout",
"(",
")",
"max_level",
"=",
"kwargs",
".",
"pop",
"(",
"'max_level'",
",",
"0",
")",
"greedy",
"=",
"kwargs",
".",
"pop",
"(",
... | Returns a LayoutSlice pointing to layout objects of type `LayoutClass` | [
"Returns",
"a",
"LayoutSlice",
"pointing",
"to",
"layout",
"objects",
"of",
"type",
"LayoutClass"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/helper.py#L38-L47 |
239,335 | django-crispy-forms/django-crispy-forms | crispy_forms/helper.py | DynamicLayoutHandler.filter_by_widget | def filter_by_widget(self, widget_type):
"""
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
"""
self._check_layout_and_form()
layout_field_names = self.layout.get_field_names()
# Let's filter all fields with widgets like widget_type
filtered_fields = []
for pointer in layout_field_names:
if isinstance(self.form.fields[pointer[1]].widget, widget_type):
filtered_fields.append(pointer)
return LayoutSlice(self.layout, filtered_fields) | python | def filter_by_widget(self, widget_type):
self._check_layout_and_form()
layout_field_names = self.layout.get_field_names()
# Let's filter all fields with widgets like widget_type
filtered_fields = []
for pointer in layout_field_names:
if isinstance(self.form.fields[pointer[1]].widget, widget_type):
filtered_fields.append(pointer)
return LayoutSlice(self.layout, filtered_fields) | [
"def",
"filter_by_widget",
"(",
"self",
",",
"widget_type",
")",
":",
"self",
".",
"_check_layout_and_form",
"(",
")",
"layout_field_names",
"=",
"self",
".",
"layout",
".",
"get_field_names",
"(",
")",
"# Let's filter all fields with widgets like widget_type",
"filtere... | Returns a LayoutSlice pointing to fields with widgets of `widget_type` | [
"Returns",
"a",
"LayoutSlice",
"pointing",
"to",
"fields",
"with",
"widgets",
"of",
"widget_type"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/helper.py#L49-L62 |
239,336 | django-crispy-forms/django-crispy-forms | crispy_forms/helper.py | FormHelper.get_attributes | def get_attributes(self, template_pack=TEMPLATE_PACK):
"""
Used by crispy_forms_tags to get helper attributes
"""
items = {
'form_method': self.form_method.strip(),
'form_tag': self.form_tag,
'form_style': self.form_style.strip(),
'form_show_errors': self.form_show_errors,
'help_text_inline': self.help_text_inline,
'error_text_inline': self.error_text_inline,
'html5_required': self.html5_required,
'form_show_labels': self.form_show_labels,
'disable_csrf': self.disable_csrf,
'label_class': self.label_class,
'field_class': self.field_class,
'include_media': self.include_media
}
if template_pack == 'bootstrap4':
bootstrap_size_match = re.findall('col-(xl|lg|md|sm)-(\d+)', self.label_class)
if bootstrap_size_match:
if template_pack == 'bootstrap4':
offset_pattern = 'offset-%s-%s'
else:
offset_pattern = 'col-%s-offset-%s'
items['bootstrap_checkbox_offsets'] = [offset_pattern % m for m in bootstrap_size_match]
else:
bootstrap_size_match = re.findall('col-(lg|md|sm|xs)-(\d+)', self.label_class)
if bootstrap_size_match:
if template_pack == 'bootstrap4':
offset_pattern = 'offset-%s-%s'
else:
offset_pattern = 'col-%s-offset-%s'
items['bootstrap_checkbox_offsets'] = [offset_pattern % m for m in bootstrap_size_match]
items['attrs'] = {}
if self.attrs:
items['attrs'] = self.attrs.copy()
if self.form_action:
items['attrs']['action'] = self.form_action.strip()
if self.form_id:
items['attrs']['id'] = self.form_id.strip()
if self.form_class:
# uni_form TEMPLATE PACK has a uniForm class by default
if template_pack == 'uni_form':
items['attrs']['class'] = "uniForm %s" % self.form_class.strip()
else:
items['attrs']['class'] = self.form_class.strip()
else:
if template_pack == 'uni_form':
items['attrs']['class'] = self.attrs.get('class', '') + " uniForm"
if self.form_group_wrapper_class:
items['attrs']['form_group_wrapper_class'] = self.form_group_wrapper_class
items['flat_attrs'] = flatatt(items['attrs'])
if self.inputs:
items['inputs'] = self.inputs
if self.form_error_title:
items['form_error_title'] = self.form_error_title.strip()
if self.formset_error_title:
items['formset_error_title'] = self.formset_error_title.strip()
for attribute_name, value in self.__dict__.items():
if attribute_name not in items and attribute_name not in ['layout', 'inputs'] and not attribute_name.startswith('_'):
items[attribute_name] = value
return items | python | def get_attributes(self, template_pack=TEMPLATE_PACK):
items = {
'form_method': self.form_method.strip(),
'form_tag': self.form_tag,
'form_style': self.form_style.strip(),
'form_show_errors': self.form_show_errors,
'help_text_inline': self.help_text_inline,
'error_text_inline': self.error_text_inline,
'html5_required': self.html5_required,
'form_show_labels': self.form_show_labels,
'disable_csrf': self.disable_csrf,
'label_class': self.label_class,
'field_class': self.field_class,
'include_media': self.include_media
}
if template_pack == 'bootstrap4':
bootstrap_size_match = re.findall('col-(xl|lg|md|sm)-(\d+)', self.label_class)
if bootstrap_size_match:
if template_pack == 'bootstrap4':
offset_pattern = 'offset-%s-%s'
else:
offset_pattern = 'col-%s-offset-%s'
items['bootstrap_checkbox_offsets'] = [offset_pattern % m for m in bootstrap_size_match]
else:
bootstrap_size_match = re.findall('col-(lg|md|sm|xs)-(\d+)', self.label_class)
if bootstrap_size_match:
if template_pack == 'bootstrap4':
offset_pattern = 'offset-%s-%s'
else:
offset_pattern = 'col-%s-offset-%s'
items['bootstrap_checkbox_offsets'] = [offset_pattern % m for m in bootstrap_size_match]
items['attrs'] = {}
if self.attrs:
items['attrs'] = self.attrs.copy()
if self.form_action:
items['attrs']['action'] = self.form_action.strip()
if self.form_id:
items['attrs']['id'] = self.form_id.strip()
if self.form_class:
# uni_form TEMPLATE PACK has a uniForm class by default
if template_pack == 'uni_form':
items['attrs']['class'] = "uniForm %s" % self.form_class.strip()
else:
items['attrs']['class'] = self.form_class.strip()
else:
if template_pack == 'uni_form':
items['attrs']['class'] = self.attrs.get('class', '') + " uniForm"
if self.form_group_wrapper_class:
items['attrs']['form_group_wrapper_class'] = self.form_group_wrapper_class
items['flat_attrs'] = flatatt(items['attrs'])
if self.inputs:
items['inputs'] = self.inputs
if self.form_error_title:
items['form_error_title'] = self.form_error_title.strip()
if self.formset_error_title:
items['formset_error_title'] = self.formset_error_title.strip()
for attribute_name, value in self.__dict__.items():
if attribute_name not in items and attribute_name not in ['layout', 'inputs'] and not attribute_name.startswith('_'):
items[attribute_name] = value
return items | [
"def",
"get_attributes",
"(",
"self",
",",
"template_pack",
"=",
"TEMPLATE_PACK",
")",
":",
"items",
"=",
"{",
"'form_method'",
":",
"self",
".",
"form_method",
".",
"strip",
"(",
")",
",",
"'form_tag'",
":",
"self",
".",
"form_tag",
",",
"'form_style'",
"... | Used by crispy_forms_tags to get helper attributes | [
"Used",
"by",
"crispy_forms_tags",
"to",
"get",
"helper",
"attributes"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/helper.py#L353-L421 |
239,337 | django-crispy-forms/django-crispy-forms | crispy_forms/utils.py | flatatt | def flatatt(attrs):
"""
Convert a dictionary of attributes to a single string.
Passed attributes are redirected to `django.forms.utils.flatatt()`
with replaced "_" (underscores) by "-" (dashes) in their names.
"""
return _flatatt({k.replace('_', '-'): v for k, v in attrs.items()}) | python | def flatatt(attrs):
return _flatatt({k.replace('_', '-'): v for k, v in attrs.items()}) | [
"def",
"flatatt",
"(",
"attrs",
")",
":",
"return",
"_flatatt",
"(",
"{",
"k",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"items",
"(",
")",
"}",
")"
] | Convert a dictionary of attributes to a single string.
Passed attributes are redirected to `django.forms.utils.flatatt()`
with replaced "_" (underscores) by "-" (dashes) in their names. | [
"Convert",
"a",
"dictionary",
"of",
"attributes",
"to",
"a",
"single",
"string",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/utils.py#L153-L160 |
239,338 | django-crispy-forms/django-crispy-forms | crispy_forms/utils.py | render_crispy_form | def render_crispy_form(form, helper=None, context=None):
"""
Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view.
"""
from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode
if helper is not None:
node = CrispyFormNode('form', 'helper')
else:
node = CrispyFormNode('form', None)
node_context = Context(context)
node_context.update({
'form': form,
'helper': helper
})
return node.render(node_context) | python | def render_crispy_form(form, helper=None, context=None):
from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode
if helper is not None:
node = CrispyFormNode('form', 'helper')
else:
node = CrispyFormNode('form', None)
node_context = Context(context)
node_context.update({
'form': form,
'helper': helper
})
return node.render(node_context) | [
"def",
"render_crispy_form",
"(",
"form",
",",
"helper",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"from",
"crispy_forms",
".",
"templatetags",
".",
"crispy_forms_tags",
"import",
"CrispyFormNode",
"if",
"helper",
"is",
"not",
"None",
":",
"node",
... | Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view. | [
"Renders",
"a",
"form",
"and",
"returns",
"its",
"HTML",
"output",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/utils.py#L163-L182 |
239,339 | moderngl/moderngl | moderngl/vertex_array.py | VertexArray.bind | def bind(self, attribute, cls, buffer, fmt, *, offset=0, stride=0, divisor=0, normalize=False) -> None:
'''
Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer (Buffer): The buffer.
format (str): The buffer format.
Keyword Args:
offset (int): The offset.
stride (int): The stride.
divisor (int): The divisor.
normalize (bool): The normalize parameter, if applicable.
'''
self.mglo.bind(attribute, cls, buffer.mglo, fmt, offset, stride, divisor, normalize) | python | def bind(self, attribute, cls, buffer, fmt, *, offset=0, stride=0, divisor=0, normalize=False) -> None:
'''
Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer (Buffer): The buffer.
format (str): The buffer format.
Keyword Args:
offset (int): The offset.
stride (int): The stride.
divisor (int): The divisor.
normalize (bool): The normalize parameter, if applicable.
'''
self.mglo.bind(attribute, cls, buffer.mglo, fmt, offset, stride, divisor, normalize) | [
"def",
"bind",
"(",
"self",
",",
"attribute",
",",
"cls",
",",
"buffer",
",",
"fmt",
",",
"*",
",",
"offset",
"=",
"0",
",",
"stride",
"=",
"0",
",",
"divisor",
"=",
"0",
",",
"normalize",
"=",
"False",
")",
"->",
"None",
":",
"self",
".",
"mgl... | Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer (Buffer): The buffer.
format (str): The buffer format.
Keyword Args:
offset (int): The offset.
stride (int): The stride.
divisor (int): The divisor.
normalize (bool): The normalize parameter, if applicable. | [
"Bind",
"individual",
"attributes",
"to",
"buffers",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/vertex_array.py#L173-L190 |
239,340 | moderngl/moderngl | examples/08_compute_shader.py | source | def source(uri, consts):
''' read gl code '''
with open(uri, 'r') as fp:
content = fp.read()
# feed constant values
for key, value in consts.items():
content = content.replace(f"%%{key}%%", str(value))
return content | python | def source(uri, consts):
''' read gl code '''
with open(uri, 'r') as fp:
content = fp.read()
# feed constant values
for key, value in consts.items():
content = content.replace(f"%%{key}%%", str(value))
return content | [
"def",
"source",
"(",
"uri",
",",
"consts",
")",
":",
"with",
"open",
"(",
"uri",
",",
"'r'",
")",
"as",
"fp",
":",
"content",
"=",
"fp",
".",
"read",
"(",
")",
"# feed constant values",
"for",
"key",
",",
"value",
"in",
"consts",
".",
"items",
"("... | read gl code | [
"read",
"gl",
"code"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/08_compute_shader.py#L17-L25 |
239,341 | moderngl/moderngl | moderngl/context.py | create_standalone_context | def create_standalone_context(require=None, **settings) -> 'Context':
'''
Create a standalone ModernGL context.
Example::
# Create a context with highest possible supported version
ctx = moderngl.create_context()
# Require at least OpenGL 4.3
ctx = moderngl.create_context(require=430)
Keyword Arguments:
require (int): OpenGL version code.
Returns:
:py:class:`Context` object
'''
backend = os.environ.get('MODERNGL_BACKEND')
if backend is not None:
settings['backend'] = backend
ctx = Context.__new__(Context)
ctx.mglo, ctx.version_code = mgl.create_standalone_context(settings)
ctx._screen = None
ctx.fbo = None
ctx._info = None
ctx.extra = None
if require is not None and ctx.version_code < require:
raise ValueError('Requested OpenGL version {}, got version {}'.format(
require, ctx.version_code))
return ctx | python | def create_standalone_context(require=None, **settings) -> 'Context':
'''
Create a standalone ModernGL context.
Example::
# Create a context with highest possible supported version
ctx = moderngl.create_context()
# Require at least OpenGL 4.3
ctx = moderngl.create_context(require=430)
Keyword Arguments:
require (int): OpenGL version code.
Returns:
:py:class:`Context` object
'''
backend = os.environ.get('MODERNGL_BACKEND')
if backend is not None:
settings['backend'] = backend
ctx = Context.__new__(Context)
ctx.mglo, ctx.version_code = mgl.create_standalone_context(settings)
ctx._screen = None
ctx.fbo = None
ctx._info = None
ctx.extra = None
if require is not None and ctx.version_code < require:
raise ValueError('Requested OpenGL version {}, got version {}'.format(
require, ctx.version_code))
return ctx | [
"def",
"create_standalone_context",
"(",
"require",
"=",
"None",
",",
"*",
"*",
"settings",
")",
"->",
"'Context'",
":",
"backend",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'MODERNGL_BACKEND'",
")",
"if",
"backend",
"is",
"not",
"None",
":",
"settings"... | Create a standalone ModernGL context.
Example::
# Create a context with highest possible supported version
ctx = moderngl.create_context()
# Require at least OpenGL 4.3
ctx = moderngl.create_context(require=430)
Keyword Arguments:
require (int): OpenGL version code.
Returns:
:py:class:`Context` object | [
"Create",
"a",
"standalone",
"ModernGL",
"context",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L1135-L1169 |
239,342 | moderngl/moderngl | moderngl/context.py | Context.copy_buffer | def copy_buffer(self, dst, src, size=-1, *, read_offset=0, write_offset=0) -> None:
'''
Copy buffer content.
Args:
dst (Buffer): The destination buffer.
src (Buffer): The source buffer.
size (int): The number of bytes to copy.
Keyword Args:
read_offset (int): The read offset.
write_offset (int): The write offset.
'''
self.mglo.copy_buffer(dst.mglo, src.mglo, size, read_offset, write_offset) | python | def copy_buffer(self, dst, src, size=-1, *, read_offset=0, write_offset=0) -> None:
'''
Copy buffer content.
Args:
dst (Buffer): The destination buffer.
src (Buffer): The source buffer.
size (int): The number of bytes to copy.
Keyword Args:
read_offset (int): The read offset.
write_offset (int): The write offset.
'''
self.mglo.copy_buffer(dst.mglo, src.mglo, size, read_offset, write_offset) | [
"def",
"copy_buffer",
"(",
"self",
",",
"dst",
",",
"src",
",",
"size",
"=",
"-",
"1",
",",
"*",
",",
"read_offset",
"=",
"0",
",",
"write_offset",
"=",
"0",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"copy_buffer",
"(",
"dst",
".",
"mglo"... | Copy buffer content.
Args:
dst (Buffer): The destination buffer.
src (Buffer): The source buffer.
size (int): The number of bytes to copy.
Keyword Args:
read_offset (int): The read offset.
write_offset (int): The write offset. | [
"Copy",
"buffer",
"content",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L505-L519 |
239,343 | moderngl/moderngl | moderngl/context.py | Context.copy_framebuffer | def copy_framebuffer(self, dst, src) -> None:
'''
Copy framebuffer content.
Use this method to:
- blit framebuffers.
- copy framebuffer content into a texture.
- downsample framebuffers. (it will allow to read the framebuffer's content)
- downsample a framebuffer directly to a texture.
Args:
dst (Framebuffer or Texture): Destination framebuffer or texture.
src (Framebuffer): Source framebuffer.
'''
self.mglo.copy_framebuffer(dst.mglo, src.mglo) | python | def copy_framebuffer(self, dst, src) -> None:
'''
Copy framebuffer content.
Use this method to:
- blit framebuffers.
- copy framebuffer content into a texture.
- downsample framebuffers. (it will allow to read the framebuffer's content)
- downsample a framebuffer directly to a texture.
Args:
dst (Framebuffer or Texture): Destination framebuffer or texture.
src (Framebuffer): Source framebuffer.
'''
self.mglo.copy_framebuffer(dst.mglo, src.mglo) | [
"def",
"copy_framebuffer",
"(",
"self",
",",
"dst",
",",
"src",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"copy_framebuffer",
"(",
"dst",
".",
"mglo",
",",
"src",
".",
"mglo",
")"
] | Copy framebuffer content.
Use this method to:
- blit framebuffers.
- copy framebuffer content into a texture.
- downsample framebuffers. (it will allow to read the framebuffer's content)
- downsample a framebuffer directly to a texture.
Args:
dst (Framebuffer or Texture): Destination framebuffer or texture.
src (Framebuffer): Source framebuffer. | [
"Copy",
"framebuffer",
"content",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L521-L537 |
239,344 | moderngl/moderngl | moderngl/context.py | Context.detect_framebuffer | def detect_framebuffer(self, glo=None) -> 'Framebuffer':
'''
Detect framebuffer.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object
'''
res = Framebuffer.__new__(Framebuffer)
res.mglo, res._size, res._samples, res._glo = self.mglo.detect_framebuffer(glo)
res._color_attachments = None
res._depth_attachment = None
res.ctx = self
res.extra = None
return res | python | def detect_framebuffer(self, glo=None) -> 'Framebuffer':
'''
Detect framebuffer.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object
'''
res = Framebuffer.__new__(Framebuffer)
res.mglo, res._size, res._samples, res._glo = self.mglo.detect_framebuffer(glo)
res._color_attachments = None
res._depth_attachment = None
res.ctx = self
res.extra = None
return res | [
"def",
"detect_framebuffer",
"(",
"self",
",",
"glo",
"=",
"None",
")",
"->",
"'Framebuffer'",
":",
"res",
"=",
"Framebuffer",
".",
"__new__",
"(",
"Framebuffer",
")",
"res",
".",
"mglo",
",",
"res",
".",
"_size",
",",
"res",
".",
"_samples",
",",
"res... | Detect framebuffer.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object | [
"Detect",
"framebuffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L539-L556 |
239,345 | moderngl/moderngl | moderngl/context.py | Context.core_profile_check | def core_profile_check(self) -> None:
'''
Core profile check.
FOR DEBUG PURPOSES ONLY
'''
profile_mask = self.info['GL_CONTEXT_PROFILE_MASK']
if profile_mask != 1:
warnings.warn('The window should request a CORE OpenGL profile')
version_code = self.version_code
if not version_code:
major, minor = map(int, self.info['GL_VERSION'].split('.', 2)[:2])
version_code = major * 100 + minor * 10
if version_code < 330:
warnings.warn('The window should support OpenGL 3.3+ (version_code=%d)' % version_code) | python | def core_profile_check(self) -> None:
'''
Core profile check.
FOR DEBUG PURPOSES ONLY
'''
profile_mask = self.info['GL_CONTEXT_PROFILE_MASK']
if profile_mask != 1:
warnings.warn('The window should request a CORE OpenGL profile')
version_code = self.version_code
if not version_code:
major, minor = map(int, self.info['GL_VERSION'].split('.', 2)[:2])
version_code = major * 100 + minor * 10
if version_code < 330:
warnings.warn('The window should support OpenGL 3.3+ (version_code=%d)' % version_code) | [
"def",
"core_profile_check",
"(",
"self",
")",
"->",
"None",
":",
"profile_mask",
"=",
"self",
".",
"info",
"[",
"'GL_CONTEXT_PROFILE_MASK'",
"]",
"if",
"profile_mask",
"!=",
"1",
":",
"warnings",
".",
"warn",
"(",
"'The window should request a CORE OpenGL profile'"... | Core profile check.
FOR DEBUG PURPOSES ONLY | [
"Core",
"profile",
"check",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L1072-L1089 |
239,346 | moderngl/moderngl | examples/window/glfw/window.py | Window.mouse_button_callback | def mouse_button_callback(self, window, button, action, mods):
"""
Handle mouse button events and forward them to the example
"""
# Offset button index by 1 to make it match the other libraries
button += 1
# Support left and right mouse button for now
if button not in [1, 2]:
return
xpos, ypos = glfw.get_cursor_pos(self.window)
if action == glfw.PRESS:
self.example.mouse_press_event(xpos, ypos, button)
else:
self.example.mouse_release_event(xpos, ypos, button) | python | def mouse_button_callback(self, window, button, action, mods):
# Offset button index by 1 to make it match the other libraries
button += 1
# Support left and right mouse button for now
if button not in [1, 2]:
return
xpos, ypos = glfw.get_cursor_pos(self.window)
if action == glfw.PRESS:
self.example.mouse_press_event(xpos, ypos, button)
else:
self.example.mouse_release_event(xpos, ypos, button) | [
"def",
"mouse_button_callback",
"(",
"self",
",",
"window",
",",
"button",
",",
"action",
",",
"mods",
")",
":",
"# Offset button index by 1 to make it match the other libraries\r",
"button",
"+=",
"1",
"# Support left and right mouse button for now\r",
"if",
"button",
"not... | Handle mouse button events and forward them to the example | [
"Handle",
"mouse",
"button",
"events",
"and",
"forward",
"them",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/glfw/window.py#L121-L136 |
239,347 | moderngl/moderngl | moderngl/buffer.py | Buffer.write_chunks | def write_chunks(self, data, start, step, count) -> None:
'''
Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets.
'''
self.mglo.write_chunks(data, start, step, count) | python | def write_chunks(self, data, start, step, count) -> None:
'''
Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets.
'''
self.mglo.write_chunks(data, start, step, count) | [
"def",
"write_chunks",
"(",
"self",
",",
"data",
",",
"start",
",",
"step",
",",
"count",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"write_chunks",
"(",
"data",
",",
"start",
",",
"step",
",",
"count",
")"
] | Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets. | [
"Split",
"data",
"to",
"count",
"equal",
"parts",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L72-L85 |
239,348 | moderngl/moderngl | moderngl/buffer.py | Buffer.read_into | def read_into(self, buffer, size=-1, *, offset=0, write_offset=0) -> None:
'''
Read the content into a buffer.
Args:
buffer (bytarray): The buffer that will receive the content.
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The read offset.
write_offset (int): The write offset.
'''
return self.mglo.read_into(buffer, size, offset, write_offset) | python | def read_into(self, buffer, size=-1, *, offset=0, write_offset=0) -> None:
'''
Read the content into a buffer.
Args:
buffer (bytarray): The buffer that will receive the content.
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The read offset.
write_offset (int): The write offset.
'''
return self.mglo.read_into(buffer, size, offset, write_offset) | [
"def",
"read_into",
"(",
"self",
",",
"buffer",
",",
"size",
"=",
"-",
"1",
",",
"*",
",",
"offset",
"=",
"0",
",",
"write_offset",
"=",
"0",
")",
"->",
"None",
":",
"return",
"self",
".",
"mglo",
".",
"read_into",
"(",
"buffer",
",",
"size",
","... | Read the content into a buffer.
Args:
buffer (bytarray): The buffer that will receive the content.
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The read offset.
write_offset (int): The write offset. | [
"Read",
"the",
"content",
"into",
"a",
"buffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L103-L116 |
239,349 | moderngl/moderngl | moderngl/buffer.py | Buffer.clear | def clear(self, size=-1, *, offset=0, chunk=None) -> None:
'''
Clear the content.
Args:
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The offset.
chunk (bytes): The chunk to use repeatedly.
'''
self.mglo.clear(size, offset, chunk) | python | def clear(self, size=-1, *, offset=0, chunk=None) -> None:
'''
Clear the content.
Args:
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The offset.
chunk (bytes): The chunk to use repeatedly.
'''
self.mglo.clear(size, offset, chunk) | [
"def",
"clear",
"(",
"self",
",",
"size",
"=",
"-",
"1",
",",
"*",
",",
"offset",
"=",
"0",
",",
"chunk",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"clear",
"(",
"size",
",",
"offset",
",",
"chunk",
")"
] | Clear the content.
Args:
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The offset.
chunk (bytes): The chunk to use repeatedly. | [
"Clear",
"the",
"content",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L157-L169 |
239,350 | moderngl/moderngl | moderngl/buffer.py | Buffer.bind_to_uniform_block | def bind_to_uniform_block(self, binding=0, *, offset=0, size=-1) -> None:
'''
Bind the buffer to a uniform block.
Args:
binding (int): The uniform block binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all.
'''
self.mglo.bind_to_uniform_block(binding, offset, size) | python | def bind_to_uniform_block(self, binding=0, *, offset=0, size=-1) -> None:
'''
Bind the buffer to a uniform block.
Args:
binding (int): The uniform block binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all.
'''
self.mglo.bind_to_uniform_block(binding, offset, size) | [
"def",
"bind_to_uniform_block",
"(",
"self",
",",
"binding",
"=",
"0",
",",
"*",
",",
"offset",
"=",
"0",
",",
"size",
"=",
"-",
"1",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"bind_to_uniform_block",
"(",
"binding",
",",
"offset",
",",
"size... | Bind the buffer to a uniform block.
Args:
binding (int): The uniform block binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all. | [
"Bind",
"the",
"buffer",
"to",
"a",
"uniform",
"block",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L171-L183 |
239,351 | moderngl/moderngl | moderngl/buffer.py | Buffer.bind_to_storage_buffer | def bind_to_storage_buffer(self, binding=0, *, offset=0, size=-1) -> None:
'''
Bind the buffer to a shader storage buffer.
Args:
binding (int): The shader storage binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all.
'''
self.mglo.bind_to_storage_buffer(binding, offset, size) | python | def bind_to_storage_buffer(self, binding=0, *, offset=0, size=-1) -> None:
'''
Bind the buffer to a shader storage buffer.
Args:
binding (int): The shader storage binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all.
'''
self.mglo.bind_to_storage_buffer(binding, offset, size) | [
"def",
"bind_to_storage_buffer",
"(",
"self",
",",
"binding",
"=",
"0",
",",
"*",
",",
"offset",
"=",
"0",
",",
"size",
"=",
"-",
"1",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"bind_to_storage_buffer",
"(",
"binding",
",",
"offset",
",",
"si... | Bind the buffer to a shader storage buffer.
Args:
binding (int): The shader storage binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all. | [
"Bind",
"the",
"buffer",
"to",
"a",
"shader",
"storage",
"buffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L185-L197 |
239,352 | moderngl/moderngl | examples/window/pyqt5/window.py | Window.swap_buffers | def swap_buffers(self):
"""
Swap buffers, set viewport, trigger events and increment frame counter
"""
self.widget.swapBuffers()
self.set_default_viewport()
self.app.processEvents()
self.frames += 1 | python | def swap_buffers(self):
self.widget.swapBuffers()
self.set_default_viewport()
self.app.processEvents()
self.frames += 1 | [
"def",
"swap_buffers",
"(",
"self",
")",
":",
"self",
".",
"widget",
".",
"swapBuffers",
"(",
")",
"self",
".",
"set_default_viewport",
"(",
")",
"self",
".",
"app",
".",
"processEvents",
"(",
")",
"self",
".",
"frames",
"+=",
"1"
] | Swap buffers, set viewport, trigger events and increment frame counter | [
"Swap",
"buffers",
"set",
"viewport",
"trigger",
"events",
"and",
"increment",
"frame",
"counter"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L100-L107 |
239,353 | moderngl/moderngl | examples/window/pyqt5/window.py | Window.resize | def resize(self, width: int, height: int):
"""
Replacement for Qt's resizeGL method.
"""
self.width = width // self.widget.devicePixelRatio()
self.height = height // self.widget.devicePixelRatio()
self.buffer_width = width
self.buffer_height = height
if self.ctx:
self.set_default_viewport()
# Make sure we notify the example about the resize
super().resize(self.buffer_width, self.buffer_height) | python | def resize(self, width: int, height: int):
self.width = width // self.widget.devicePixelRatio()
self.height = height // self.widget.devicePixelRatio()
self.buffer_width = width
self.buffer_height = height
if self.ctx:
self.set_default_viewport()
# Make sure we notify the example about the resize
super().resize(self.buffer_width, self.buffer_height) | [
"def",
"resize",
"(",
"self",
",",
"width",
":",
"int",
",",
"height",
":",
"int",
")",
":",
"self",
".",
"width",
"=",
"width",
"//",
"self",
".",
"widget",
".",
"devicePixelRatio",
"(",
")",
"self",
".",
"height",
"=",
"height",
"//",
"self",
"."... | Replacement for Qt's resizeGL method. | [
"Replacement",
"for",
"Qt",
"s",
"resizeGL",
"method",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L109-L122 |
239,354 | moderngl/moderngl | examples/window/pyqt5/window.py | Window.key_pressed_event | def key_pressed_event(self, event):
"""
Process Qt key press events forwarding them to the example
"""
if event.key() == self.keys.ESCAPE:
self.close()
self.example.key_event(event.key(), self.keys.ACTION_PRESS) | python | def key_pressed_event(self, event):
if event.key() == self.keys.ESCAPE:
self.close()
self.example.key_event(event.key(), self.keys.ACTION_PRESS) | [
"def",
"key_pressed_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"key",
"(",
")",
"==",
"self",
".",
"keys",
".",
"ESCAPE",
":",
"self",
".",
"close",
"(",
")",
"self",
".",
"example",
".",
"key_event",
"(",
"event",
".",
"key",... | Process Qt key press events forwarding them to the example | [
"Process",
"Qt",
"key",
"press",
"events",
"forwarding",
"them",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L124-L131 |
239,355 | moderngl/moderngl | examples/window/pyqt5/window.py | Window.key_release_event | def key_release_event(self, event):
"""
Process Qt key release events forwarding them to the example
"""
self.example.key_event(event.key(), self.keys.ACTION_RELEASE) | python | def key_release_event(self, event):
self.example.key_event(event.key(), self.keys.ACTION_RELEASE) | [
"def",
"key_release_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"example",
".",
"key_event",
"(",
"event",
".",
"key",
"(",
")",
",",
"self",
".",
"keys",
".",
"ACTION_RELEASE",
")"
] | Process Qt key release events forwarding them to the example | [
"Process",
"Qt",
"key",
"release",
"events",
"forwarding",
"them",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L133-L137 |
239,356 | moderngl/moderngl | examples/window/pyqt5/window.py | Window.mouse_move_event | def mouse_move_event(self, event):
"""
Forward mouse cursor position events to the example
"""
self.example.mouse_position_event(event.x(), event.y()) | python | def mouse_move_event(self, event):
self.example.mouse_position_event(event.x(), event.y()) | [
"def",
"mouse_move_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"example",
".",
"mouse_position_event",
"(",
"event",
".",
"x",
"(",
")",
",",
"event",
".",
"y",
"(",
")",
")"
] | Forward mouse cursor position events to the example | [
"Forward",
"mouse",
"cursor",
"position",
"events",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L139-L143 |
239,357 | moderngl/moderngl | examples/window/pyqt5/window.py | Window.mouse_press_event | def mouse_press_event(self, event):
"""
Forward mouse press events to the example
"""
# Support left and right mouse button for now
if event.button() not in [1, 2]:
return
self.example.mouse_press_event(event.x(), event.y(), event.button()) | python | def mouse_press_event(self, event):
# Support left and right mouse button for now
if event.button() not in [1, 2]:
return
self.example.mouse_press_event(event.x(), event.y(), event.button()) | [
"def",
"mouse_press_event",
"(",
"self",
",",
"event",
")",
":",
"# Support left and right mouse button for now\r",
"if",
"event",
".",
"button",
"(",
")",
"not",
"in",
"[",
"1",
",",
"2",
"]",
":",
"return",
"self",
".",
"example",
".",
"mouse_press_event",
... | Forward mouse press events to the example | [
"Forward",
"mouse",
"press",
"events",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L145-L153 |
239,358 | moderngl/moderngl | examples/window/pyqt5/window.py | Window.mouse_release_event | def mouse_release_event(self, event):
"""
Forward mouse release events to the example
"""
# Support left and right mouse button for now
if event.button() not in [1, 2]:
return
self.example.mouse_release_event(event.x(), event.y(), event.button()) | python | def mouse_release_event(self, event):
# Support left and right mouse button for now
if event.button() not in [1, 2]:
return
self.example.mouse_release_event(event.x(), event.y(), event.button()) | [
"def",
"mouse_release_event",
"(",
"self",
",",
"event",
")",
":",
"# Support left and right mouse button for now\r",
"if",
"event",
".",
"button",
"(",
")",
"not",
"in",
"[",
"1",
",",
"2",
"]",
":",
"return",
"self",
".",
"example",
".",
"mouse_release_event... | Forward mouse release events to the example | [
"Forward",
"mouse",
"release",
"events",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L155-L163 |
239,359 | moderngl/moderngl | moderngl/framebuffer.py | Framebuffer.read | def read(self, viewport=None, components=3, *, attachment=0, alignment=1, dtype='f1') -> bytes:
'''
Read the content of the framebuffer.
Args:
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
Returns:
bytes
'''
return self.mglo.read(viewport, components, attachment, alignment, dtype) | python | def read(self, viewport=None, components=3, *, attachment=0, alignment=1, dtype='f1') -> bytes:
'''
Read the content of the framebuffer.
Args:
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
Returns:
bytes
'''
return self.mglo.read(viewport, components, attachment, alignment, dtype) | [
"def",
"read",
"(",
"self",
",",
"viewport",
"=",
"None",
",",
"components",
"=",
"3",
",",
"*",
",",
"attachment",
"=",
"0",
",",
"alignment",
"=",
"1",
",",
"dtype",
"=",
"'f1'",
")",
"->",
"bytes",
":",
"return",
"self",
".",
"mglo",
".",
"rea... | Read the content of the framebuffer.
Args:
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
Returns:
bytes | [
"Read",
"the",
"content",
"of",
"the",
"framebuffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/framebuffer.py#L174-L191 |
239,360 | moderngl/moderngl | moderngl/framebuffer.py | Framebuffer.read_into | def read_into(self, buffer, viewport=None, components=3, *,
attachment=0, alignment=1, dtype='f1', write_offset=0) -> None:
'''
Read the content of the framebuffer into a buffer.
Args:
buffer (bytearray): The buffer that will receive the pixels.
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
write_offset (int): The write offset.
'''
if type(buffer) is Buffer:
buffer = buffer.mglo
return self.mglo.read_into(buffer, viewport, components, attachment, alignment, dtype, write_offset) | python | def read_into(self, buffer, viewport=None, components=3, *,
attachment=0, alignment=1, dtype='f1', write_offset=0) -> None:
'''
Read the content of the framebuffer into a buffer.
Args:
buffer (bytearray): The buffer that will receive the pixels.
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
write_offset (int): The write offset.
'''
if type(buffer) is Buffer:
buffer = buffer.mglo
return self.mglo.read_into(buffer, viewport, components, attachment, alignment, dtype, write_offset) | [
"def",
"read_into",
"(",
"self",
",",
"buffer",
",",
"viewport",
"=",
"None",
",",
"components",
"=",
"3",
",",
"*",
",",
"attachment",
"=",
"0",
",",
"alignment",
"=",
"1",
",",
"dtype",
"=",
"'f1'",
",",
"write_offset",
"=",
"0",
")",
"->",
"None... | Read the content of the framebuffer into a buffer.
Args:
buffer (bytearray): The buffer that will receive the pixels.
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
write_offset (int): The write offset. | [
"Read",
"the",
"content",
"of",
"the",
"framebuffer",
"into",
"a",
"buffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/framebuffer.py#L193-L213 |
239,361 | moderngl/moderngl | examples/window/base.py | BaseWindow.resize | def resize(self, width, height):
"""
Should be called every time window is resized
so the example can adapt to the new size if needed
"""
if self.example:
self.example.resize(width, height) | python | def resize(self, width, height):
if self.example:
self.example.resize(width, height) | [
"def",
"resize",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"if",
"self",
".",
"example",
":",
"self",
".",
"example",
".",
"resize",
"(",
"width",
",",
"height",
")"
] | Should be called every time window is resized
so the example can adapt to the new size if needed | [
"Should",
"be",
"called",
"every",
"time",
"window",
"is",
"resized",
"so",
"the",
"example",
"can",
"adapt",
"to",
"the",
"new",
"size",
"if",
"needed"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/base.py#L136-L142 |
239,362 | moderngl/moderngl | examples/window/base.py | BaseWindow.set_default_viewport | def set_default_viewport(self):
"""
Calculates the viewport based on the configured aspect ratio.
Will add black borders and center the viewport if the window
do not match the configured viewport.
If aspect ratio is None the viewport will be scaled
to the entire window size regardless of size.
"""
if self.aspect_ratio:
expected_width = int(self.buffer_height * self.aspect_ratio)
expected_height = int(expected_width / self.aspect_ratio)
if expected_width > self.buffer_width:
expected_width = self.buffer_width
expected_height = int(expected_width / self.aspect_ratio)
blank_space_x = self.buffer_width - expected_width
blank_space_y = self.buffer_height - expected_height
self.ctx.viewport = (
blank_space_x // 2,
blank_space_y // 2,
expected_width,
expected_height,
)
else:
self.ctx.viewport = (0, 0, self.buffer_width, self.buffer_height) | python | def set_default_viewport(self):
if self.aspect_ratio:
expected_width = int(self.buffer_height * self.aspect_ratio)
expected_height = int(expected_width / self.aspect_ratio)
if expected_width > self.buffer_width:
expected_width = self.buffer_width
expected_height = int(expected_width / self.aspect_ratio)
blank_space_x = self.buffer_width - expected_width
blank_space_y = self.buffer_height - expected_height
self.ctx.viewport = (
blank_space_x // 2,
blank_space_y // 2,
expected_width,
expected_height,
)
else:
self.ctx.viewport = (0, 0, self.buffer_width, self.buffer_height) | [
"def",
"set_default_viewport",
"(",
"self",
")",
":",
"if",
"self",
".",
"aspect_ratio",
":",
"expected_width",
"=",
"int",
"(",
"self",
".",
"buffer_height",
"*",
"self",
".",
"aspect_ratio",
")",
"expected_height",
"=",
"int",
"(",
"expected_width",
"/",
"... | Calculates the viewport based on the configured aspect ratio.
Will add black borders and center the viewport if the window
do not match the configured viewport.
If aspect ratio is None the viewport will be scaled
to the entire window size regardless of size. | [
"Calculates",
"the",
"viewport",
"based",
"on",
"the",
"configured",
"aspect",
"ratio",
".",
"Will",
"add",
"black",
"borders",
"and",
"center",
"the",
"viewport",
"if",
"the",
"window",
"do",
"not",
"match",
"the",
"configured",
"viewport",
".",
"If",
"aspe... | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/base.py#L150-L177 |
239,363 | moderngl/moderngl | examples/window/base.py | BaseWindow.print_context_info | def print_context_info(self):
"""
Prints moderngl context info.
"""
print("Context Version:")
print('ModernGL:', moderngl.__version__)
print('vendor:', self.ctx.info['GL_VENDOR'])
print('renderer:', self.ctx.info['GL_RENDERER'])
print('version:', self.ctx.info['GL_VERSION'])
print('python:', sys.version)
print('platform:', sys.platform)
print('code:', self.ctx.version_code) | python | def print_context_info(self):
print("Context Version:")
print('ModernGL:', moderngl.__version__)
print('vendor:', self.ctx.info['GL_VENDOR'])
print('renderer:', self.ctx.info['GL_RENDERER'])
print('version:', self.ctx.info['GL_VERSION'])
print('python:', sys.version)
print('platform:', sys.platform)
print('code:', self.ctx.version_code) | [
"def",
"print_context_info",
"(",
"self",
")",
":",
"print",
"(",
"\"Context Version:\"",
")",
"print",
"(",
"'ModernGL:'",
",",
"moderngl",
".",
"__version__",
")",
"print",
"(",
"'vendor:'",
",",
"self",
".",
"ctx",
".",
"info",
"[",
"'GL_VENDOR'",
"]",
... | Prints moderngl context info. | [
"Prints",
"moderngl",
"context",
"info",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/base.py#L187-L198 |
239,364 | moderngl/moderngl | moderngl/texture.py | Texture.read | def read(self, *, level=0, alignment=1) -> bytes:
'''
Read the content of the texture into a buffer.
Keyword Args:
level (int): The mipmap level.
alignment (int): The byte alignment of the pixels.
Returns:
bytes
'''
return self.mglo.read(level, alignment) | python | def read(self, *, level=0, alignment=1) -> bytes:
'''
Read the content of the texture into a buffer.
Keyword Args:
level (int): The mipmap level.
alignment (int): The byte alignment of the pixels.
Returns:
bytes
'''
return self.mglo.read(level, alignment) | [
"def",
"read",
"(",
"self",
",",
"*",
",",
"level",
"=",
"0",
",",
"alignment",
"=",
"1",
")",
"->",
"bytes",
":",
"return",
"self",
".",
"mglo",
".",
"read",
"(",
"level",
",",
"alignment",
")"
] | Read the content of the texture into a buffer.
Keyword Args:
level (int): The mipmap level.
alignment (int): The byte alignment of the pixels.
Returns:
bytes | [
"Read",
"the",
"content",
"of",
"the",
"texture",
"into",
"a",
"buffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/texture.py#L270-L282 |
239,365 | moderngl/moderngl | examples/window/__init__.py | parse_args | def parse_args(args=None):
"""Parse arguments from sys.argv"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-w', '--window',
default="pyqt5",
choices=find_window_classes(),
help='Name for the window type to use',
)
parser.add_argument(
'-fs', '--fullscreen',
action="store_true",
help='Open the window in fullscreen mode',
)
parser.add_argument(
'-vs', '--vsync',
type=str2bool,
default="1",
help="Enable or disable vsync",
)
parser.add_argument(
'-s', '--samples',
type=int,
default=4,
help="Specify the desired number of samples to use for multisampling",
)
parser.add_argument(
'-c', '--cursor',
type=str2bool,
default="true",
help="Enable or disable displaying the mouse cursor",
)
return parser.parse_args(args or sys.argv[1:]) | python | def parse_args(args=None):
parser = argparse.ArgumentParser()
parser.add_argument(
'-w', '--window',
default="pyqt5",
choices=find_window_classes(),
help='Name for the window type to use',
)
parser.add_argument(
'-fs', '--fullscreen',
action="store_true",
help='Open the window in fullscreen mode',
)
parser.add_argument(
'-vs', '--vsync',
type=str2bool,
default="1",
help="Enable or disable vsync",
)
parser.add_argument(
'-s', '--samples',
type=int,
default=4,
help="Specify the desired number of samples to use for multisampling",
)
parser.add_argument(
'-c', '--cursor',
type=str2bool,
default="true",
help="Enable or disable displaying the mouse cursor",
)
return parser.parse_args(args or sys.argv[1:]) | [
"def",
"parse_args",
"(",
"args",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-w'",
",",
"'--window'",
",",
"default",
"=",
"\"pyqt5\"",
",",
"choices",
"=",
"find_window_classes",
... | Parse arguments from sys.argv | [
"Parse",
"arguments",
"from",
"sys",
".",
"argv"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/__init__.py#L65-L99 |
239,366 | moderngl/moderngl | moderngl/compute_shader.py | ComputeShader.run | def run(self, group_x=1, group_y=1, group_z=1) -> None:
'''
Run the compute shader.
Args:
group_x (int): The number of work groups to be launched in the X dimension.
group_y (int): The number of work groups to be launched in the Y dimension.
group_z (int): The number of work groups to be launched in the Z dimension.
'''
return self.mglo.run(group_x, group_y, group_z) | python | def run(self, group_x=1, group_y=1, group_z=1) -> None:
'''
Run the compute shader.
Args:
group_x (int): The number of work groups to be launched in the X dimension.
group_y (int): The number of work groups to be launched in the Y dimension.
group_z (int): The number of work groups to be launched in the Z dimension.
'''
return self.mglo.run(group_x, group_y, group_z) | [
"def",
"run",
"(",
"self",
",",
"group_x",
"=",
"1",
",",
"group_y",
"=",
"1",
",",
"group_z",
"=",
"1",
")",
"->",
"None",
":",
"return",
"self",
".",
"mglo",
".",
"run",
"(",
"group_x",
",",
"group_y",
",",
"group_z",
")"
] | Run the compute shader.
Args:
group_x (int): The number of work groups to be launched in the X dimension.
group_y (int): The number of work groups to be launched in the Y dimension.
group_z (int): The number of work groups to be launched in the Z dimension. | [
"Run",
"the",
"compute",
"shader",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/compute_shader.py#L54-L64 |
239,367 | moderngl/moderngl | moderngl/compute_shader.py | ComputeShader.get | def get(self, key, default) -> Union[Uniform, UniformBlock, Subroutine, Attribute, Varying]:
'''
Returns a Uniform, UniformBlock, Subroutine, Attribute or Varying.
Args:
default: This is the value to be returned in case key does not exist.
Returns:
:py:class:`Uniform`, :py:class:`UniformBlock`, :py:class:`Subroutine`,
:py:class:`Attribute` or :py:class:`Varying`
'''
return self._members.get(key, default) | python | def get(self, key, default) -> Union[Uniform, UniformBlock, Subroutine, Attribute, Varying]:
'''
Returns a Uniform, UniformBlock, Subroutine, Attribute or Varying.
Args:
default: This is the value to be returned in case key does not exist.
Returns:
:py:class:`Uniform`, :py:class:`UniformBlock`, :py:class:`Subroutine`,
:py:class:`Attribute` or :py:class:`Varying`
'''
return self._members.get(key, default) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
")",
"->",
"Union",
"[",
"Uniform",
",",
"UniformBlock",
",",
"Subroutine",
",",
"Attribute",
",",
"Varying",
"]",
":",
"return",
"self",
".",
"_members",
".",
"get",
"(",
"key",
",",
"default",
... | Returns a Uniform, UniformBlock, Subroutine, Attribute or Varying.
Args:
default: This is the value to be returned in case key does not exist.
Returns:
:py:class:`Uniform`, :py:class:`UniformBlock`, :py:class:`Subroutine`,
:py:class:`Attribute` or :py:class:`Varying` | [
"Returns",
"a",
"Uniform",
"UniformBlock",
"Subroutine",
"Attribute",
"or",
"Varying",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/compute_shader.py#L66-L78 |
239,368 | moderngl/moderngl | examples/window/sdl2/window.py | Window.resize | def resize(self, width, height):
"""
Sets the new size and buffer size internally
"""
self.width = width
self.height = height
self.buffer_width, self.buffer_height = self.width, self.height
self.set_default_viewport()
super().resize(self.buffer_width, self.buffer_height) | python | def resize(self, width, height):
self.width = width
self.height = height
self.buffer_width, self.buffer_height = self.width, self.height
self.set_default_viewport()
super().resize(self.buffer_width, self.buffer_height) | [
"def",
"resize",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"self",
".",
"width",
"=",
"width",
"self",
".",
"height",
"=",
"height",
"self",
".",
"buffer_width",
",",
"self",
".",
"buffer_height",
"=",
"self",
".",
"width",
",",
"self",
"."... | Sets the new size and buffer size internally | [
"Sets",
"the",
"new",
"size",
"and",
"buffer",
"size",
"internally"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/sdl2/window.py#L76-L85 |
239,369 | moderngl/moderngl | examples/window/sdl2/window.py | Window.process_events | def process_events(self):
"""
Loop through and handle all the queued events.
"""
for event in sdl2.ext.get_events():
if event.type == sdl2.SDL_MOUSEMOTION:
self.example.mouse_position_event(event.motion.x, event.motion.y)
elif event.type == sdl2.SDL_MOUSEBUTTONUP:
# Support left and right mouse button for now
if event.button.button in [1, 3]:
self.example.mouse_press_event(
event.motion.x, event.motion.y,
1 if event.button.button == 1 else 2,
)
elif event.type == sdl2.SDL_MOUSEBUTTONDOWN:
# Support left and right mouse button for now
if event.button.button in [1, 3]:
self.example.mouse_release_event(
event.motion.x, event.motion.y,
1 if event.button.button == 1 else 2,
)
elif event.type in [sdl2.SDL_KEYDOWN, sdl2.SDL_KEYUP]:
if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
self.close()
self.example.key_event(event.key.keysym.sym, event.type)
elif event.type == sdl2.SDL_QUIT:
self.close()
elif event.type == sdl2.SDL_WINDOWEVENT:
if event.window.event == sdl2.SDL_WINDOWEVENT_RESIZED:
self.resize(event.window.data1, event.window.data2) | python | def process_events(self):
for event in sdl2.ext.get_events():
if event.type == sdl2.SDL_MOUSEMOTION:
self.example.mouse_position_event(event.motion.x, event.motion.y)
elif event.type == sdl2.SDL_MOUSEBUTTONUP:
# Support left and right mouse button for now
if event.button.button in [1, 3]:
self.example.mouse_press_event(
event.motion.x, event.motion.y,
1 if event.button.button == 1 else 2,
)
elif event.type == sdl2.SDL_MOUSEBUTTONDOWN:
# Support left and right mouse button for now
if event.button.button in [1, 3]:
self.example.mouse_release_event(
event.motion.x, event.motion.y,
1 if event.button.button == 1 else 2,
)
elif event.type in [sdl2.SDL_KEYDOWN, sdl2.SDL_KEYUP]:
if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
self.close()
self.example.key_event(event.key.keysym.sym, event.type)
elif event.type == sdl2.SDL_QUIT:
self.close()
elif event.type == sdl2.SDL_WINDOWEVENT:
if event.window.event == sdl2.SDL_WINDOWEVENT_RESIZED:
self.resize(event.window.data1, event.window.data2) | [
"def",
"process_events",
"(",
"self",
")",
":",
"for",
"event",
"in",
"sdl2",
".",
"ext",
".",
"get_events",
"(",
")",
":",
"if",
"event",
".",
"type",
"==",
"sdl2",
".",
"SDL_MOUSEMOTION",
":",
"self",
".",
"example",
".",
"mouse_position_event",
"(",
... | Loop through and handle all the queued events. | [
"Loop",
"through",
"and",
"handle",
"all",
"the",
"queued",
"events",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/sdl2/window.py#L87-L122 |
239,370 | moderngl/moderngl | examples/window/sdl2/window.py | Window.destroy | def destroy(self):
"""
Gracefully close the window
"""
sdl2.SDL_GL_DeleteContext(self.context)
sdl2.SDL_DestroyWindow(self.window)
sdl2.SDL_Quit() | python | def destroy(self):
sdl2.SDL_GL_DeleteContext(self.context)
sdl2.SDL_DestroyWindow(self.window)
sdl2.SDL_Quit() | [
"def",
"destroy",
"(",
"self",
")",
":",
"sdl2",
".",
"SDL_GL_DeleteContext",
"(",
"self",
".",
"context",
")",
"sdl2",
".",
"SDL_DestroyWindow",
"(",
"self",
".",
"window",
")",
"sdl2",
".",
"SDL_Quit",
"(",
")"
] | Gracefully close the window | [
"Gracefully",
"close",
"the",
"window"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/sdl2/window.py#L124-L130 |
239,371 | moderngl/moderngl | examples/window/pyglet/window.py | Window.on_key_press | def on_key_press(self, symbol, modifiers):
"""
Pyglet specific key press callback.
Forwards and translates the events to the example
"""
self.example.key_event(symbol, self.keys.ACTION_PRESS) | python | def on_key_press(self, symbol, modifiers):
self.example.key_event(symbol, self.keys.ACTION_PRESS) | [
"def",
"on_key_press",
"(",
"self",
",",
"symbol",
",",
"modifiers",
")",
":",
"self",
".",
"example",
".",
"key_event",
"(",
"symbol",
",",
"self",
".",
"keys",
".",
"ACTION_PRESS",
")"
] | Pyglet specific key press callback.
Forwards and translates the events to the example | [
"Pyglet",
"specific",
"key",
"press",
"callback",
".",
"Forwards",
"and",
"translates",
"the",
"events",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyglet/window.py#L96-L101 |
239,372 | moderngl/moderngl | examples/window/pyglet/window.py | Window.on_key_release | def on_key_release(self, symbol, modifiers):
"""
Pyglet specific key release callback.
Forwards and translates the events to the example
"""
self.example.key_event(symbol, self.keys.ACTION_RELEASE) | python | def on_key_release(self, symbol, modifiers):
self.example.key_event(symbol, self.keys.ACTION_RELEASE) | [
"def",
"on_key_release",
"(",
"self",
",",
"symbol",
",",
"modifiers",
")",
":",
"self",
".",
"example",
".",
"key_event",
"(",
"symbol",
",",
"self",
".",
"keys",
".",
"ACTION_RELEASE",
")"
] | Pyglet specific key release callback.
Forwards and translates the events to the example | [
"Pyglet",
"specific",
"key",
"release",
"callback",
".",
"Forwards",
"and",
"translates",
"the",
"events",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyglet/window.py#L103-L108 |
239,373 | moderngl/moderngl | examples/window/pyglet/window.py | Window.on_mouse_motion | def on_mouse_motion(self, x, y, dx, dy):
"""
Pyglet specific mouse motion callback.
Forwards and traslates the event to the example
"""
# Screen coordinates relative to the lower-left corner
# so we have to flip the y axis to make this consistent with
# other window libraries
self.example.mouse_position_event(x, self.buffer_height - y) | python | def on_mouse_motion(self, x, y, dx, dy):
# Screen coordinates relative to the lower-left corner
# so we have to flip the y axis to make this consistent with
# other window libraries
self.example.mouse_position_event(x, self.buffer_height - y) | [
"def",
"on_mouse_motion",
"(",
"self",
",",
"x",
",",
"y",
",",
"dx",
",",
"dy",
")",
":",
"# Screen coordinates relative to the lower-left corner\r",
"# so we have to flip the y axis to make this consistent with\r",
"# other window libraries\r",
"self",
".",
"example",
".",
... | Pyglet specific mouse motion callback.
Forwards and traslates the event to the example | [
"Pyglet",
"specific",
"mouse",
"motion",
"callback",
".",
"Forwards",
"and",
"traslates",
"the",
"event",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyglet/window.py#L110-L118 |
239,374 | moderngl/moderngl | examples/window/pyglet/window.py | Window.on_mouse_press | def on_mouse_press(self, x: int, y: int, button, mods):
"""
Handle mouse press events and forward to example window
"""
if button in [1, 4]:
self.example.mouse_press_event(
x, self.buffer_height - y,
1 if button == 1 else 2,
) | python | def on_mouse_press(self, x: int, y: int, button, mods):
if button in [1, 4]:
self.example.mouse_press_event(
x, self.buffer_height - y,
1 if button == 1 else 2,
) | [
"def",
"on_mouse_press",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"button",
",",
"mods",
")",
":",
"if",
"button",
"in",
"[",
"1",
",",
"4",
"]",
":",
"self",
".",
"example",
".",
"mouse_press_event",
"(",
"x",
",",
"self",
... | Handle mouse press events and forward to example window | [
"Handle",
"mouse",
"press",
"events",
"and",
"forward",
"to",
"example",
"window"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyglet/window.py#L120-L128 |
239,375 | moderngl/moderngl | examples/window/pyglet/window.py | Window.on_mouse_release | def on_mouse_release(self, x: int, y: int, button, mods):
"""
Handle mouse release events and forward to example window
"""
if button in [1, 4]:
self.example.mouse_release_event(
x, self.buffer_height - y,
1 if button == 1 else 2,
) | python | def on_mouse_release(self, x: int, y: int, button, mods):
if button in [1, 4]:
self.example.mouse_release_event(
x, self.buffer_height - y,
1 if button == 1 else 2,
) | [
"def",
"on_mouse_release",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"button",
",",
"mods",
")",
":",
"if",
"button",
"in",
"[",
"1",
",",
"4",
"]",
":",
"self",
".",
"example",
".",
"mouse_release_event",
"(",
"x",
",",
"self... | Handle mouse release events and forward to example window | [
"Handle",
"mouse",
"release",
"events",
"and",
"forward",
"to",
"example",
"window"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyglet/window.py#L130-L138 |
239,376 | moderngl/moderngl | moderngl/texture_cube.py | TextureCube.write | def write(self, face, data, viewport=None, *, alignment=1) -> None:
'''
Update the content of the texture.
Args:
face (int): The face to update.
data (bytes): The pixel data.
viewport (tuple): The viewport.
Keyword Args:
alignment (int): The byte alignment of the pixels.
'''
if type(data) is Buffer:
data = data.mglo
self.mglo.write(face, data, viewport, alignment) | python | def write(self, face, data, viewport=None, *, alignment=1) -> None:
'''
Update the content of the texture.
Args:
face (int): The face to update.
data (bytes): The pixel data.
viewport (tuple): The viewport.
Keyword Args:
alignment (int): The byte alignment of the pixels.
'''
if type(data) is Buffer:
data = data.mglo
self.mglo.write(face, data, viewport, alignment) | [
"def",
"write",
"(",
"self",
",",
"face",
",",
"data",
",",
"viewport",
"=",
"None",
",",
"*",
",",
"alignment",
"=",
"1",
")",
"->",
"None",
":",
"if",
"type",
"(",
"data",
")",
"is",
"Buffer",
":",
"data",
"=",
"data",
".",
"mglo",
"self",
".... | Update the content of the texture.
Args:
face (int): The face to update.
data (bytes): The pixel data.
viewport (tuple): The viewport.
Keyword Args:
alignment (int): The byte alignment of the pixels. | [
"Update",
"the",
"content",
"of",
"the",
"texture",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/texture_cube.py#L170-L186 |
239,377 | moderngl/moderngl | examples/00_empty_window.py | EmptyWindow.key_event | def key_event(self, key, action):
"""
Handle key events in a generic way
supporting all window types.
"""
if action == self.wnd.keys.ACTION_PRESS:
if key == self.wnd.keys.SPACE:
print("Space was pressed")
if action == self.wnd.keys.ACTION_RELEASE:
if key == self.wnd.keys.SPACE:
print("Space was released") | python | def key_event(self, key, action):
if action == self.wnd.keys.ACTION_PRESS:
if key == self.wnd.keys.SPACE:
print("Space was pressed")
if action == self.wnd.keys.ACTION_RELEASE:
if key == self.wnd.keys.SPACE:
print("Space was released") | [
"def",
"key_event",
"(",
"self",
",",
"key",
",",
"action",
")",
":",
"if",
"action",
"==",
"self",
".",
"wnd",
".",
"keys",
".",
"ACTION_PRESS",
":",
"if",
"key",
"==",
"self",
".",
"wnd",
".",
"keys",
".",
"SPACE",
":",
"print",
"(",
"\"Space was... | Handle key events in a generic way
supporting all window types. | [
"Handle",
"key",
"events",
"in",
"a",
"generic",
"way",
"supporting",
"all",
"window",
"types",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/00_empty_window.py#L24-L35 |
239,378 | moderngl/moderngl | examples/00_empty_window.py | EmptyWindow.mouse_press_event | def mouse_press_event(self, x, y, button):
"""Reports left and right mouse button presses + position"""
if button == 1:
print("Left mouse button pressed @", x, y)
if button == 2:
print("Right mouse button pressed @", x, y) | python | def mouse_press_event(self, x, y, button):
if button == 1:
print("Left mouse button pressed @", x, y)
if button == 2:
print("Right mouse button pressed @", x, y) | [
"def",
"mouse_press_event",
"(",
"self",
",",
"x",
",",
"y",
",",
"button",
")",
":",
"if",
"button",
"==",
"1",
":",
"print",
"(",
"\"Left mouse button pressed @\"",
",",
"x",
",",
"y",
")",
"if",
"button",
"==",
"2",
":",
"print",
"(",
"\"Right mouse... | Reports left and right mouse button presses + position | [
"Reports",
"left",
"and",
"right",
"mouse",
"button",
"presses",
"+",
"position"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/00_empty_window.py#L44-L49 |
239,379 | moderngl/moderngl | examples/00_empty_window.py | EmptyWindow.mouse_release_event | def mouse_release_event(self, x, y, button):
"""Reports left and right mouse button releases + position"""
if button == 1:
print("Left mouse button released @", x, y)
if button == 2:
print("Right mouse button released @", x, y) | python | def mouse_release_event(self, x, y, button):
if button == 1:
print("Left mouse button released @", x, y)
if button == 2:
print("Right mouse button released @", x, y) | [
"def",
"mouse_release_event",
"(",
"self",
",",
"x",
",",
"y",
",",
"button",
")",
":",
"if",
"button",
"==",
"1",
":",
"print",
"(",
"\"Left mouse button released @\"",
",",
"x",
",",
"y",
")",
"if",
"button",
"==",
"2",
":",
"print",
"(",
"\"Right mo... | Reports left and right mouse button releases + position | [
"Reports",
"left",
"and",
"right",
"mouse",
"button",
"releases",
"+",
"position"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/00_empty_window.py#L51-L56 |
239,380 | moderngl/moderngl | moderngl/program.py | detect_format | def detect_format(program, attributes) -> str:
'''
Detect format for vertex attributes.
The format returned does not contain padding.
Args:
program (Program): The program.
attributes (list): A list of attribute names.
Returns:
str
'''
def fmt(attr):
'''
For internal use only.
'''
return attr.array_length * attr.dimension, attr.shape
return ' '.join('%d%s' % fmt(program[a]) for a in attributes) | python | def detect_format(program, attributes) -> str:
'''
Detect format for vertex attributes.
The format returned does not contain padding.
Args:
program (Program): The program.
attributes (list): A list of attribute names.
Returns:
str
'''
def fmt(attr):
'''
For internal use only.
'''
return attr.array_length * attr.dimension, attr.shape
return ' '.join('%d%s' % fmt(program[a]) for a in attributes) | [
"def",
"detect_format",
"(",
"program",
",",
"attributes",
")",
"->",
"str",
":",
"def",
"fmt",
"(",
"attr",
")",
":",
"'''\n For internal use only.\n '''",
"return",
"attr",
".",
"array_length",
"*",
"attr",
".",
"dimension",
",",
"attr",
".",... | Detect format for vertex attributes.
The format returned does not contain padding.
Args:
program (Program): The program.
attributes (list): A list of attribute names.
Returns:
str | [
"Detect",
"format",
"for",
"vertex",
"attributes",
".",
"The",
"format",
"returned",
"does",
"not",
"contain",
"padding",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/program.py#L115-L135 |
239,381 | dswah/pyGAM | pygam/callbacks.py | validate_callback_data | def validate_callback_data(method):
"""
wraps a callback's method to pull the desired arguments from the vars dict
also checks to ensure the method's arguments are in the vars dict
Parameters
----------
method : callable
Returns
-------
validated callable
"""
@wraps(method)
def method_wrapper(*args, **kwargs):
"""
Parameters
----------
*args
**kwargs
Returns
-------
method's output
"""
expected = method.__code__.co_varnames
# rename curret gam object
if 'self' in kwargs:
gam = kwargs['self']
del(kwargs['self'])
kwargs['gam'] = gam
# loop once to check any missing
missing = []
for e in expected:
if e == 'self':
continue
if e not in kwargs:
missing.append(e)
assert len(missing) == 0, 'CallBack cannot reference: {}'.\
format(', '.join(missing))
# loop again to extract desired
kwargs_subset = {}
for e in expected:
if e == 'self':
continue
kwargs_subset[e] = kwargs[e]
return method(*args, **kwargs_subset)
return method_wrapper | python | def validate_callback_data(method):
@wraps(method)
def method_wrapper(*args, **kwargs):
"""
Parameters
----------
*args
**kwargs
Returns
-------
method's output
"""
expected = method.__code__.co_varnames
# rename curret gam object
if 'self' in kwargs:
gam = kwargs['self']
del(kwargs['self'])
kwargs['gam'] = gam
# loop once to check any missing
missing = []
for e in expected:
if e == 'self':
continue
if e not in kwargs:
missing.append(e)
assert len(missing) == 0, 'CallBack cannot reference: {}'.\
format(', '.join(missing))
# loop again to extract desired
kwargs_subset = {}
for e in expected:
if e == 'self':
continue
kwargs_subset[e] = kwargs[e]
return method(*args, **kwargs_subset)
return method_wrapper | [
"def",
"validate_callback_data",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"method_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n\n Parameters\n ----------\n *args\n **kwargs\n\n Returns\... | wraps a callback's method to pull the desired arguments from the vars dict
also checks to ensure the method's arguments are in the vars dict
Parameters
----------
method : callable
Returns
-------
validated callable | [
"wraps",
"a",
"callback",
"s",
"method",
"to",
"pull",
"the",
"desired",
"arguments",
"from",
"the",
"vars",
"dict",
"also",
"checks",
"to",
"ensure",
"the",
"method",
"s",
"arguments",
"are",
"in",
"the",
"vars",
"dict"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/callbacks.py#L13-L66 |
239,382 | dswah/pyGAM | pygam/callbacks.py | validate_callback | def validate_callback(callback):
"""
validates a callback's on_loop_start and on_loop_end methods
Parameters
----------
callback : Callback object
Returns
-------
validated callback
"""
if not(hasattr(callback, '_validated')) or callback._validated == False:
assert hasattr(callback, 'on_loop_start') \
or hasattr(callback, 'on_loop_end'), \
'callback must have `on_loop_start` or `on_loop_end` method'
if hasattr(callback, 'on_loop_start'):
setattr(callback, 'on_loop_start',
validate_callback_data(callback.on_loop_start))
if hasattr(callback, 'on_loop_end'):
setattr(callback, 'on_loop_end',
validate_callback_data(callback.on_loop_end))
setattr(callback, '_validated', True)
return callback | python | def validate_callback(callback):
if not(hasattr(callback, '_validated')) or callback._validated == False:
assert hasattr(callback, 'on_loop_start') \
or hasattr(callback, 'on_loop_end'), \
'callback must have `on_loop_start` or `on_loop_end` method'
if hasattr(callback, 'on_loop_start'):
setattr(callback, 'on_loop_start',
validate_callback_data(callback.on_loop_start))
if hasattr(callback, 'on_loop_end'):
setattr(callback, 'on_loop_end',
validate_callback_data(callback.on_loop_end))
setattr(callback, '_validated', True)
return callback | [
"def",
"validate_callback",
"(",
"callback",
")",
":",
"if",
"not",
"(",
"hasattr",
"(",
"callback",
",",
"'_validated'",
")",
")",
"or",
"callback",
".",
"_validated",
"==",
"False",
":",
"assert",
"hasattr",
"(",
"callback",
",",
"'on_loop_start'",
")",
... | validates a callback's on_loop_start and on_loop_end methods
Parameters
----------
callback : Callback object
Returns
-------
validated callback | [
"validates",
"a",
"callback",
"s",
"on_loop_start",
"and",
"on_loop_end",
"methods"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/callbacks.py#L68-L91 |
239,383 | dswah/pyGAM | pygam/distributions.py | Distribution.phi | def phi(self, y, mu, edof, weights):
"""
GLM scale parameter.
for Binomial and Poisson families this is unity
for Normal family this is variance
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
edof : float
estimated degrees of freedom
weights : array-like shape (n,) or None, default: None
sample weights
if None, defaults to array of ones
Returns
-------
scale : estimated model scale
"""
if self._known_scale:
return self.scale
else:
return (np.sum(weights * self.V(mu)**-1 * (y - mu)**2) /
(len(mu) - edof)) | python | def phi(self, y, mu, edof, weights):
if self._known_scale:
return self.scale
else:
return (np.sum(weights * self.V(mu)**-1 * (y - mu)**2) /
(len(mu) - edof)) | [
"def",
"phi",
"(",
"self",
",",
"y",
",",
"mu",
",",
"edof",
",",
"weights",
")",
":",
"if",
"self",
".",
"_known_scale",
":",
"return",
"self",
".",
"scale",
"else",
":",
"return",
"(",
"np",
".",
"sum",
"(",
"weights",
"*",
"self",
".",
"V",
... | GLM scale parameter.
for Binomial and Poisson families this is unity
for Normal family this is variance
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
edof : float
estimated degrees of freedom
weights : array-like shape (n,) or None, default: None
sample weights
if None, defaults to array of ones
Returns
-------
scale : estimated model scale | [
"GLM",
"scale",
"parameter",
".",
"for",
"Binomial",
"and",
"Poisson",
"families",
"this",
"is",
"unity",
"for",
"Normal",
"family",
"this",
"is",
"variance"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/distributions.py#L61-L87 |
239,384 | dswah/pyGAM | pygam/distributions.py | GammaDist.sample | def sample(self, mu):
"""
Return random samples from this Gamma distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.array of same shape as mu
"""
# in numpy.random.gamma, `shape` is the parameter sometimes denoted by
# `k` that corresponds to `nu` in S. Wood (2006) Table 2.1
shape = 1. / self.scale
# in numpy.random.gamma, `scale` is the parameter sometimes denoted by
# `theta` that corresponds to mu / nu in S. Wood (2006) Table 2.1
scale = mu / shape
return np.random.gamma(shape=shape, scale=scale, size=None) | python | def sample(self, mu):
# in numpy.random.gamma, `shape` is the parameter sometimes denoted by
# `k` that corresponds to `nu` in S. Wood (2006) Table 2.1
shape = 1. / self.scale
# in numpy.random.gamma, `scale` is the parameter sometimes denoted by
# `theta` that corresponds to mu / nu in S. Wood (2006) Table 2.1
scale = mu / shape
return np.random.gamma(shape=shape, scale=scale, size=None) | [
"def",
"sample",
"(",
"self",
",",
"mu",
")",
":",
"# in numpy.random.gamma, `shape` is the parameter sometimes denoted by",
"# `k` that corresponds to `nu` in S. Wood (2006) Table 2.1",
"shape",
"=",
"1.",
"/",
"self",
".",
"scale",
"# in numpy.random.gamma, `scale` is the paramet... | Return random samples from this Gamma distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.array of same shape as mu | [
"Return",
"random",
"samples",
"from",
"this",
"Gamma",
"distribution",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/distributions.py#L535-L554 |
239,385 | dswah/pyGAM | pygam/datasets/load_datasets.py | _clean_X_y | def _clean_X_y(X, y):
"""ensure that X and y data are float and correct shapes
"""
return make_2d(X, verbose=False).astype('float'), y.astype('float') | python | def _clean_X_y(X, y):
return make_2d(X, verbose=False).astype('float'), y.astype('float') | [
"def",
"_clean_X_y",
"(",
"X",
",",
"y",
")",
":",
"return",
"make_2d",
"(",
"X",
",",
"verbose",
"=",
"False",
")",
".",
"astype",
"(",
"'float'",
")",
",",
"y",
".",
"astype",
"(",
"'float'",
")"
] | ensure that X and y data are float and correct shapes | [
"ensure",
"that",
"X",
"and",
"y",
"data",
"are",
"float",
"and",
"correct",
"shapes"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L17-L20 |
239,386 | dswah/pyGAM | pygam/datasets/load_datasets.py | mcycle | def mcycle(return_X_y=True):
"""motorcyle acceleration dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the times after the impact.
y contains the acceleration.
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/MASS/mcycle.html
"""
# y is real
# recommend LinearGAM
motor = pd.read_csv(PATH + '/mcycle.csv', index_col=0)
if return_X_y:
X = motor.times.values
y = motor.accel
return _clean_X_y(X, y)
return motor | python | def mcycle(return_X_y=True):
# y is real
# recommend LinearGAM
motor = pd.read_csv(PATH + '/mcycle.csv', index_col=0)
if return_X_y:
X = motor.times.values
y = motor.accel
return _clean_X_y(X, y)
return motor | [
"def",
"mcycle",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# y is real",
"# recommend LinearGAM",
"motor",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/mcycle.csv'",
",",
"index_col",
"=",
"0",
")",
"if",
"return_X_y",
":",
"X",
"=",
"motor",
".",
"... | motorcyle acceleration dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the times after the impact.
y contains the acceleration.
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/MASS/mcycle.html | [
"motorcyle",
"acceleration",
"dataset"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L22-L52 |
239,387 | dswah/pyGAM | pygam/datasets/load_datasets.py | coal | def coal(return_X_y=True):
"""coal-mining accidents dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
The (X, y) tuple is a processed version of the otherwise raw DataFrame.
A histogram of 150 bins has been computed describing the number accidents per year.
X contains the midpoints of histogram bins.
y contains the count in each histogram bin.
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/boot/coal.html
"""
# y is counts
# recommend PoissonGAM
coal = pd.read_csv(PATH + '/coal.csv', index_col=0)
if return_X_y:
y, x = np.histogram(coal.values, bins=150)
X = x[:-1] + np.diff(x)/2 # get midpoints of bins
return _clean_X_y(X, y)
return coal | python | def coal(return_X_y=True):
# y is counts
# recommend PoissonGAM
coal = pd.read_csv(PATH + '/coal.csv', index_col=0)
if return_X_y:
y, x = np.histogram(coal.values, bins=150)
X = x[:-1] + np.diff(x)/2 # get midpoints of bins
return _clean_X_y(X, y)
return coal | [
"def",
"coal",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# y is counts",
"# recommend PoissonGAM",
"coal",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/coal.csv'",
",",
"index_col",
"=",
"0",
")",
"if",
"return_X_y",
":",
"y",
",",
"x",
"=",
"np",
... | coal-mining accidents dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
The (X, y) tuple is a processed version of the otherwise raw DataFrame.
A histogram of 150 bins has been computed describing the number accidents per year.
X contains the midpoints of histogram bins.
y contains the count in each histogram bin.
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/boot/coal.html | [
"coal",
"-",
"mining",
"accidents",
"dataset"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L54-L88 |
239,388 | dswah/pyGAM | pygam/datasets/load_datasets.py | faithful | def faithful(return_X_y=True):
"""old-faithful dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
The (X, y) tuple is a processed version of the otherwise raw DataFrame.
A histogram of 200 bins has been computed describing the wating time between eruptions.
X contains the midpoints of histogram bins.
y contains the count in each histogram bin.
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/datasets/faithful.html
"""
# y is counts
# recommend PoissonGAM
faithful = pd.read_csv(PATH + '/faithful.csv', index_col=0)
if return_X_y:
y, x = np.histogram(faithful['eruptions'], bins=200)
X = x[:-1] + np.diff(x)/2 # get midpoints of bins
return _clean_X_y(X, y)
return faithful | python | def faithful(return_X_y=True):
# y is counts
# recommend PoissonGAM
faithful = pd.read_csv(PATH + '/faithful.csv', index_col=0)
if return_X_y:
y, x = np.histogram(faithful['eruptions'], bins=200)
X = x[:-1] + np.diff(x)/2 # get midpoints of bins
return _clean_X_y(X, y)
return faithful | [
"def",
"faithful",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# y is counts",
"# recommend PoissonGAM",
"faithful",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/faithful.csv'",
",",
"index_col",
"=",
"0",
")",
"if",
"return_X_y",
":",
"y",
",",
"x",
"=... | old-faithful dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
The (X, y) tuple is a processed version of the otherwise raw DataFrame.
A histogram of 200 bins has been computed describing the wating time between eruptions.
X contains the midpoints of histogram bins.
y contains the count in each histogram bin.
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/datasets/faithful.html | [
"old",
"-",
"faithful",
"dataset"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L90-L124 |
239,389 | dswah/pyGAM | pygam/datasets/load_datasets.py | trees | def trees(return_X_y=True):
"""cherry trees dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the girth and the height of each tree.
y contains the volume.
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/datasets/trees.html
"""
# y is real.
# recommend InvGaussGAM, or GAM(distribution='gamma', link='log')
trees = pd.read_csv(PATH + '/trees.csv', index_col=0)
if return_X_y:
y = trees.Volume.values
X = trees[['Girth', 'Height']].values
return _clean_X_y(X, y)
return trees | python | def trees(return_X_y=True):
# y is real.
# recommend InvGaussGAM, or GAM(distribution='gamma', link='log')
trees = pd.read_csv(PATH + '/trees.csv', index_col=0)
if return_X_y:
y = trees.Volume.values
X = trees[['Girth', 'Height']].values
return _clean_X_y(X, y)
return trees | [
"def",
"trees",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# y is real.",
"# recommend InvGaussGAM, or GAM(distribution='gamma', link='log')",
"trees",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/trees.csv'",
",",
"index_col",
"=",
"0",
")",
"if",
"return_X_y",... | cherry trees dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the girth and the height of each tree.
y contains the volume.
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/datasets/trees.html | [
"cherry",
"trees",
"dataset"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L161-L191 |
239,390 | dswah/pyGAM | pygam/datasets/load_datasets.py | default | def default(return_X_y=True):
"""credit default dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the category of student or not, credit card balance,
and income.
y contains the outcome of default (0) or not (1).
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/ISLR/Default.html
"""
# y is binary
# recommend LogisticGAM
default = pd.read_csv(PATH + '/default.csv', index_col=0)
if return_X_y:
default = default.values
default[:,0] = np.unique(default[:,0], return_inverse=True)[1]
default[:,1] = np.unique(default[:,1], return_inverse=True)[1]
X = default[:,1:]
y = default[:,0]
return _clean_X_y(X, y)
return default | python | def default(return_X_y=True):
# y is binary
# recommend LogisticGAM
default = pd.read_csv(PATH + '/default.csv', index_col=0)
if return_X_y:
default = default.values
default[:,0] = np.unique(default[:,0], return_inverse=True)[1]
default[:,1] = np.unique(default[:,1], return_inverse=True)[1]
X = default[:,1:]
y = default[:,0]
return _clean_X_y(X, y)
return default | [
"def",
"default",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# y is binary",
"# recommend LogisticGAM",
"default",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/default.csv'",
",",
"index_col",
"=",
"0",
")",
"if",
"return_X_y",
":",
"default",
"=",
"defa... | credit default dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the category of student or not, credit card balance,
and income.
y contains the outcome of default (0) or not (1).
Source:
https://vincentarelbundock.github.io/Rdatasets/doc/ISLR/Default.html | [
"credit",
"default",
"dataset"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L193-L228 |
239,391 | dswah/pyGAM | pygam/datasets/load_datasets.py | hepatitis | def hepatitis(return_X_y=True):
"""hepatitis in Bulgaria dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the age of each patient group.
y contains the ratio of HAV positive patients to the total number for each
age group.
Groups with 0 total patients are excluded.
Source:
Keiding, N. (1991) Age-specific incidence and prevalence: a statistical perspective
"""
# y is real
# recommend LinearGAM
hep = pd.read_csv(PATH + '/hepatitis_A_bulgaria.csv').astype(float)
if return_X_y:
# eliminate 0/0
mask = (hep.total > 0).values
hep = hep[mask]
X = hep.age.values
y = hep.hepatitis_A_positive.values / hep.total.values
return _clean_X_y(X, y)
return hep | python | def hepatitis(return_X_y=True):
# y is real
# recommend LinearGAM
hep = pd.read_csv(PATH + '/hepatitis_A_bulgaria.csv').astype(float)
if return_X_y:
# eliminate 0/0
mask = (hep.total > 0).values
hep = hep[mask]
X = hep.age.values
y = hep.hepatitis_A_positive.values / hep.total.values
return _clean_X_y(X, y)
return hep | [
"def",
"hepatitis",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# y is real",
"# recommend LinearGAM",
"hep",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/hepatitis_A_bulgaria.csv'",
")",
".",
"astype",
"(",
"float",
")",
"if",
"return_X_y",
":",
"# elimina... | hepatitis in Bulgaria dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the age of each patient group.
y contains the ratio of HAV positive patients to the total number for each
age group.
Groups with 0 total patients are excluded.
Source:
Keiding, N. (1991) Age-specific incidence and prevalence: a statistical perspective | [
"hepatitis",
"in",
"Bulgaria",
"dataset"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L266-L304 |
239,392 | dswah/pyGAM | pygam/datasets/load_datasets.py | toy_classification | def toy_classification(return_X_y=True, n=5000):
"""toy classification dataset with irrelevant features
fitting a logistic model on this data and performing a model summary
should reveal that features 2,3,4 are not significant.
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
n : int, default: 5000
number of samples to generate
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains 5 variables:
continuous feature 0
continuous feature 1
irrelevant feature 0
irrelevant feature 1
irrelevant feature 2
categorical feature 0
y contains binary labels
Also, this dataset is randomly generated and will vary each time.
"""
# make features
X = np.random.rand(n,5) * 10 - 5
cat = np.random.randint(0,4, n)
X = np.c_[X, cat]
# make observations
log_odds = (-0.5*X[:,0]**2) + 5 +(-0.5*X[:,1]**2) + np.mod(X[:,-1], 2)*-30
p = 1/(1+np.exp(-log_odds)).squeeze()
y = (np.random.rand(n) < p).astype(np.int)
if return_X_y:
return X, y
else:
return pd.DataFrame(np.c_[X, y], columns=[['continuous0',
'continuous1',
'irrelevant0',
'irrelevant1',
'irrelevant2',
'categorical0',
'observations'
]]) | python | def toy_classification(return_X_y=True, n=5000):
# make features
X = np.random.rand(n,5) * 10 - 5
cat = np.random.randint(0,4, n)
X = np.c_[X, cat]
# make observations
log_odds = (-0.5*X[:,0]**2) + 5 +(-0.5*X[:,1]**2) + np.mod(X[:,-1], 2)*-30
p = 1/(1+np.exp(-log_odds)).squeeze()
y = (np.random.rand(n) < p).astype(np.int)
if return_X_y:
return X, y
else:
return pd.DataFrame(np.c_[X, y], columns=[['continuous0',
'continuous1',
'irrelevant0',
'irrelevant1',
'irrelevant2',
'categorical0',
'observations'
]]) | [
"def",
"toy_classification",
"(",
"return_X_y",
"=",
"True",
",",
"n",
"=",
"5000",
")",
":",
"# make features",
"X",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"n",
",",
"5",
")",
"*",
"10",
"-",
"5",
"cat",
"=",
"np",
".",
"random",
".",
"rand... | toy classification dataset with irrelevant features
fitting a logistic model on this data and performing a model summary
should reveal that features 2,3,4 are not significant.
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
n : int, default: 5000
number of samples to generate
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains 5 variables:
continuous feature 0
continuous feature 1
irrelevant feature 0
irrelevant feature 1
irrelevant feature 2
categorical feature 0
y contains binary labels
Also, this dataset is randomly generated and will vary each time. | [
"toy",
"classification",
"dataset",
"with",
"irrelevant",
"features"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L306-L361 |
239,393 | dswah/pyGAM | pygam/datasets/load_datasets.py | head_circumference | def head_circumference(return_X_y=True):
"""head circumference for dutch boys
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the age in years of each patient.
y contains the head circumference in centimeters
"""
# y is real
# recommend ExpectileGAM
head = pd.read_csv(PATH + '/head_circumference.csv', index_col=0).astype(float)
if return_X_y:
y = head['head'].values
X = head[['age']].values
return _clean_X_y(X, y)
return head | python | def head_circumference(return_X_y=True):
# y is real
# recommend ExpectileGAM
head = pd.read_csv(PATH + '/head_circumference.csv', index_col=0).astype(float)
if return_X_y:
y = head['head'].values
X = head[['age']].values
return _clean_X_y(X, y)
return head | [
"def",
"head_circumference",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# y is real",
"# recommend ExpectileGAM",
"head",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/head_circumference.csv'",
",",
"index_col",
"=",
"0",
")",
".",
"astype",
"(",
"float",
"... | head circumference for dutch boys
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains the age in years of each patient.
y contains the head circumference in centimeters | [
"head",
"circumference",
"for",
"dutch",
"boys"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L363-L391 |
239,394 | dswah/pyGAM | pygam/datasets/load_datasets.py | chicago | def chicago(return_X_y=True):
"""Chicago air pollution and death rate data
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains [['time', 'tmpd', 'pm10median', 'o3median']], with no NaNs
y contains 'death', the deaths per day, with no NaNs
Source:
R gamair package
`data(chicago)`
Notes
-----
https://cran.r-project.org/web/packages/gamair/gamair.pdf
https://rdrr.io/cran/gamair/man/chicago.html
Columns:
death : total deaths (per day).
pm10median : median particles in 2.5-10 per cubic m
pm25median : median particles < 2.5 mg per cubic m (more dangerous).
o3median : Ozone in parts per billion
so2median : Median Sulpher dioxide measurement
time : time in days
tmpd : temperature in fahrenheit
"""
# recommend PoissonGAM
chi = pd.read_csv(PATH + '/chicago.csv', index_col=0).astype(float)
if return_X_y:
chi = chi[['time', 'tmpd', 'pm10median', 'o3median', 'death']].dropna()
X = chi[['time', 'tmpd', 'pm10median', 'o3median']].values
y = chi['death'].values
return X, y
else:
return chi | python | def chicago(return_X_y=True):
# recommend PoissonGAM
chi = pd.read_csv(PATH + '/chicago.csv', index_col=0).astype(float)
if return_X_y:
chi = chi[['time', 'tmpd', 'pm10median', 'o3median', 'death']].dropna()
X = chi[['time', 'tmpd', 'pm10median', 'o3median']].values
y = chi['death'].values
return X, y
else:
return chi | [
"def",
"chicago",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# recommend PoissonGAM",
"chi",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/chicago.csv'",
",",
"index_col",
"=",
"0",
")",
".",
"astype",
"(",
"float",
")",
"if",
"return_X_y",
":",
"chi"... | Chicago air pollution and death rate data
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains [['time', 'tmpd', 'pm10median', 'o3median']], with no NaNs
y contains 'death', the deaths per day, with no NaNs
Source:
R gamair package
`data(chicago)`
Notes
-----
https://cran.r-project.org/web/packages/gamair/gamair.pdf
https://rdrr.io/cran/gamair/man/chicago.html
Columns:
death : total deaths (per day).
pm10median : median particles in 2.5-10 per cubic m
pm25median : median particles < 2.5 mg per cubic m (more dangerous).
o3median : Ozone in parts per billion
so2median : Median Sulpher dioxide measurement
time : time in days
tmpd : temperature in fahrenheit | [
"Chicago",
"air",
"pollution",
"and",
"death",
"rate",
"data"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L393-L442 |
239,395 | dswah/pyGAM | pygam/datasets/load_datasets.py | toy_interaction | def toy_interaction(return_X_y=True, n=50000, stddev=0.1):
"""a sinusoid modulated by a linear function
this is a simple dataset to test a model's capacity to fit interactions
between features.
a GAM with no interaction terms will have an R-squared close to 0,
while a GAM with a tensor product will have R-squared close to 1.
the data is random, and will vary on each invocation.
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
n : int, optional
number of points to generate
stddev : positive float, optional,
standard deviation of irreducible error
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains [['sinusoid', 'linear']]
y is formed by multiplying the sinusoid by the linear function.
Source:
"""
X = np.random.uniform(-1,1, size=(n, 2))
X[:, 1] *= 5
y = np.sin(X[:,0] * 2 * np.pi * 1.5) * X[:,1]
y += np.random.randn(len(X)) * stddev
if return_X_y:
return X, y
else:
data = pd.DataFrame(np.c_[X, y])
data.columns = [['sinusoid', 'linear', 'y']]
return data | python | def toy_interaction(return_X_y=True, n=50000, stddev=0.1):
X = np.random.uniform(-1,1, size=(n, 2))
X[:, 1] *= 5
y = np.sin(X[:,0] * 2 * np.pi * 1.5) * X[:,1]
y += np.random.randn(len(X)) * stddev
if return_X_y:
return X, y
else:
data = pd.DataFrame(np.c_[X, y])
data.columns = [['sinusoid', 'linear', 'y']]
return data | [
"def",
"toy_interaction",
"(",
"return_X_y",
"=",
"True",
",",
"n",
"=",
"50000",
",",
"stddev",
"=",
"0.1",
")",
":",
"X",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
",",
"size",
"=",
"(",
"n",
",",
"2",
")",
")",
"X"... | a sinusoid modulated by a linear function
this is a simple dataset to test a model's capacity to fit interactions
between features.
a GAM with no interaction terms will have an R-squared close to 0,
while a GAM with a tensor product will have R-squared close to 1.
the data is random, and will vary on each invocation.
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
n : int, optional
number of points to generate
stddev : positive float, optional,
standard deviation of irreducible error
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
-----
X contains [['sinusoid', 'linear']]
y is formed by multiplying the sinusoid by the linear function.
Source: | [
"a",
"sinusoid",
"modulated",
"by",
"a",
"linear",
"function"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/datasets/load_datasets.py#L444-L493 |
239,396 | dswah/pyGAM | gen_imgs.py | gen_multi_data | def gen_multi_data(n=5000):
"""
multivariate Logistic problem
"""
X, y = toy_classification(return_X_y=True, n=10000)
lgam = LogisticGAM(s(0) + s(1) + s(2) + s(3) + s(4) + f(5))
lgam.fit(X, y)
plt.figure()
for i, term in enumerate(lgam.terms):
if term.isintercept:
continue
plt.plot(lgam.partial_dependence(term=i))
plt.savefig('imgs/pygam_multi_pdep.png', dpi=300)
plt.figure()
plt.plot(lgam.logs_['deviance'])
plt.savefig('imgs/pygam_multi_deviance.png', dpi=300) | python | def gen_multi_data(n=5000):
X, y = toy_classification(return_X_y=True, n=10000)
lgam = LogisticGAM(s(0) + s(1) + s(2) + s(3) + s(4) + f(5))
lgam.fit(X, y)
plt.figure()
for i, term in enumerate(lgam.terms):
if term.isintercept:
continue
plt.plot(lgam.partial_dependence(term=i))
plt.savefig('imgs/pygam_multi_pdep.png', dpi=300)
plt.figure()
plt.plot(lgam.logs_['deviance'])
plt.savefig('imgs/pygam_multi_deviance.png', dpi=300) | [
"def",
"gen_multi_data",
"(",
"n",
"=",
"5000",
")",
":",
"X",
",",
"y",
"=",
"toy_classification",
"(",
"return_X_y",
"=",
"True",
",",
"n",
"=",
"10000",
")",
"lgam",
"=",
"LogisticGAM",
"(",
"s",
"(",
"0",
")",
"+",
"s",
"(",
"1",
")",
"+",
... | multivariate Logistic problem | [
"multivariate",
"Logistic",
"problem"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/gen_imgs.py#L229-L248 |
239,397 | dswah/pyGAM | gen_imgs.py | gen_tensor_data | def gen_tensor_data():
"""
toy interaction data
"""
X, y = toy_interaction(return_X_y=True, n=10000)
gam = LinearGAM(te(0, 1,lam=0.1)).fit(X, y)
XX = gam.generate_X_grid(term=0, meshgrid=True)
Z = gam.partial_dependence(term=0, meshgrid=True)
fig = plt.figure(figsize=(9,6))
ax = plt.axes(projection='3d')
ax.dist = 7.5
ax.plot_surface(XX[0], XX[1], Z, cmap='viridis')
ax.set_axis_off()
fig.tight_layout()
plt.savefig('imgs/pygam_tensor.png', transparent=True, dpi=300) | python | def gen_tensor_data():
X, y = toy_interaction(return_X_y=True, n=10000)
gam = LinearGAM(te(0, 1,lam=0.1)).fit(X, y)
XX = gam.generate_X_grid(term=0, meshgrid=True)
Z = gam.partial_dependence(term=0, meshgrid=True)
fig = plt.figure(figsize=(9,6))
ax = plt.axes(projection='3d')
ax.dist = 7.5
ax.plot_surface(XX[0], XX[1], Z, cmap='viridis')
ax.set_axis_off()
fig.tight_layout()
plt.savefig('imgs/pygam_tensor.png', transparent=True, dpi=300) | [
"def",
"gen_tensor_data",
"(",
")",
":",
"X",
",",
"y",
"=",
"toy_interaction",
"(",
"return_X_y",
"=",
"True",
",",
"n",
"=",
"10000",
")",
"gam",
"=",
"LinearGAM",
"(",
"te",
"(",
"0",
",",
"1",
",",
"lam",
"=",
"0.1",
")",
")",
".",
"fit",
"... | toy interaction data | [
"toy",
"interaction",
"data"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/gen_imgs.py#L250-L267 |
239,398 | dswah/pyGAM | gen_imgs.py | expectiles | def expectiles():
"""
a bunch of expectiles
"""
X, y = mcycle(return_X_y=True)
# lets fit the mean model first by CV
gam50 = ExpectileGAM(expectile=0.5).gridsearch(X, y)
# and copy the smoothing to the other models
lam = gam50.lam
# now fit a few more models
gam95 = ExpectileGAM(expectile=0.95, lam=lam).fit(X, y)
gam75 = ExpectileGAM(expectile=0.75, lam=lam).fit(X, y)
gam25 = ExpectileGAM(expectile=0.25, lam=lam).fit(X, y)
gam05 = ExpectileGAM(expectile=0.05, lam=lam).fit(X, y)
XX = gam50.generate_X_grid(term=0, n=500)
fig = plt.figure()
plt.scatter(X, y, c='k', alpha=0.2)
plt.plot(XX, gam95.predict(XX), label='0.95')
plt.plot(XX, gam75.predict(XX), label='0.75')
plt.plot(XX, gam50.predict(XX), label='0.50')
plt.plot(XX, gam25.predict(XX), label='0.25')
plt.plot(XX, gam05.predict(XX), label='0.05')
plt.legend()
fig.tight_layout()
plt.savefig('imgs/pygam_expectiles.png', dpi=300) | python | def expectiles():
X, y = mcycle(return_X_y=True)
# lets fit the mean model first by CV
gam50 = ExpectileGAM(expectile=0.5).gridsearch(X, y)
# and copy the smoothing to the other models
lam = gam50.lam
# now fit a few more models
gam95 = ExpectileGAM(expectile=0.95, lam=lam).fit(X, y)
gam75 = ExpectileGAM(expectile=0.75, lam=lam).fit(X, y)
gam25 = ExpectileGAM(expectile=0.25, lam=lam).fit(X, y)
gam05 = ExpectileGAM(expectile=0.05, lam=lam).fit(X, y)
XX = gam50.generate_X_grid(term=0, n=500)
fig = plt.figure()
plt.scatter(X, y, c='k', alpha=0.2)
plt.plot(XX, gam95.predict(XX), label='0.95')
plt.plot(XX, gam75.predict(XX), label='0.75')
plt.plot(XX, gam50.predict(XX), label='0.50')
plt.plot(XX, gam25.predict(XX), label='0.25')
plt.plot(XX, gam05.predict(XX), label='0.05')
plt.legend()
fig.tight_layout()
plt.savefig('imgs/pygam_expectiles.png', dpi=300) | [
"def",
"expectiles",
"(",
")",
":",
"X",
",",
"y",
"=",
"mcycle",
"(",
"return_X_y",
"=",
"True",
")",
"# lets fit the mean model first by CV",
"gam50",
"=",
"ExpectileGAM",
"(",
"expectile",
"=",
"0.5",
")",
".",
"gridsearch",
"(",
"X",
",",
"y",
")",
"... | a bunch of expectiles | [
"a",
"bunch",
"of",
"expectiles"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/gen_imgs.py#L287-L318 |
239,399 | dswah/pyGAM | pygam/utils.py | cholesky | def cholesky(A, sparse=True, verbose=True):
"""
Choose the best possible cholesky factorizor.
if possible, import the Scikit-Sparse sparse Cholesky method.
Permutes the output L to ensure A = L.H . L
otherwise defaults to numpy's non-sparse version
Parameters
----------
A : array-like
array to decompose
sparse : boolean, default: True
whether to return a sparse array
verbose : bool, default: True
whether to print warnings
"""
if SKSPIMPORT:
A = sp.sparse.csc_matrix(A)
try:
F = spcholesky(A)
# permutation matrix P
P = sp.sparse.lil_matrix(A.shape)
p = F.P()
P[np.arange(len(p)), p] = 1
# permute
L = F.L()
L = P.T.dot(L)
except CholmodNotPositiveDefiniteError as e:
raise NotPositiveDefiniteError('Matrix is not positive definite')
if sparse:
return L.T # upper triangular factorization
return L.T.A # upper triangular factorization
else:
msg = 'Could not import Scikit-Sparse or Suite-Sparse.\n'\
'This will slow down optimization for models with '\
'monotonicity/convexity penalties and many splines.\n'\
'See installation instructions for installing '\
'Scikit-Sparse and Suite-Sparse via Conda.'
if verbose:
warnings.warn(msg)
if sp.sparse.issparse(A):
A = A.A
try:
L = sp.linalg.cholesky(A, lower=False)
except LinAlgError as e:
raise NotPositiveDefiniteError('Matrix is not positive definite')
if sparse:
return sp.sparse.csc_matrix(L)
return L | python | def cholesky(A, sparse=True, verbose=True):
if SKSPIMPORT:
A = sp.sparse.csc_matrix(A)
try:
F = spcholesky(A)
# permutation matrix P
P = sp.sparse.lil_matrix(A.shape)
p = F.P()
P[np.arange(len(p)), p] = 1
# permute
L = F.L()
L = P.T.dot(L)
except CholmodNotPositiveDefiniteError as e:
raise NotPositiveDefiniteError('Matrix is not positive definite')
if sparse:
return L.T # upper triangular factorization
return L.T.A # upper triangular factorization
else:
msg = 'Could not import Scikit-Sparse or Suite-Sparse.\n'\
'This will slow down optimization for models with '\
'monotonicity/convexity penalties and many splines.\n'\
'See installation instructions for installing '\
'Scikit-Sparse and Suite-Sparse via Conda.'
if verbose:
warnings.warn(msg)
if sp.sparse.issparse(A):
A = A.A
try:
L = sp.linalg.cholesky(A, lower=False)
except LinAlgError as e:
raise NotPositiveDefiniteError('Matrix is not positive definite')
if sparse:
return sp.sparse.csc_matrix(L)
return L | [
"def",
"cholesky",
"(",
"A",
",",
"sparse",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"SKSPIMPORT",
":",
"A",
"=",
"sp",
".",
"sparse",
".",
"csc_matrix",
"(",
"A",
")",
"try",
":",
"F",
"=",
"spcholesky",
"(",
"A",
")",
"# permut... | Choose the best possible cholesky factorizor.
if possible, import the Scikit-Sparse sparse Cholesky method.
Permutes the output L to ensure A = L.H . L
otherwise defaults to numpy's non-sparse version
Parameters
----------
A : array-like
array to decompose
sparse : boolean, default: True
whether to return a sparse array
verbose : bool, default: True
whether to print warnings | [
"Choose",
"the",
"best",
"possible",
"cholesky",
"factorizor",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/utils.py#L33-L90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.