repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
coleifer/walrus | walrus/containers.py | ZSet.incr | def incr(self, key, incr_by=1.):
"""
Increment the score of an item in the ZSet.
:param key: Item to increment.
:param incr_by: Amount to increment item's score.
"""
return self.database.zincrby(self.key, incr_by, key) | python | def incr(self, key, incr_by=1.):
"""
Increment the score of an item in the ZSet.
:param key: Item to increment.
:param incr_by: Amount to increment item's score.
"""
return self.database.zincrby(self.key, incr_by, key) | [
"def",
"incr",
"(",
"self",
",",
"key",
",",
"incr_by",
"=",
"1.",
")",
":",
"return",
"self",
".",
"database",
".",
"zincrby",
"(",
"self",
".",
"key",
",",
"incr_by",
",",
"key",
")"
] | Increment the score of an item in the ZSet.
:param key: Item to increment.
:param incr_by: Amount to increment item's score. | [
"Increment",
"the",
"score",
"of",
"an",
"item",
"in",
"the",
"ZSet",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L762-L769 | train | 203,000 |
coleifer/walrus | walrus/containers.py | ZSet.interstore | def interstore(self, dest, *others, **kwargs):
"""
Store the intersection of the current zset and one or more
others in a new key.
:param dest: the name of the key to store intersection
:param others: One or more :py:class:`ZSet` instances
:returns: A :py:class:`ZSet` referencing ``dest``.
"""
keys = [self.key]
keys.extend([other.key for other in others])
self.database.zinterstore(dest, keys, **kwargs)
return self.database.ZSet(dest) | python | def interstore(self, dest, *others, **kwargs):
"""
Store the intersection of the current zset and one or more
others in a new key.
:param dest: the name of the key to store intersection
:param others: One or more :py:class:`ZSet` instances
:returns: A :py:class:`ZSet` referencing ``dest``.
"""
keys = [self.key]
keys.extend([other.key for other in others])
self.database.zinterstore(dest, keys, **kwargs)
return self.database.ZSet(dest) | [
"def",
"interstore",
"(",
"self",
",",
"dest",
",",
"*",
"others",
",",
"*",
"*",
"kwargs",
")",
":",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
"keys",
".",
"extend",
"(",
"[",
"other",
".",
"key",
"for",
"other",
"in",
"others",
"]",
")",
"se... | Store the intersection of the current zset and one or more
others in a new key.
:param dest: the name of the key to store intersection
:param others: One or more :py:class:`ZSet` instances
:returns: A :py:class:`ZSet` referencing ``dest``. | [
"Store",
"the",
"intersection",
"of",
"the",
"current",
"zset",
"and",
"one",
"or",
"more",
"others",
"in",
"a",
"new",
"key",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L786-L798 | train | 203,001 |
coleifer/walrus | walrus/containers.py | ZSet.from_dict | def from_dict(cls, database, key, data, clear=False):
"""
Create and populate a ZSet object from a data dictionary.
"""
zset = cls(database, key)
if clear:
zset.clear()
zset.add(data)
return zset | python | def from_dict(cls, database, key, data, clear=False):
"""
Create and populate a ZSet object from a data dictionary.
"""
zset = cls(database, key)
if clear:
zset.clear()
zset.add(data)
return zset | [
"def",
"from_dict",
"(",
"cls",
",",
"database",
",",
"key",
",",
"data",
",",
"clear",
"=",
"False",
")",
":",
"zset",
"=",
"cls",
"(",
"database",
",",
"key",
")",
"if",
"clear",
":",
"zset",
".",
"clear",
"(",
")",
"zset",
".",
"add",
"(",
"... | Create and populate a ZSet object from a data dictionary. | [
"Create",
"and",
"populate",
"a",
"ZSet",
"object",
"from",
"a",
"data",
"dictionary",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L892-L900 | train | 203,002 |
coleifer/walrus | walrus/containers.py | Array.append | def append(self, value):
"""Append a new value to the end of the array."""
self.database.run_script(
'array_append',
keys=[self.key],
args=[value]) | python | def append(self, value):
"""Append a new value to the end of the array."""
self.database.run_script(
'array_append',
keys=[self.key],
args=[value]) | [
"def",
"append",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"database",
".",
"run_script",
"(",
"'array_append'",
",",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
",",
"args",
"=",
"[",
"value",
"]",
")"
] | Append a new value to the end of the array. | [
"Append",
"a",
"new",
"value",
"to",
"the",
"end",
"of",
"the",
"array",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L970-L975 | train | 203,003 |
coleifer/walrus | walrus/containers.py | Array.extend | def extend(self, values):
"""Extend the array, appending the given values."""
self.database.run_script(
'array_extend',
keys=[self.key],
args=values) | python | def extend(self, values):
"""Extend the array, appending the given values."""
self.database.run_script(
'array_extend',
keys=[self.key],
args=values) | [
"def",
"extend",
"(",
"self",
",",
"values",
")",
":",
"self",
".",
"database",
".",
"run_script",
"(",
"'array_extend'",
",",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
",",
"args",
"=",
"values",
")"
] | Extend the array, appending the given values. | [
"Extend",
"the",
"array",
"appending",
"the",
"given",
"values",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L977-L982 | train | 203,004 |
coleifer/walrus | walrus/containers.py | Array.pop | def pop(self, idx=None):
"""
Remove an item from the array. By default this will be the
last item by index, but any index can be specified.
"""
if idx is not None:
return self.database.run_script(
'array_remove',
keys=[self.key],
args=[idx])
else:
return self.database.run_script(
'array_pop',
keys=[self.key],
args=[]) | python | def pop(self, idx=None):
"""
Remove an item from the array. By default this will be the
last item by index, but any index can be specified.
"""
if idx is not None:
return self.database.run_script(
'array_remove',
keys=[self.key],
args=[idx])
else:
return self.database.run_script(
'array_pop',
keys=[self.key],
args=[]) | [
"def",
"pop",
"(",
"self",
",",
"idx",
"=",
"None",
")",
":",
"if",
"idx",
"is",
"not",
"None",
":",
"return",
"self",
".",
"database",
".",
"run_script",
"(",
"'array_remove'",
",",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
",",
"args",
"=",
"[... | Remove an item from the array. By default this will be the
last item by index, but any index can be specified. | [
"Remove",
"an",
"item",
"from",
"the",
"array",
".",
"By",
"default",
"this",
"will",
"be",
"the",
"last",
"item",
"by",
"index",
"but",
"any",
"index",
"can",
"be",
"specified",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L984-L998 | train | 203,005 |
coleifer/walrus | walrus/containers.py | Array.as_list | def as_list(self, decode=False):
"""
Return a list of items in the array.
"""
return [_decode(i) for i in self] if decode else list(self) | python | def as_list(self, decode=False):
"""
Return a list of items in the array.
"""
return [_decode(i) for i in self] if decode else list(self) | [
"def",
"as_list",
"(",
"self",
",",
"decode",
"=",
"False",
")",
":",
"return",
"[",
"_decode",
"(",
"i",
")",
"for",
"i",
"in",
"self",
"]",
"if",
"decode",
"else",
"list",
"(",
"self",
")"
] | Return a list of items in the array. | [
"Return",
"a",
"list",
"of",
"items",
"in",
"the",
"array",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1016-L1020 | train | 203,006 |
coleifer/walrus | walrus/containers.py | Array.from_list | def from_list(cls, database, key, data, clear=False):
"""
Create and populate an Array object from a data dictionary.
"""
arr = cls(database, key)
if clear:
arr.clear()
arr.extend(data)
return arr | python | def from_list(cls, database, key, data, clear=False):
"""
Create and populate an Array object from a data dictionary.
"""
arr = cls(database, key)
if clear:
arr.clear()
arr.extend(data)
return arr | [
"def",
"from_list",
"(",
"cls",
",",
"database",
",",
"key",
",",
"data",
",",
"clear",
"=",
"False",
")",
":",
"arr",
"=",
"cls",
"(",
"database",
",",
"key",
")",
"if",
"clear",
":",
"arr",
".",
"clear",
"(",
")",
"arr",
".",
"extend",
"(",
"... | Create and populate an Array object from a data dictionary. | [
"Create",
"and",
"populate",
"an",
"Array",
"object",
"from",
"a",
"data",
"dictionary",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1023-L1031 | train | 203,007 |
coleifer/walrus | walrus/containers.py | Stream.add | def add(self, data, id='*', maxlen=None, approximate=True):
"""
Add data to a stream.
:param dict data: data to add to stream
:param id: identifier for message ('*' to automatically append)
:param maxlen: maximum length for stream
:param approximate: allow stream max length to be approximate
:returns: the added message id.
"""
return self.database.xadd(self.key, data, id, maxlen, approximate) | python | def add(self, data, id='*', maxlen=None, approximate=True):
"""
Add data to a stream.
:param dict data: data to add to stream
:param id: identifier for message ('*' to automatically append)
:param maxlen: maximum length for stream
:param approximate: allow stream max length to be approximate
:returns: the added message id.
"""
return self.database.xadd(self.key, data, id, maxlen, approximate) | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"id",
"=",
"'*'",
",",
"maxlen",
"=",
"None",
",",
"approximate",
"=",
"True",
")",
":",
"return",
"self",
".",
"database",
".",
"xadd",
"(",
"self",
".",
"key",
",",
"data",
",",
"id",
",",
"maxlen",
... | Add data to a stream.
:param dict data: data to add to stream
:param id: identifier for message ('*' to automatically append)
:param maxlen: maximum length for stream
:param approximate: allow stream max length to be approximate
:returns: the added message id. | [
"Add",
"data",
"to",
"a",
"stream",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1051-L1061 | train | 203,008 |
coleifer/walrus | walrus/containers.py | Stream.range | def range(self, start='-', stop='+', count=None):
"""
Read a range of values from a stream.
:param start: start key of range (inclusive) or '-' for oldest message
:param stop: stop key of range (inclusive) or '+' for newest message
:param count: limit number of messages returned
"""
return self.database.xrange(self.key, start, stop, count) | python | def range(self, start='-', stop='+', count=None):
"""
Read a range of values from a stream.
:param start: start key of range (inclusive) or '-' for oldest message
:param stop: stop key of range (inclusive) or '+' for newest message
:param count: limit number of messages returned
"""
return self.database.xrange(self.key, start, stop, count) | [
"def",
"range",
"(",
"self",
",",
"start",
"=",
"'-'",
",",
"stop",
"=",
"'+'",
",",
"count",
"=",
"None",
")",
":",
"return",
"self",
".",
"database",
".",
"xrange",
"(",
"self",
".",
"key",
",",
"start",
",",
"stop",
",",
"count",
")"
] | Read a range of values from a stream.
:param start: start key of range (inclusive) or '-' for oldest message
:param stop: stop key of range (inclusive) or '+' for newest message
:param count: limit number of messages returned | [
"Read",
"a",
"range",
"of",
"values",
"from",
"a",
"stream",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1089-L1097 | train | 203,009 |
coleifer/walrus | walrus/containers.py | Stream.revrange | def revrange(self, start='+', stop='-', count=None):
"""
Read a range of values from a stream in reverse.
:param start: start key of range (inclusive) or '+' for newest message
:param stop: stop key of range (inclusive) or '-' for oldest message
:param count: limit number of messages returned
"""
return self.database.xrevrange(self.key, start, stop, count) | python | def revrange(self, start='+', stop='-', count=None):
"""
Read a range of values from a stream in reverse.
:param start: start key of range (inclusive) or '+' for newest message
:param stop: stop key of range (inclusive) or '-' for oldest message
:param count: limit number of messages returned
"""
return self.database.xrevrange(self.key, start, stop, count) | [
"def",
"revrange",
"(",
"self",
",",
"start",
"=",
"'+'",
",",
"stop",
"=",
"'-'",
",",
"count",
"=",
"None",
")",
":",
"return",
"self",
".",
"database",
".",
"xrevrange",
"(",
"self",
".",
"key",
",",
"start",
",",
"stop",
",",
"count",
")"
] | Read a range of values from a stream in reverse.
:param start: start key of range (inclusive) or '+' for newest message
:param stop: stop key of range (inclusive) or '-' for oldest message
:param count: limit number of messages returned | [
"Read",
"a",
"range",
"of",
"values",
"from",
"a",
"stream",
"in",
"reverse",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1099-L1107 | train | 203,010 |
coleifer/walrus | walrus/containers.py | Stream.read | def read(self, count=None, block=None, last_id=None):
"""
Monitor stream for new data.
:param int count: limit number of messages returned
:param int block: milliseconds to block, 0 for indefinitely
:param last_id: Last id read (an exclusive lower-bound). If the '$'
value is given, we will only read values added *after* our command
started blocking.
:returns: a list of (message id, data) 2-tuples.
"""
if last_id is None: last_id = '0-0'
resp = self.database.xread({self.key: _decode(last_id)}, count, block)
# resp is a 2-tuple of stream name -> message list.
return resp[0][1] if resp else [] | python | def read(self, count=None, block=None, last_id=None):
"""
Monitor stream for new data.
:param int count: limit number of messages returned
:param int block: milliseconds to block, 0 for indefinitely
:param last_id: Last id read (an exclusive lower-bound). If the '$'
value is given, we will only read values added *after* our command
started blocking.
:returns: a list of (message id, data) 2-tuples.
"""
if last_id is None: last_id = '0-0'
resp = self.database.xread({self.key: _decode(last_id)}, count, block)
# resp is a 2-tuple of stream name -> message list.
return resp[0][1] if resp else [] | [
"def",
"read",
"(",
"self",
",",
"count",
"=",
"None",
",",
"block",
"=",
"None",
",",
"last_id",
"=",
"None",
")",
":",
"if",
"last_id",
"is",
"None",
":",
"last_id",
"=",
"'0-0'",
"resp",
"=",
"self",
".",
"database",
".",
"xread",
"(",
"{",
"s... | Monitor stream for new data.
:param int count: limit number of messages returned
:param int block: milliseconds to block, 0 for indefinitely
:param last_id: Last id read (an exclusive lower-bound). If the '$'
value is given, we will only read values added *after* our command
started blocking.
:returns: a list of (message id, data) 2-tuples. | [
"Monitor",
"stream",
"for",
"new",
"data",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1135-L1150 | train | 203,011 |
coleifer/walrus | walrus/containers.py | Stream.trim | def trim(self, count, approximate=True):
"""
Trim the stream to the given "count" of messages, discarding the oldest
messages first.
:param count: maximum size of stream
:param approximate: allow size to be approximate
"""
return self.database.xtrim(self.key, count, approximate) | python | def trim(self, count, approximate=True):
"""
Trim the stream to the given "count" of messages, discarding the oldest
messages first.
:param count: maximum size of stream
:param approximate: allow size to be approximate
"""
return self.database.xtrim(self.key, count, approximate) | [
"def",
"trim",
"(",
"self",
",",
"count",
",",
"approximate",
"=",
"True",
")",
":",
"return",
"self",
".",
"database",
".",
"xtrim",
"(",
"self",
".",
"key",
",",
"count",
",",
"approximate",
")"
] | Trim the stream to the given "count" of messages, discarding the oldest
messages first.
:param count: maximum size of stream
:param approximate: allow size to be approximate | [
"Trim",
"the",
"stream",
"to",
"the",
"given",
"count",
"of",
"messages",
"discarding",
"the",
"oldest",
"messages",
"first",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1188-L1196 | train | 203,012 |
coleifer/walrus | walrus/containers.py | ConsumerGroupStream.pending | def pending(self, start='-', stop='+', count=1000, consumer=None):
"""
List pending messages within the consumer group for this stream.
:param start: start id (or '-' for oldest pending)
:param stop: stop id (or '+' for newest pending)
:param count: limit number of messages returned
:param consumer: restrict message list to the given consumer
:returns: A list containing status for each pending message. Each
pending message returns [id, consumer, idle time, deliveries].
"""
return self.database.xpending_range(self.key, self.group, start, stop,
count, consumer) | python | def pending(self, start='-', stop='+', count=1000, consumer=None):
"""
List pending messages within the consumer group for this stream.
:param start: start id (or '-' for oldest pending)
:param stop: stop id (or '+' for newest pending)
:param count: limit number of messages returned
:param consumer: restrict message list to the given consumer
:returns: A list containing status for each pending message. Each
pending message returns [id, consumer, idle time, deliveries].
"""
return self.database.xpending_range(self.key, self.group, start, stop,
count, consumer) | [
"def",
"pending",
"(",
"self",
",",
"start",
"=",
"'-'",
",",
"stop",
"=",
"'+'",
",",
"count",
"=",
"1000",
",",
"consumer",
"=",
"None",
")",
":",
"return",
"self",
".",
"database",
".",
"xpending_range",
"(",
"self",
".",
"key",
",",
"self",
"."... | List pending messages within the consumer group for this stream.
:param start: start id (or '-' for oldest pending)
:param stop: stop id (or '+' for newest pending)
:param count: limit number of messages returned
:param consumer: restrict message list to the given consumer
:returns: A list containing status for each pending message. Each
pending message returns [id, consumer, idle time, deliveries]. | [
"List",
"pending",
"messages",
"within",
"the",
"consumer",
"group",
"for",
"this",
"stream",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1257-L1269 | train | 203,013 |
coleifer/walrus | walrus/containers.py | ConsumerGroupStream.delete_consumer | def delete_consumer(self, consumer=None):
"""
Remove a specific consumer from a consumer group.
:consumer: name of consumer to delete. If not provided, will be the
default consumer for this stream.
:returns: number of pending messages that the consumer had before
being deleted.
"""
if consumer is None: consumer = self._consumer
return self.database.xgroup_delconsumer(self.key, self.group, consumer) | python | def delete_consumer(self, consumer=None):
"""
Remove a specific consumer from a consumer group.
:consumer: name of consumer to delete. If not provided, will be the
default consumer for this stream.
:returns: number of pending messages that the consumer had before
being deleted.
"""
if consumer is None: consumer = self._consumer
return self.database.xgroup_delconsumer(self.key, self.group, consumer) | [
"def",
"delete_consumer",
"(",
"self",
",",
"consumer",
"=",
"None",
")",
":",
"if",
"consumer",
"is",
"None",
":",
"consumer",
"=",
"self",
".",
"_consumer",
"return",
"self",
".",
"database",
".",
"xgroup_delconsumer",
"(",
"self",
".",
"key",
",",
"se... | Remove a specific consumer from a consumer group.
:consumer: name of consumer to delete. If not provided, will be the
default consumer for this stream.
:returns: number of pending messages that the consumer had before
being deleted. | [
"Remove",
"a",
"specific",
"consumer",
"from",
"a",
"consumer",
"group",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1297-L1307 | train | 203,014 |
coleifer/walrus | walrus/containers.py | ConsumerGroup.create | def create(self, ensure_keys_exist=True, mkstream=False):
"""
Create the consumer group and register it with the group's stream keys.
:param ensure_keys_exist: Ensure that the streams exist before creating
the consumer group. Streams that do not exist will be created.
:param mkstream: Use the "MKSTREAM" option to ensure stream exists (may
require unstable version of Redis).
"""
if ensure_keys_exist:
for key in self.keys:
if not self.database.exists(key):
msg_id = self.database.xadd(key, {'': ''}, id=b'0-1')
self.database.xdel(key, msg_id)
elif self.database.type(key) != b'stream':
raise ValueError('Consumer group key "%s" exists and is '
'not a stream. To prevent data-loss '
'this key will not be deleted.')
resp = {}
# Mapping of key -> last-read message ID.
for key, value in self.keys.items():
try:
resp[key] = self.database.xgroup_create(key, self.name, value,
mkstream)
except ResponseError as exc:
if exception_message(exc).startswith('BUSYGROUP'):
resp[key] = False
else:
raise
return resp | python | def create(self, ensure_keys_exist=True, mkstream=False):
"""
Create the consumer group and register it with the group's stream keys.
:param ensure_keys_exist: Ensure that the streams exist before creating
the consumer group. Streams that do not exist will be created.
:param mkstream: Use the "MKSTREAM" option to ensure stream exists (may
require unstable version of Redis).
"""
if ensure_keys_exist:
for key in self.keys:
if not self.database.exists(key):
msg_id = self.database.xadd(key, {'': ''}, id=b'0-1')
self.database.xdel(key, msg_id)
elif self.database.type(key) != b'stream':
raise ValueError('Consumer group key "%s" exists and is '
'not a stream. To prevent data-loss '
'this key will not be deleted.')
resp = {}
# Mapping of key -> last-read message ID.
for key, value in self.keys.items():
try:
resp[key] = self.database.xgroup_create(key, self.name, value,
mkstream)
except ResponseError as exc:
if exception_message(exc).startswith('BUSYGROUP'):
resp[key] = False
else:
raise
return resp | [
"def",
"create",
"(",
"self",
",",
"ensure_keys_exist",
"=",
"True",
",",
"mkstream",
"=",
"False",
")",
":",
"if",
"ensure_keys_exist",
":",
"for",
"key",
"in",
"self",
".",
"keys",
":",
"if",
"not",
"self",
".",
"database",
".",
"exists",
"(",
"key",... | Create the consumer group and register it with the group's stream keys.
:param ensure_keys_exist: Ensure that the streams exist before creating
the consumer group. Streams that do not exist will be created.
:param mkstream: Use the "MKSTREAM" option to ensure stream exists (may
require unstable version of Redis). | [
"Create",
"the",
"consumer",
"group",
"and",
"register",
"it",
"with",
"the",
"group",
"s",
"stream",
"keys",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1368-L1399 | train | 203,015 |
coleifer/walrus | walrus/containers.py | ConsumerGroup.destroy | def destroy(self):
"""
Destroy the consumer group.
"""
resp = {}
for key in self.keys:
resp[key] = self.database.xgroup_destroy(key, self.name)
return resp | python | def destroy(self):
"""
Destroy the consumer group.
"""
resp = {}
for key in self.keys:
resp[key] = self.database.xgroup_destroy(key, self.name)
return resp | [
"def",
"destroy",
"(",
"self",
")",
":",
"resp",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"keys",
":",
"resp",
"[",
"key",
"]",
"=",
"self",
".",
"database",
".",
"xgroup_destroy",
"(",
"key",
",",
"self",
".",
"name",
")",
"return",
"resp... | Destroy the consumer group. | [
"Destroy",
"the",
"consumer",
"group",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1408-L1415 | train | 203,016 |
coleifer/walrus | walrus/containers.py | BitField.get | def get(self, fmt, offset):
"""
Get the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. u8 for an
unsigned 8-bit integer.
:param int offset: offset (in number of bits).
:returns: a :py:class:`BitFieldOperation` instance.
"""
bfo = BitFieldOperation(self.database, self.key)
return bfo.get(fmt, offset) | python | def get(self, fmt, offset):
"""
Get the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. u8 for an
unsigned 8-bit integer.
:param int offset: offset (in number of bits).
:returns: a :py:class:`BitFieldOperation` instance.
"""
bfo = BitFieldOperation(self.database, self.key)
return bfo.get(fmt, offset) | [
"def",
"get",
"(",
"self",
",",
"fmt",
",",
"offset",
")",
":",
"bfo",
"=",
"BitFieldOperation",
"(",
"self",
".",
"database",
",",
"self",
".",
"key",
")",
"return",
"bfo",
".",
"get",
"(",
"fmt",
",",
"offset",
")"
] | Get the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. u8 for an
unsigned 8-bit integer.
:param int offset: offset (in number of bits).
:returns: a :py:class:`BitFieldOperation` instance. | [
"Get",
"the",
"value",
"of",
"a",
"given",
"bitfield",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1558-L1568 | train | 203,017 |
coleifer/walrus | walrus/containers.py | BitField.set | def set(self, fmt, offset, value):
"""
Set the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. u8 for an
unsigned 8-bit integer.
:param int offset: offset (in number of bits).
:param int value: value to set at the given position.
:returns: a :py:class:`BitFieldOperation` instance.
"""
bfo = BitFieldOperation(self.database, self.key)
return bfo.set(fmt, offset, value) | python | def set(self, fmt, offset, value):
"""
Set the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. u8 for an
unsigned 8-bit integer.
:param int offset: offset (in number of bits).
:param int value: value to set at the given position.
:returns: a :py:class:`BitFieldOperation` instance.
"""
bfo = BitFieldOperation(self.database, self.key)
return bfo.set(fmt, offset, value) | [
"def",
"set",
"(",
"self",
",",
"fmt",
",",
"offset",
",",
"value",
")",
":",
"bfo",
"=",
"BitFieldOperation",
"(",
"self",
".",
"database",
",",
"self",
".",
"key",
")",
"return",
"bfo",
".",
"set",
"(",
"fmt",
",",
"offset",
",",
"value",
")"
] | Set the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. u8 for an
unsigned 8-bit integer.
:param int offset: offset (in number of bits).
:param int value: value to set at the given position.
:returns: a :py:class:`BitFieldOperation` instance. | [
"Set",
"the",
"value",
"of",
"a",
"given",
"bitfield",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1570-L1581 | train | 203,018 |
coleifer/walrus | walrus/containers.py | BloomFilter.add | def add(self, data):
"""
Add an item to the bloomfilter.
:param bytes data: a bytestring representing the item to add.
"""
bfo = BitFieldOperation(self.database, self.key)
for bit_index in self._get_seeds(data):
bfo.set('u1', bit_index, 1)
bfo.execute() | python | def add(self, data):
"""
Add an item to the bloomfilter.
:param bytes data: a bytestring representing the item to add.
"""
bfo = BitFieldOperation(self.database, self.key)
for bit_index in self._get_seeds(data):
bfo.set('u1', bit_index, 1)
bfo.execute() | [
"def",
"add",
"(",
"self",
",",
"data",
")",
":",
"bfo",
"=",
"BitFieldOperation",
"(",
"self",
".",
"database",
",",
"self",
".",
"key",
")",
"for",
"bit_index",
"in",
"self",
".",
"_get_seeds",
"(",
"data",
")",
":",
"bfo",
".",
"set",
"(",
"'u1'... | Add an item to the bloomfilter.
:param bytes data: a bytestring representing the item to add. | [
"Add",
"an",
"item",
"to",
"the",
"bloomfilter",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1690-L1699 | train | 203,019 |
coleifer/walrus | walrus/containers.py | BloomFilter.contains | def contains(self, data):
"""
Check if an item has been added to the bloomfilter.
:param bytes data: a bytestring representing the item to check.
:returns: a boolean indicating whether or not the item is present in
the bloomfilter. False-positives are possible, but a negative
return value is definitive.
"""
bfo = BitFieldOperation(self.database, self.key)
for bit_index in self._get_seeds(data):
bfo.get('u1', bit_index)
return all(bfo.execute()) | python | def contains(self, data):
"""
Check if an item has been added to the bloomfilter.
:param bytes data: a bytestring representing the item to check.
:returns: a boolean indicating whether or not the item is present in
the bloomfilter. False-positives are possible, but a negative
return value is definitive.
"""
bfo = BitFieldOperation(self.database, self.key)
for bit_index in self._get_seeds(data):
bfo.get('u1', bit_index)
return all(bfo.execute()) | [
"def",
"contains",
"(",
"self",
",",
"data",
")",
":",
"bfo",
"=",
"BitFieldOperation",
"(",
"self",
".",
"database",
",",
"self",
".",
"key",
")",
"for",
"bit_index",
"in",
"self",
".",
"_get_seeds",
"(",
"data",
")",
":",
"bfo",
".",
"get",
"(",
... | Check if an item has been added to the bloomfilter.
:param bytes data: a bytestring representing the item to check.
:returns: a boolean indicating whether or not the item is present in
the bloomfilter. False-positives are possible, but a negative
return value is definitive. | [
"Check",
"if",
"an",
"item",
"has",
"been",
"added",
"to",
"the",
"bloomfilter",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1701-L1713 | train | 203,020 |
coleifer/walrus | walrus/graph.py | Graph.store_many | def store_many(self, items):
"""
Store multiple subject-predicate-object triples in the database.
:param items: A list of (subj, pred, obj) 3-tuples.
"""
with self.walrus.atomic():
for item in items:
self.store(*item) | python | def store_many(self, items):
"""
Store multiple subject-predicate-object triples in the database.
:param items: A list of (subj, pred, obj) 3-tuples.
"""
with self.walrus.atomic():
for item in items:
self.store(*item) | [
"def",
"store_many",
"(",
"self",
",",
"items",
")",
":",
"with",
"self",
".",
"walrus",
".",
"atomic",
"(",
")",
":",
"for",
"item",
"in",
"items",
":",
"self",
".",
"store",
"(",
"*",
"item",
")"
] | Store multiple subject-predicate-object triples in the database.
:param items: A list of (subj, pred, obj) 3-tuples. | [
"Store",
"multiple",
"subject",
"-",
"predicate",
"-",
"object",
"triples",
"in",
"the",
"database",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/graph.py#L90-L98 | train | 203,021 |
coleifer/walrus | walrus/graph.py | Graph.delete | def delete(self, s, p, o):
"""Remove the given subj-pred-obj triple from the database."""
with self.walrus.atomic():
for key in self.keys_for_values(s, p, o):
del self._z[key] | python | def delete(self, s, p, o):
"""Remove the given subj-pred-obj triple from the database."""
with self.walrus.atomic():
for key in self.keys_for_values(s, p, o):
del self._z[key] | [
"def",
"delete",
"(",
"self",
",",
"s",
",",
"p",
",",
"o",
")",
":",
"with",
"self",
".",
"walrus",
".",
"atomic",
"(",
")",
":",
"for",
"key",
"in",
"self",
".",
"keys_for_values",
"(",
"s",
",",
"p",
",",
"o",
")",
":",
"del",
"self",
".",... | Remove the given subj-pred-obj triple from the database. | [
"Remove",
"the",
"given",
"subj",
"-",
"pred",
"-",
"obj",
"triple",
"from",
"the",
"database",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/graph.py#L100-L104 | train | 203,022 |
coleifer/walrus | walrus/graph.py | Graph.search | def search(self, *conditions):
"""
Given a set of conditions, return all values that satisfy the
conditions for a given set of variables.
For example, suppose I wanted to find all of my friends who live in
Kansas:
.. code-block:: python
X = graph.v.X
results = graph.search(
{'s': 'charlie', 'p': 'friends', 'o': X},
{'s': X, 'p': 'lives', 'o': 'Kansas'})
The return value consists of a dictionary keyed by variable, whose
values are ``set`` objects containing the values that satisfy the
query clauses, e.g.:
.. code-block:: python
print results
# Result has one key, for our "X" variable. The value is the set
# of my friends that live in Kansas.
# {'X': {'huey', 'nuggie'}}
# We can assume the following triples exist:
# ('charlie', 'friends', 'huey')
# ('charlie', 'friends', 'nuggie')
# ('huey', 'lives', 'Kansas')
# ('nuggie', 'lives', 'Kansas')
"""
results = {}
for condition in conditions:
if isinstance(condition, tuple):
query = dict(zip('spo', condition))
else:
query = condition.copy()
materialized = {}
targets = []
for part in ('s', 'p', 'o'):
if isinstance(query[part], Variable):
variable = query.pop(part)
materialized[part] = set()
targets.append((variable, part))
# Potentially rather than popping all the variables, we could use
# the result values from a previous condition and do O(results)
# loops looking for a single variable.
for result in self.query(**query):
ok = True
for var, part in targets:
if var in results and result[part] not in results[var]:
ok = False
break
if ok:
for var, part in targets:
materialized[part].add(result[part])
for var, part in targets:
if var in results:
results[var] &= materialized[part]
else:
results[var] = materialized[part]
return dict((var.name, vals) for (var, vals) in results.items()) | python | def search(self, *conditions):
"""
Given a set of conditions, return all values that satisfy the
conditions for a given set of variables.
For example, suppose I wanted to find all of my friends who live in
Kansas:
.. code-block:: python
X = graph.v.X
results = graph.search(
{'s': 'charlie', 'p': 'friends', 'o': X},
{'s': X, 'p': 'lives', 'o': 'Kansas'})
The return value consists of a dictionary keyed by variable, whose
values are ``set`` objects containing the values that satisfy the
query clauses, e.g.:
.. code-block:: python
print results
# Result has one key, for our "X" variable. The value is the set
# of my friends that live in Kansas.
# {'X': {'huey', 'nuggie'}}
# We can assume the following triples exist:
# ('charlie', 'friends', 'huey')
# ('charlie', 'friends', 'nuggie')
# ('huey', 'lives', 'Kansas')
# ('nuggie', 'lives', 'Kansas')
"""
results = {}
for condition in conditions:
if isinstance(condition, tuple):
query = dict(zip('spo', condition))
else:
query = condition.copy()
materialized = {}
targets = []
for part in ('s', 'p', 'o'):
if isinstance(query[part], Variable):
variable = query.pop(part)
materialized[part] = set()
targets.append((variable, part))
# Potentially rather than popping all the variables, we could use
# the result values from a previous condition and do O(results)
# loops looking for a single variable.
for result in self.query(**query):
ok = True
for var, part in targets:
if var in results and result[part] not in results[var]:
ok = False
break
if ok:
for var, part in targets:
materialized[part].add(result[part])
for var, part in targets:
if var in results:
results[var] &= materialized[part]
else:
results[var] = materialized[part]
return dict((var.name, vals) for (var, vals) in results.items()) | [
"def",
"search",
"(",
"self",
",",
"*",
"conditions",
")",
":",
"results",
"=",
"{",
"}",
"for",
"condition",
"in",
"conditions",
":",
"if",
"isinstance",
"(",
"condition",
",",
"tuple",
")",
":",
"query",
"=",
"dict",
"(",
"zip",
"(",
"'spo'",
",",
... | Given a set of conditions, return all values that satisfy the
conditions for a given set of variables.
For example, suppose I wanted to find all of my friends who live in
Kansas:
.. code-block:: python
X = graph.v.X
results = graph.search(
{'s': 'charlie', 'p': 'friends', 'o': X},
{'s': X, 'p': 'lives', 'o': 'Kansas'})
The return value consists of a dictionary keyed by variable, whose
values are ``set`` objects containing the values that satisfy the
query clauses, e.g.:
.. code-block:: python
print results
# Result has one key, for our "X" variable. The value is the set
# of my friends that live in Kansas.
# {'X': {'huey', 'nuggie'}}
# We can assume the following triples exist:
# ('charlie', 'friends', 'huey')
# ('charlie', 'friends', 'nuggie')
# ('huey', 'lives', 'Kansas')
# ('nuggie', 'lives', 'Kansas') | [
"Given",
"a",
"set",
"of",
"conditions",
"return",
"all",
"values",
"that",
"satisfy",
"the",
"conditions",
"for",
"a",
"given",
"set",
"of",
"variables",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/graph.py#L164-L233 | train | 203,023 |
coleifer/walrus | walrus/database.py | Database.run_script | def run_script(self, script_name, keys=None, args=None):
"""
Execute a walrus script with the given arguments.
:param script_name: The base name of the script to execute.
:param list keys: Keys referenced by the script.
:param list args: Arguments passed in to the script.
:returns: Return value of script.
.. note:: Redis scripts require two parameters, ``keys``
and ``args``, which are referenced in lua as ``KEYS``
and ``ARGV``.
"""
return self._scripts[script_name](keys, args) | python | def run_script(self, script_name, keys=None, args=None):
"""
Execute a walrus script with the given arguments.
:param script_name: The base name of the script to execute.
:param list keys: Keys referenced by the script.
:param list args: Arguments passed in to the script.
:returns: Return value of script.
.. note:: Redis scripts require two parameters, ``keys``
and ``args``, which are referenced in lua as ``KEYS``
and ``ARGV``.
"""
return self._scripts[script_name](keys, args) | [
"def",
"run_script",
"(",
"self",
",",
"script_name",
",",
"keys",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"return",
"self",
".",
"_scripts",
"[",
"script_name",
"]",
"(",
"keys",
",",
"args",
")"
] | Execute a walrus script with the given arguments.
:param script_name: The base name of the script to execute.
:param list keys: Keys referenced by the script.
:param list args: Arguments passed in to the script.
:returns: Return value of script.
.. note:: Redis scripts require two parameters, ``keys``
and ``args``, which are referenced in lua as ``KEYS``
and ``ARGV``. | [
"Execute",
"a",
"walrus",
"script",
"with",
"the",
"given",
"arguments",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/database.py#L150-L163 | train | 203,024 |
coleifer/walrus | walrus/database.py | Database.rate_limit | def rate_limit(self, name, limit=5, per=60, debug=False):
"""
Rate limit implementation. Allows up to `limit` of events every `per`
seconds.
See :ref:`rate-limit` for more information.
"""
return RateLimit(self, name, limit, per, debug) | python | def rate_limit(self, name, limit=5, per=60, debug=False):
"""
Rate limit implementation. Allows up to `limit` of events every `per`
seconds.
See :ref:`rate-limit` for more information.
"""
return RateLimit(self, name, limit, per, debug) | [
"def",
"rate_limit",
"(",
"self",
",",
"name",
",",
"limit",
"=",
"5",
",",
"per",
"=",
"60",
",",
"debug",
"=",
"False",
")",
":",
"return",
"RateLimit",
"(",
"self",
",",
"name",
",",
"limit",
",",
"per",
",",
"debug",
")"
] | Rate limit implementation. Allows up to `limit` of events every `per`
seconds.
See :ref:`rate-limit` for more information. | [
"Rate",
"limit",
"implementation",
".",
"Allows",
"up",
"to",
"limit",
"of",
"events",
"every",
"per",
"seconds",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/database.py#L250-L257 | train | 203,025 |
coleifer/walrus | walrus/database.py | Database.cas | def cas(self, key, value, new_value):
"""
Perform an atomic compare-and-set on the value in "key", using a prefix
match on the provided value.
"""
return self.run_script('cas', keys=[key], args=[value, new_value]) | python | def cas(self, key, value, new_value):
"""
Perform an atomic compare-and-set on the value in "key", using a prefix
match on the provided value.
"""
return self.run_script('cas', keys=[key], args=[value, new_value]) | [
"def",
"cas",
"(",
"self",
",",
"key",
",",
"value",
",",
"new_value",
")",
":",
"return",
"self",
".",
"run_script",
"(",
"'cas'",
",",
"keys",
"=",
"[",
"key",
"]",
",",
"args",
"=",
"[",
"value",
",",
"new_value",
"]",
")"
] | Perform an atomic compare-and-set on the value in "key", using a prefix
match on the provided value. | [
"Perform",
"an",
"atomic",
"compare",
"-",
"and",
"-",
"set",
"on",
"the",
"value",
"in",
"key",
"using",
"a",
"prefix",
"match",
"on",
"the",
"provided",
"value",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/database.py#L365-L370 | train | 203,026 |
coleifer/walrus | walrus/database.py | Database.listener | def listener(self, channels=None, patterns=None, is_async=False):
"""
Decorator for wrapping functions used to listen for Redis
pub-sub messages.
The listener will listen until the decorated function
raises a ``StopIteration`` exception.
:param list channels: Channels to listen on.
:param list patterns: Patterns to match.
:param bool is_async: Whether to start the listener in a
separate thread.
"""
def decorator(fn):
_channels = channels or []
_patterns = patterns or []
@wraps(fn)
def inner():
pubsub = self.pubsub()
def listen():
for channel in _channels:
pubsub.subscribe(channel)
for pattern in _patterns:
pubsub.psubscribe(pattern)
for data_dict in pubsub.listen():
try:
ret = fn(**data_dict)
except StopIteration:
pubsub.close()
break
if is_async:
worker = threading.Thread(target=listen)
worker.start()
return worker
else:
listen()
return inner
return decorator | python | def listener(self, channels=None, patterns=None, is_async=False):
"""
Decorator for wrapping functions used to listen for Redis
pub-sub messages.
The listener will listen until the decorated function
raises a ``StopIteration`` exception.
:param list channels: Channels to listen on.
:param list patterns: Patterns to match.
:param bool is_async: Whether to start the listener in a
separate thread.
"""
def decorator(fn):
_channels = channels or []
_patterns = patterns or []
@wraps(fn)
def inner():
pubsub = self.pubsub()
def listen():
for channel in _channels:
pubsub.subscribe(channel)
for pattern in _patterns:
pubsub.psubscribe(pattern)
for data_dict in pubsub.listen():
try:
ret = fn(**data_dict)
except StopIteration:
pubsub.close()
break
if is_async:
worker = threading.Thread(target=listen)
worker.start()
return worker
else:
listen()
return inner
return decorator | [
"def",
"listener",
"(",
"self",
",",
"channels",
"=",
"None",
",",
"patterns",
"=",
"None",
",",
"is_async",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"_channels",
"=",
"channels",
"or",
"[",
"]",
"_patterns",
"=",
"patterns",
... | Decorator for wrapping functions used to listen for Redis
pub-sub messages.
The listener will listen until the decorated function
raises a ``StopIteration`` exception.
:param list channels: Channels to listen on.
:param list patterns: Patterns to match.
:param bool is_async: Whether to start the listener in a
separate thread. | [
"Decorator",
"for",
"wrapping",
"functions",
"used",
"to",
"listen",
"for",
"Redis",
"pub",
"-",
"sub",
"messages",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/database.py#L372-L414 | train | 203,027 |
coleifer/walrus | walrus/database.py | Database.stream_log | def stream_log(self, callback, connection_id='monitor'):
"""
Stream Redis activity one line at a time to the given
callback.
:param callback: A function that accepts a single argument,
the Redis command.
"""
conn = self.connection_pool.get_connection(connection_id, None)
conn.send_command('monitor')
while callback(conn.read_response()):
pass | python | def stream_log(self, callback, connection_id='monitor'):
"""
Stream Redis activity one line at a time to the given
callback.
:param callback: A function that accepts a single argument,
the Redis command.
"""
conn = self.connection_pool.get_connection(connection_id, None)
conn.send_command('monitor')
while callback(conn.read_response()):
pass | [
"def",
"stream_log",
"(",
"self",
",",
"callback",
",",
"connection_id",
"=",
"'monitor'",
")",
":",
"conn",
"=",
"self",
".",
"connection_pool",
".",
"get_connection",
"(",
"connection_id",
",",
"None",
")",
"conn",
".",
"send_command",
"(",
"'monitor'",
")... | Stream Redis activity one line at a time to the given
callback.
:param callback: A function that accepts a single argument,
the Redis command. | [
"Stream",
"Redis",
"activity",
"one",
"line",
"at",
"a",
"time",
"to",
"the",
"given",
"callback",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/database.py#L416-L427 | train | 203,028 |
coleifer/walrus | walrus/models.py | Query.make_key | def make_key(self, *parts):
"""Generate a namespaced key for the given path."""
separator = getattr(self.model_class, 'index_separator', '.')
parts = map(decode, parts)
return '%s%s' % (self._base_key, separator.join(map(str, parts))) | python | def make_key(self, *parts):
"""Generate a namespaced key for the given path."""
separator = getattr(self.model_class, 'index_separator', '.')
parts = map(decode, parts)
return '%s%s' % (self._base_key, separator.join(map(str, parts))) | [
"def",
"make_key",
"(",
"self",
",",
"*",
"parts",
")",
":",
"separator",
"=",
"getattr",
"(",
"self",
".",
"model_class",
",",
"'index_separator'",
",",
"'.'",
")",
"parts",
"=",
"map",
"(",
"decode",
",",
"parts",
")",
"return",
"'%s%s'",
"%",
"(",
... | Generate a namespaced key for the given path. | [
"Generate",
"a",
"namespaced",
"key",
"for",
"the",
"given",
"path",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/models.py#L369-L373 | train | 203,029 |
coleifer/walrus | walrus/models.py | Model.get | def get(cls, expression):
"""
Retrieve the model instance matching the given expression.
If the number of matching results is not equal to one, then
a ``ValueError`` will be raised.
:param expression: A boolean expression to filter by.
:returns: The matching :py:class:`Model` instance.
:raises: ``ValueError`` if result set size is not 1.
"""
executor = Executor(cls.__database__)
result = executor.execute(expression)
if len(result) != 1:
raise ValueError('Got %s results, expected 1.' % len(result))
return cls.load(result._first_or_any(), convert_key=False) | python | def get(cls, expression):
"""
Retrieve the model instance matching the given expression.
If the number of matching results is not equal to one, then
a ``ValueError`` will be raised.
:param expression: A boolean expression to filter by.
:returns: The matching :py:class:`Model` instance.
:raises: ``ValueError`` if result set size is not 1.
"""
executor = Executor(cls.__database__)
result = executor.execute(expression)
if len(result) != 1:
raise ValueError('Got %s results, expected 1.' % len(result))
return cls.load(result._first_or_any(), convert_key=False) | [
"def",
"get",
"(",
"cls",
",",
"expression",
")",
":",
"executor",
"=",
"Executor",
"(",
"cls",
".",
"__database__",
")",
"result",
"=",
"executor",
".",
"execute",
"(",
"expression",
")",
"if",
"len",
"(",
"result",
")",
"!=",
"1",
":",
"raise",
"Va... | Retrieve the model instance matching the given expression.
If the number of matching results is not equal to one, then
a ``ValueError`` will be raised.
:param expression: A boolean expression to filter by.
:returns: The matching :py:class:`Model` instance.
:raises: ``ValueError`` if result set size is not 1. | [
"Retrieve",
"the",
"model",
"instance",
"matching",
"the",
"given",
"expression",
".",
"If",
"the",
"number",
"of",
"matching",
"results",
"is",
"not",
"equal",
"to",
"one",
"then",
"a",
"ValueError",
"will",
"be",
"raised",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/models.py#L770-L784 | train | 203,030 |
coleifer/walrus | walrus/models.py | Model.load | def load(cls, primary_key, convert_key=True):
"""
Retrieve a model instance by primary key.
:param primary_key: The primary key of the model instance.
:returns: Corresponding :py:class:`Model` instance.
:raises: ``KeyError`` if object with given primary key does
not exist.
"""
if convert_key:
primary_key = cls._query.get_primary_hash_key(primary_key)
if not cls.__database__.hash_exists(primary_key):
raise KeyError('Object not found.')
raw_data = cls.__database__.hgetall(primary_key)
if PY3:
raw_data = decode_dict_keys(raw_data)
data = {}
for name, field in cls._fields.items():
if isinstance(field, _ContainerField):
continue
elif name in raw_data:
data[name] = field.python_value(raw_data[name])
else:
data[name] = None
return cls(**data) | python | def load(cls, primary_key, convert_key=True):
"""
Retrieve a model instance by primary key.
:param primary_key: The primary key of the model instance.
:returns: Corresponding :py:class:`Model` instance.
:raises: ``KeyError`` if object with given primary key does
not exist.
"""
if convert_key:
primary_key = cls._query.get_primary_hash_key(primary_key)
if not cls.__database__.hash_exists(primary_key):
raise KeyError('Object not found.')
raw_data = cls.__database__.hgetall(primary_key)
if PY3:
raw_data = decode_dict_keys(raw_data)
data = {}
for name, field in cls._fields.items():
if isinstance(field, _ContainerField):
continue
elif name in raw_data:
data[name] = field.python_value(raw_data[name])
else:
data[name] = None
return cls(**data) | [
"def",
"load",
"(",
"cls",
",",
"primary_key",
",",
"convert_key",
"=",
"True",
")",
":",
"if",
"convert_key",
":",
"primary_key",
"=",
"cls",
".",
"_query",
".",
"get_primary_hash_key",
"(",
"primary_key",
")",
"if",
"not",
"cls",
".",
"__database__",
"."... | Retrieve a model instance by primary key.
:param primary_key: The primary key of the model instance.
:returns: Corresponding :py:class:`Model` instance.
:raises: ``KeyError`` if object with given primary key does
not exist. | [
"Retrieve",
"a",
"model",
"instance",
"by",
"primary",
"key",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/models.py#L787-L812 | train | 203,031 |
coleifer/walrus | walrus/models.py | Model.delete | def delete(self, for_update=False):
"""
Delete the given model instance.
"""
hash_key = self.get_hash_id()
try:
original_instance = self.load(hash_key, convert_key=False)
except KeyError:
return
# Remove from the `all` index.
all_index = self._query.all_index()
all_index.remove(hash_key)
# Remove from the secondary indexes.
for field in self._indexes:
for index in field.get_indexes():
index.remove(original_instance)
if not for_update:
for field in self._fields.values():
if isinstance(field, _ContainerField):
field._delete(self)
# Remove the object itself.
self.__database__.delete(hash_key) | python | def delete(self, for_update=False):
"""
Delete the given model instance.
"""
hash_key = self.get_hash_id()
try:
original_instance = self.load(hash_key, convert_key=False)
except KeyError:
return
# Remove from the `all` index.
all_index = self._query.all_index()
all_index.remove(hash_key)
# Remove from the secondary indexes.
for field in self._indexes:
for index in field.get_indexes():
index.remove(original_instance)
if not for_update:
for field in self._fields.values():
if isinstance(field, _ContainerField):
field._delete(self)
# Remove the object itself.
self.__database__.delete(hash_key) | [
"def",
"delete",
"(",
"self",
",",
"for_update",
"=",
"False",
")",
":",
"hash_key",
"=",
"self",
".",
"get_hash_id",
"(",
")",
"try",
":",
"original_instance",
"=",
"self",
".",
"load",
"(",
"hash_key",
",",
"convert_key",
"=",
"False",
")",
"except",
... | Delete the given model instance. | [
"Delete",
"the",
"given",
"model",
"instance",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/models.py#L821-L846 | train | 203,032 |
coleifer/walrus | walrus/rate_limit.py | RateLimit.limit | def limit(self, key):
"""
Function to log an event with the given key. If the ``key`` has not
exceeded their alotted events, then the function returns ``False`` to
indicate that no limit is being imposed.
If the ``key`` has exceeded the number of events, then the function
returns ``True`` indicating rate-limiting should occur.
:param str key: A key identifying the source of the event.
:returns: Boolean indicating whether the event should be rate-limited
or not.
"""
if self._debug:
return False
counter = self.database.List(self.name + ':' + key)
n = len(counter)
is_limited = False
if n < self._limit:
counter.prepend(str(time.time()))
else:
oldest = float(counter[-1])
if time.time() - oldest < self._per:
is_limited = True
else:
counter.prepend(str(time.time()))
del counter[:self._limit]
counter.pexpire(int(self._per * 2000))
return is_limited | python | def limit(self, key):
"""
Function to log an event with the given key. If the ``key`` has not
exceeded their alotted events, then the function returns ``False`` to
indicate that no limit is being imposed.
If the ``key`` has exceeded the number of events, then the function
returns ``True`` indicating rate-limiting should occur.
:param str key: A key identifying the source of the event.
:returns: Boolean indicating whether the event should be rate-limited
or not.
"""
if self._debug:
return False
counter = self.database.List(self.name + ':' + key)
n = len(counter)
is_limited = False
if n < self._limit:
counter.prepend(str(time.time()))
else:
oldest = float(counter[-1])
if time.time() - oldest < self._per:
is_limited = True
else:
counter.prepend(str(time.time()))
del counter[:self._limit]
counter.pexpire(int(self._per * 2000))
return is_limited | [
"def",
"limit",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"_debug",
":",
"return",
"False",
"counter",
"=",
"self",
".",
"database",
".",
"List",
"(",
"self",
".",
"name",
"+",
"':'",
"+",
"key",
")",
"n",
"=",
"len",
"(",
"counter",
... | Function to log an event with the given key. If the ``key`` has not
exceeded their alotted events, then the function returns ``False`` to
indicate that no limit is being imposed.
If the ``key`` has exceeded the number of events, then the function
returns ``True`` indicating rate-limiting should occur.
:param str key: A key identifying the source of the event.
:returns: Boolean indicating whether the event should be rate-limited
or not. | [
"Function",
"to",
"log",
"an",
"event",
"with",
"the",
"given",
"key",
".",
"If",
"the",
"key",
"has",
"not",
"exceeded",
"their",
"alotted",
"events",
"then",
"the",
"function",
"returns",
"False",
"to",
"indicate",
"that",
"no",
"limit",
"is",
"being",
... | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/rate_limit.py#L31-L60 | train | 203,033 |
coleifer/walrus | walrus/rate_limit.py | RateLimit.rate_limited | def rate_limited(self, key_function=None):
"""
Function or method decorator that will prevent calls to the decorated
function when the number of events has been exceeded for the given
time period.
It is probably important that you take care to choose an appropiate
key function. For instance, if rate-limiting a web-page you might use
the requesting user's IP as the key.
If the number of allowed events has been exceedd, a
``RateLimitException`` will be raised.
:param key_function: Function that accepts the params of the decorated
function and returns a string key. If not provided, a hash of the
args and kwargs will be used.
:returns: If the call is not rate-limited, then the return value will
be that of the decorated function.
:raises: ``RateLimitException``.
"""
if key_function is None:
def key_function(*args, **kwargs):
data = pickle.dumps((args, sorted(kwargs.items())))
return hashlib.md5(data).hexdigest()
def decorator(fn):
@wraps(fn)
def inner(*args, **kwargs):
key = key_function(*args, **kwargs)
if self.limit(key):
raise RateLimitException(
'Call to %s exceeded %s events in %s seconds.' % (
fn.__name__, self._limit, self._per))
return fn(*args, **kwargs)
return inner
return decorator | python | def rate_limited(self, key_function=None):
"""
Function or method decorator that will prevent calls to the decorated
function when the number of events has been exceeded for the given
time period.
It is probably important that you take care to choose an appropiate
key function. For instance, if rate-limiting a web-page you might use
the requesting user's IP as the key.
If the number of allowed events has been exceedd, a
``RateLimitException`` will be raised.
:param key_function: Function that accepts the params of the decorated
function and returns a string key. If not provided, a hash of the
args and kwargs will be used.
:returns: If the call is not rate-limited, then the return value will
be that of the decorated function.
:raises: ``RateLimitException``.
"""
if key_function is None:
def key_function(*args, **kwargs):
data = pickle.dumps((args, sorted(kwargs.items())))
return hashlib.md5(data).hexdigest()
def decorator(fn):
@wraps(fn)
def inner(*args, **kwargs):
key = key_function(*args, **kwargs)
if self.limit(key):
raise RateLimitException(
'Call to %s exceeded %s events in %s seconds.' % (
fn.__name__, self._limit, self._per))
return fn(*args, **kwargs)
return inner
return decorator | [
"def",
"rate_limited",
"(",
"self",
",",
"key_function",
"=",
"None",
")",
":",
"if",
"key_function",
"is",
"None",
":",
"def",
"key_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"pickle",
".",
"dumps",
"(",
"(",
"args"... | Function or method decorator that will prevent calls to the decorated
function when the number of events has been exceeded for the given
time period.
It is probably important that you take care to choose an appropiate
key function. For instance, if rate-limiting a web-page you might use
the requesting user's IP as the key.
If the number of allowed events has been exceedd, a
``RateLimitException`` will be raised.
:param key_function: Function that accepts the params of the decorated
function and returns a string key. If not provided, a hash of the
args and kwargs will be used.
:returns: If the call is not rate-limited, then the return value will
be that of the decorated function.
:raises: ``RateLimitException``. | [
"Function",
"or",
"method",
"decorator",
"that",
"will",
"prevent",
"calls",
"to",
"the",
"decorated",
"function",
"when",
"the",
"number",
"of",
"events",
"has",
"been",
"exceeded",
"for",
"the",
"given",
"time",
"period",
"."
] | 82bf15a6613487b5b5fefeb488f186d7e0106547 | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/rate_limit.py#L62-L97 | train | 203,034 |
TomAugspurger/engarde | engarde/checks.py | is_monotonic | def is_monotonic(df, items=None, increasing=None, strict=False):
"""
Asserts that the DataFrame is monotonic.
Parameters
==========
df : Series or DataFrame
items : dict
mapping columns to conditions (increasing, strict)
increasing : None or bool
None is either increasing or decreasing.
strict : whether the comparison should be strict
Returns
=======
df : DataFrame
"""
if items is None:
items = {k: (increasing, strict) for k in df}
for col, (increasing, strict) in items.items():
s = pd.Index(df[col])
if increasing:
good = getattr(s, 'is_monotonic_increasing')
elif increasing is None:
good = getattr(s, 'is_monotonic') | getattr(s, 'is_monotonic_decreasing')
else:
good = getattr(s, 'is_monotonic_decreasing')
if strict:
if increasing:
good = good & (s.to_series().diff().dropna() > 0).all()
elif increasing is None:
good = good & ((s.to_series().diff().dropna() > 0).all() |
(s.to_series().diff().dropna() < 0).all())
else:
good = good & (s.to_series().diff().dropna() < 0).all()
if not good:
raise AssertionError
return df | python | def is_monotonic(df, items=None, increasing=None, strict=False):
"""
Asserts that the DataFrame is monotonic.
Parameters
==========
df : Series or DataFrame
items : dict
mapping columns to conditions (increasing, strict)
increasing : None or bool
None is either increasing or decreasing.
strict : whether the comparison should be strict
Returns
=======
df : DataFrame
"""
if items is None:
items = {k: (increasing, strict) for k in df}
for col, (increasing, strict) in items.items():
s = pd.Index(df[col])
if increasing:
good = getattr(s, 'is_monotonic_increasing')
elif increasing is None:
good = getattr(s, 'is_monotonic') | getattr(s, 'is_monotonic_decreasing')
else:
good = getattr(s, 'is_monotonic_decreasing')
if strict:
if increasing:
good = good & (s.to_series().diff().dropna() > 0).all()
elif increasing is None:
good = good & ((s.to_series().diff().dropna() > 0).all() |
(s.to_series().diff().dropna() < 0).all())
else:
good = good & (s.to_series().diff().dropna() < 0).all()
if not good:
raise AssertionError
return df | [
"def",
"is_monotonic",
"(",
"df",
",",
"items",
"=",
"None",
",",
"increasing",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"if",
"items",
"is",
"None",
":",
"items",
"=",
"{",
"k",
":",
"(",
"increasing",
",",
"strict",
")",
"for",
"k",
... | Asserts that the DataFrame is monotonic.
Parameters
==========
df : Series or DataFrame
items : dict
mapping columns to conditions (increasing, strict)
increasing : None or bool
None is either increasing or decreasing.
strict : whether the comparison should be strict
Returns
=======
df : DataFrame | [
"Asserts",
"that",
"the",
"DataFrame",
"is",
"monotonic",
"."
] | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L46-L85 | train | 203,035 |
TomAugspurger/engarde | engarde/checks.py | is_shape | def is_shape(df, shape):
"""
Asserts that the DataFrame is of a known shape.
Parameters
==========
df : DataFrame
shape : tuple
(n_rows, n_columns). Use None or -1 if you don't care
about a dimension.
Returns
=======
df : DataFrame
"""
try:
check = np.all(np.equal(df.shape, shape) | (np.equal(shape, [-1, -1]) |
np.equal(shape, [None, None])))
assert check
except AssertionError as e:
msg = ("Expected shape: {}\n"
"\t\tActual shape: {}".format(shape, df.shape))
e.args = (msg,)
raise
return df | python | def is_shape(df, shape):
"""
Asserts that the DataFrame is of a known shape.
Parameters
==========
df : DataFrame
shape : tuple
(n_rows, n_columns). Use None or -1 if you don't care
about a dimension.
Returns
=======
df : DataFrame
"""
try:
check = np.all(np.equal(df.shape, shape) | (np.equal(shape, [-1, -1]) |
np.equal(shape, [None, None])))
assert check
except AssertionError as e:
msg = ("Expected shape: {}\n"
"\t\tActual shape: {}".format(shape, df.shape))
e.args = (msg,)
raise
return df | [
"def",
"is_shape",
"(",
"df",
",",
"shape",
")",
":",
"try",
":",
"check",
"=",
"np",
".",
"all",
"(",
"np",
".",
"equal",
"(",
"df",
".",
"shape",
",",
"shape",
")",
"|",
"(",
"np",
".",
"equal",
"(",
"shape",
",",
"[",
"-",
"1",
",",
"-",... | Asserts that the DataFrame is of a known shape.
Parameters
==========
df : DataFrame
shape : tuple
(n_rows, n_columns). Use None or -1 if you don't care
about a dimension.
Returns
=======
df : DataFrame | [
"Asserts",
"that",
"the",
"DataFrame",
"is",
"of",
"a",
"known",
"shape",
"."
] | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L87-L112 | train | 203,036 |
TomAugspurger/engarde | engarde/checks.py | unique | def unique(df, columns=None):
"""
Asserts that columns in the DataFrame only have unique values.
Parameters
----------
df : DataFrame
columns : list
list of columns to restrict the check to. If None, check all columns.
Returns
-------
df : DataFrame
same as the original
"""
if columns is None:
columns = df.columns
for col in columns:
if not df[col].is_unique:
raise AssertionError("Column {!r} contains non-unique values".format(col))
return df | python | def unique(df, columns=None):
"""
Asserts that columns in the DataFrame only have unique values.
Parameters
----------
df : DataFrame
columns : list
list of columns to restrict the check to. If None, check all columns.
Returns
-------
df : DataFrame
same as the original
"""
if columns is None:
columns = df.columns
for col in columns:
if not df[col].is_unique:
raise AssertionError("Column {!r} contains non-unique values".format(col))
return df | [
"def",
"unique",
"(",
"df",
",",
"columns",
"=",
"None",
")",
":",
"if",
"columns",
"is",
"None",
":",
"columns",
"=",
"df",
".",
"columns",
"for",
"col",
"in",
"columns",
":",
"if",
"not",
"df",
"[",
"col",
"]",
".",
"is_unique",
":",
"raise",
"... | Asserts that columns in the DataFrame only have unique values.
Parameters
----------
df : DataFrame
columns : list
list of columns to restrict the check to. If None, check all columns.
Returns
-------
df : DataFrame
same as the original | [
"Asserts",
"that",
"columns",
"in",
"the",
"DataFrame",
"only",
"have",
"unique",
"values",
"."
] | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L115-L135 | train | 203,037 |
TomAugspurger/engarde | engarde/checks.py | unique_index | def unique_index(df):
"""
Assert that the index is unique
Parameters
==========
df : DataFrame
Returns
=======
df : DataFrame
"""
try:
assert df.index.is_unique
except AssertionError as e:
e.args = df.index.get_duplicates()
raise
return df | python | def unique_index(df):
"""
Assert that the index is unique
Parameters
==========
df : DataFrame
Returns
=======
df : DataFrame
"""
try:
assert df.index.is_unique
except AssertionError as e:
e.args = df.index.get_duplicates()
raise
return df | [
"def",
"unique_index",
"(",
"df",
")",
":",
"try",
":",
"assert",
"df",
".",
"index",
".",
"is_unique",
"except",
"AssertionError",
"as",
"e",
":",
"e",
".",
"args",
"=",
"df",
".",
"index",
".",
"get_duplicates",
"(",
")",
"raise",
"return",
"df"
] | Assert that the index is unique
Parameters
==========
df : DataFrame
Returns
=======
df : DataFrame | [
"Assert",
"that",
"the",
"index",
"is",
"unique"
] | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L138-L155 | train | 203,038 |
TomAugspurger/engarde | engarde/checks.py | within_n_std | def within_n_std(df, n=3):
"""
Assert that every value is within ``n`` standard
deviations of its column's mean.
Parameters
==========
df : DataFame
n : int
number of standard deviations from the mean
Returns
=======
df : DataFrame
"""
means = df.mean()
stds = df.std()
inliers = (np.abs(df[means.index] - means) < n * stds)
if not np.all(inliers):
msg = generic.bad_locations(~inliers)
raise AssertionError(msg)
return df | python | def within_n_std(df, n=3):
"""
Assert that every value is within ``n`` standard
deviations of its column's mean.
Parameters
==========
df : DataFame
n : int
number of standard deviations from the mean
Returns
=======
df : DataFrame
"""
means = df.mean()
stds = df.std()
inliers = (np.abs(df[means.index] - means) < n * stds)
if not np.all(inliers):
msg = generic.bad_locations(~inliers)
raise AssertionError(msg)
return df | [
"def",
"within_n_std",
"(",
"df",
",",
"n",
"=",
"3",
")",
":",
"means",
"=",
"df",
".",
"mean",
"(",
")",
"stds",
"=",
"df",
".",
"std",
"(",
")",
"inliers",
"=",
"(",
"np",
".",
"abs",
"(",
"df",
"[",
"means",
".",
"index",
"]",
"-",
"mea... | Assert that every value is within ``n`` standard
deviations of its column's mean.
Parameters
==========
df : DataFame
n : int
number of standard deviations from the mean
Returns
=======
df : DataFrame | [
"Assert",
"that",
"every",
"value",
"is",
"within",
"n",
"standard",
"deviations",
"of",
"its",
"column",
"s",
"mean",
"."
] | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L200-L221 | train | 203,039 |
TomAugspurger/engarde | engarde/checks.py | has_dtypes | def has_dtypes(df, items):
"""
Assert that a DataFrame has ``dtypes``
Parameters
==========
df: DataFrame
items: dict
mapping of columns to dtype.
Returns
=======
df : DataFrame
"""
dtypes = df.dtypes
for k, v in items.items():
if not dtypes[k] == v:
raise AssertionError("{} has the wrong dtype. Should be ({}), is ({})".format(k, v,dtypes[k]))
return df | python | def has_dtypes(df, items):
"""
Assert that a DataFrame has ``dtypes``
Parameters
==========
df: DataFrame
items: dict
mapping of columns to dtype.
Returns
=======
df : DataFrame
"""
dtypes = df.dtypes
for k, v in items.items():
if not dtypes[k] == v:
raise AssertionError("{} has the wrong dtype. Should be ({}), is ({})".format(k, v,dtypes[k]))
return df | [
"def",
"has_dtypes",
"(",
"df",
",",
"items",
")",
":",
"dtypes",
"=",
"df",
".",
"dtypes",
"for",
"k",
",",
"v",
"in",
"items",
".",
"items",
"(",
")",
":",
"if",
"not",
"dtypes",
"[",
"k",
"]",
"==",
"v",
":",
"raise",
"AssertionError",
"(",
... | Assert that a DataFrame has ``dtypes``
Parameters
==========
df: DataFrame
items: dict
mapping of columns to dtype.
Returns
=======
df : DataFrame | [
"Assert",
"that",
"a",
"DataFrame",
"has",
"dtypes"
] | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L223-L241 | train | 203,040 |
TomAugspurger/engarde | engarde/checks.py | one_to_many | def one_to_many(df, unitcol, manycol):
"""
Assert that a many-to-one relationship is preserved between two
columns. For example, a retail store will have have distinct
departments, each with several employees. If each employee may
only work in a single department, then the relationship of the
department to the employees is one to many.
Parameters
==========
df : DataFrame
unitcol : str
The column that encapulates the groups in ``manycol``.
manycol : str
The column that must remain unique in the distict pairs
between ``manycol`` and ``unitcol``
Returns
=======
df : DataFrame
"""
subset = df[[manycol, unitcol]].drop_duplicates()
for many in subset[manycol].unique():
if subset[subset[manycol] == many].shape[0] > 1:
msg = "{} in {} has multiple values for {}".format(many, manycol, unitcol)
raise AssertionError(msg)
return df | python | def one_to_many(df, unitcol, manycol):
"""
Assert that a many-to-one relationship is preserved between two
columns. For example, a retail store will have have distinct
departments, each with several employees. If each employee may
only work in a single department, then the relationship of the
department to the employees is one to many.
Parameters
==========
df : DataFrame
unitcol : str
The column that encapulates the groups in ``manycol``.
manycol : str
The column that must remain unique in the distict pairs
between ``manycol`` and ``unitcol``
Returns
=======
df : DataFrame
"""
subset = df[[manycol, unitcol]].drop_duplicates()
for many in subset[manycol].unique():
if subset[subset[manycol] == many].shape[0] > 1:
msg = "{} in {} has multiple values for {}".format(many, manycol, unitcol)
raise AssertionError(msg)
return df | [
"def",
"one_to_many",
"(",
"df",
",",
"unitcol",
",",
"manycol",
")",
":",
"subset",
"=",
"df",
"[",
"[",
"manycol",
",",
"unitcol",
"]",
"]",
".",
"drop_duplicates",
"(",
")",
"for",
"many",
"in",
"subset",
"[",
"manycol",
"]",
".",
"unique",
"(",
... | Assert that a many-to-one relationship is preserved between two
columns. For example, a retail store will have have distinct
departments, each with several employees. If each employee may
only work in a single department, then the relationship of the
department to the employees is one to many.
Parameters
==========
df : DataFrame
unitcol : str
The column that encapulates the groups in ``manycol``.
manycol : str
The column that must remain unique in the distict pairs
between ``manycol`` and ``unitcol``
Returns
=======
df : DataFrame | [
"Assert",
"that",
"a",
"many",
"-",
"to",
"-",
"one",
"relationship",
"is",
"preserved",
"between",
"two",
"columns",
".",
"For",
"example",
"a",
"retail",
"store",
"will",
"have",
"have",
"distinct",
"departments",
"each",
"with",
"several",
"employees",
".... | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L244-L272 | train | 203,041 |
TomAugspurger/engarde | engarde/checks.py | is_same_as | def is_same_as(df, df_to_compare, **kwargs):
"""
Assert that two pandas dataframes are the equal
Parameters
==========
df : pandas DataFrame
df_to_compare : pandas DataFrame
**kwargs : dict
keyword arguments passed through to panda's ``assert_frame_equal``
Returns
=======
df : DataFrame
"""
try:
tm.assert_frame_equal(df, df_to_compare, **kwargs)
except AssertionError as exc:
six.raise_from(AssertionError("DataFrames are not equal"), exc)
return df | python | def is_same_as(df, df_to_compare, **kwargs):
"""
Assert that two pandas dataframes are the equal
Parameters
==========
df : pandas DataFrame
df_to_compare : pandas DataFrame
**kwargs : dict
keyword arguments passed through to panda's ``assert_frame_equal``
Returns
=======
df : DataFrame
"""
try:
tm.assert_frame_equal(df, df_to_compare, **kwargs)
except AssertionError as exc:
six.raise_from(AssertionError("DataFrames are not equal"), exc)
return df | [
"def",
"is_same_as",
"(",
"df",
",",
"df_to_compare",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"tm",
".",
"assert_frame_equal",
"(",
"df",
",",
"df_to_compare",
",",
"*",
"*",
"kwargs",
")",
"except",
"AssertionError",
"as",
"exc",
":",
"six",
".... | Assert that two pandas dataframes are the equal
Parameters
==========
df : pandas DataFrame
df_to_compare : pandas DataFrame
**kwargs : dict
keyword arguments passed through to panda's ``assert_frame_equal``
Returns
=======
df : DataFrame | [
"Assert",
"that",
"two",
"pandas",
"dataframes",
"are",
"the",
"equal"
] | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L275-L295 | train | 203,042 |
TomAugspurger/engarde | docs/sphinxext/ipython_directive.py | EmbeddedSphinxShell.ensure_pyplot | def ensure_pyplot(self):
"""
Ensures that pyplot has been imported into the embedded IPython shell.
Also, makes sure to set the backend appropriately if not set already.
"""
# We are here if the @figure pseudo decorator was used. Thus, it's
# possible that we could be here even if python_mplbackend were set to
# `None`. That's also strange and perhaps worthy of raising an
# exception, but for now, we just set the backend to 'agg'.
if not self._pyplot_imported:
if 'matplotlib.backends' not in sys.modules:
# Then ipython_matplotlib was set to None but there was a
# call to the @figure decorator (and ipython_execlines did
# not set a backend).
#raise Exception("No backend was set, but @figure was used!")
import matplotlib
matplotlib.use('agg')
# Always import pyplot into embedded shell.
self.process_input_line('import matplotlib.pyplot as plt',
store_history=False)
self._pyplot_imported = True | python | def ensure_pyplot(self):
"""
Ensures that pyplot has been imported into the embedded IPython shell.
Also, makes sure to set the backend appropriately if not set already.
"""
# We are here if the @figure pseudo decorator was used. Thus, it's
# possible that we could be here even if python_mplbackend were set to
# `None`. That's also strange and perhaps worthy of raising an
# exception, but for now, we just set the backend to 'agg'.
if not self._pyplot_imported:
if 'matplotlib.backends' not in sys.modules:
# Then ipython_matplotlib was set to None but there was a
# call to the @figure decorator (and ipython_execlines did
# not set a backend).
#raise Exception("No backend was set, but @figure was used!")
import matplotlib
matplotlib.use('agg')
# Always import pyplot into embedded shell.
self.process_input_line('import matplotlib.pyplot as plt',
store_history=False)
self._pyplot_imported = True | [
"def",
"ensure_pyplot",
"(",
"self",
")",
":",
"# We are here if the @figure pseudo decorator was used. Thus, it's",
"# possible that we could be here even if python_mplbackend were set to",
"# `None`. That's also strange and perhaps worthy of raising an",
"# exception, but for now, we just set th... | Ensures that pyplot has been imported into the embedded IPython shell.
Also, makes sure to set the backend appropriately if not set already. | [
"Ensures",
"that",
"pyplot",
"has",
"been",
"imported",
"into",
"the",
"embedded",
"IPython",
"shell",
"."
] | e7ea040cf0d20aee7ca4375b8c27caa2d9e43945 | https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/docs/sphinxext/ipython_directive.py#L610-L634 | train | 203,043 |
slimkrazy/python-google-places | googleplaces/__init__.py | _fetch_remote_json | def _fetch_remote_json(service_url, params=None, use_http_post=False):
"""Retrieves a JSON object from a URL."""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return (request_url, json.loads(str_response, parse_float=Decimal))
return (request_url, json.load(response, parse_float=Decimal)) | python | def _fetch_remote_json(service_url, params=None, use_http_post=False):
"""Retrieves a JSON object from a URL."""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return (request_url, json.loads(str_response, parse_float=Decimal))
return (request_url, json.load(response, parse_float=Decimal)) | [
"def",
"_fetch_remote_json",
"(",
"service_url",
",",
"params",
"=",
"None",
",",
"use_http_post",
"=",
"False",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"request_url",
",",
"response",
"=",
"_fetch_remote",
"(",
"service_url",
",",
"... | Retrieves a JSON object from a URL. | [
"Retrieves",
"a",
"JSON",
"object",
"from",
"a",
"URL",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L73-L82 | train | 203,044 |
slimkrazy/python-google-places | googleplaces/__init__.py | _fetch_remote_file | def _fetch_remote_file(service_url, params=None, use_http_post=False):
"""Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data)
"""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
dummy, params = cgi.parse_header(
response.headers.get('Content-Disposition', ''))
fn = params['filename']
return (response.headers.get('content-type'),
fn, response.read(), response.geturl()) | python | def _fetch_remote_file(service_url, params=None, use_http_post=False):
"""Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data)
"""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
dummy, params = cgi.parse_header(
response.headers.get('Content-Disposition', ''))
fn = params['filename']
return (response.headers.get('content-type'),
fn, response.read(), response.geturl()) | [
"def",
"_fetch_remote_file",
"(",
"service_url",
",",
"params",
"=",
"None",
",",
"use_http_post",
"=",
"False",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"request_url",
",",
"response",
"=",
"_fetch_remote",
"(",
"service_url",
",",
"... | Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data) | [
"Retrieves",
"a",
"file",
"from",
"a",
"URL",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L84-L98 | train | 203,045 |
slimkrazy/python-google-places | googleplaces/__init__.py | geocode_location | def geocode_location(location, sensor=False, api_key=None):
"""Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location.
"""
params = {'address': location, 'sensor': str(sensor).lower()}
if api_key is not None:
params['key'] = api_key
url, geo_response = _fetch_remote_json(
GooglePlaces.GEOCODE_API_URL, params)
_validate_response(url, geo_response)
if geo_response['status'] == GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS:
error_detail = ('Lat/Lng for location \'%s\' can\'t be determined.' %
location)
raise GooglePlacesError(error_detail)
return geo_response['results'][0]['geometry']['location'] | python | def geocode_location(location, sensor=False, api_key=None):
"""Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location.
"""
params = {'address': location, 'sensor': str(sensor).lower()}
if api_key is not None:
params['key'] = api_key
url, geo_response = _fetch_remote_json(
GooglePlaces.GEOCODE_API_URL, params)
_validate_response(url, geo_response)
if geo_response['status'] == GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS:
error_detail = ('Lat/Lng for location \'%s\' can\'t be determined.' %
location)
raise GooglePlacesError(error_detail)
return geo_response['results'][0]['geometry']['location'] | [
"def",
"geocode_location",
"(",
"location",
",",
"sensor",
"=",
"False",
",",
"api_key",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'address'",
":",
"location",
",",
"'sensor'",
":",
"str",
"(",
"sensor",
")",
".",
"lower",
"(",
")",
"}",
"if",
"api... | Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location. | [
"Converts",
"a",
"human",
"-",
"readable",
"location",
"to",
"lat",
"-",
"lng",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L100-L124 | train | 203,046 |
slimkrazy/python-google-places | googleplaces/__init__.py | _get_place_details | def _get_place_details(place_id, api_key, sensor=False,
language=lang.ENGLISH):
"""Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place.
"""
url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL,
{'placeid': place_id,
'sensor': str(sensor).lower(),
'key': api_key,
'language': language})
_validate_response(url, detail_response)
return detail_response['result'] | python | def _get_place_details(place_id, api_key, sensor=False,
language=lang.ENGLISH):
"""Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place.
"""
url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL,
{'placeid': place_id,
'sensor': str(sensor).lower(),
'key': api_key,
'language': language})
_validate_response(url, detail_response)
return detail_response['result'] | [
"def",
"_get_place_details",
"(",
"place_id",
",",
"api_key",
",",
"sensor",
"=",
"False",
",",
"language",
"=",
"lang",
".",
"ENGLISH",
")",
":",
"url",
",",
"detail_response",
"=",
"_fetch_remote_json",
"(",
"GooglePlaces",
".",
"DETAIL_API_URL",
",",
"{",
... | Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place. | [
"Gets",
"a",
"detailed",
"place",
"response",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L126-L139 | train | 203,047 |
slimkrazy/python-google-places | googleplaces/__init__.py | _validate_response | def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: %s' %
(url, response['status']))
raise GooglePlacesError(error_detail) | python | def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: %s' %
(url, response['status']))
raise GooglePlacesError(error_detail) | [
"def",
"_validate_response",
"(",
"url",
",",
"response",
")",
":",
"if",
"response",
"[",
"'status'",
"]",
"not",
"in",
"[",
"GooglePlaces",
".",
"RESPONSE_STATUS_OK",
",",
"GooglePlaces",
".",
"RESPONSE_STATUS_ZERO_RESULTS",
"]",
":",
"error_detail",
"=",
"(",... | Validates that the response from Google was successful. | [
"Validates",
"that",
"the",
"response",
"from",
"Google",
"was",
"successful",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L169-L175 | train | 203,048 |
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.nearby_search | def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | python | def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | [
"def",
"nearby_search",
"(",
"self",
",",
"language",
"=",
"lang",
".",
"ENGLISH",
",",
"keyword",
"=",
"None",
",",
"location",
"=",
"None",
",",
"lat_lng",
"=",
"None",
",",
"name",
"=",
"None",
",",
"radius",
"=",
"3200",
",",
"rankby",
"=",
"rank... | Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None) | [
"Perform",
"a",
"nearby",
"search",
"using",
"the",
"Google",
"Places",
"API",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L232-L306 | train | 203,049 |
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.text_search | def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | python | def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | [
"def",
"text_search",
"(",
"self",
",",
"query",
"=",
"None",
",",
"language",
"=",
"lang",
".",
"ENGLISH",
",",
"lat_lng",
"=",
"None",
",",
"radius",
"=",
"3200",
",",
"type",
"=",
"None",
",",
"types",
"=",
"[",
"]",
",",
"location",
"=",
"None"... | Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param. | [
"Perform",
"a",
"text",
"search",
"using",
"the",
"Google",
"Places",
"API",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L308-L354 | train | 203,050 |
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.autocomplete | def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response) | python | def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response) | [
"def",
"autocomplete",
"(",
"self",
",",
"input",
",",
"lat_lng",
"=",
"None",
",",
"location",
"=",
"None",
",",
"radius",
"=",
"3200",
",",
"language",
"=",
"lang",
".",
"ENGLISH",
",",
"types",
"=",
"None",
",",
"components",
"=",
"[",
"]",
")",
... | Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')] | [
"Perform",
"an",
"autocomplete",
"search",
"using",
"the",
"Google",
"Places",
"API",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L356-L401 | train | 203,051 |
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.radar_search | def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | python | def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | [
"def",
"radar_search",
"(",
"self",
",",
"sensor",
"=",
"False",
",",
"keyword",
"=",
"None",
",",
"name",
"=",
"None",
",",
"language",
"=",
"lang",
".",
"ENGLISH",
",",
"lat_lng",
"=",
"None",
",",
"opennow",
"=",
"False",
",",
"radius",
"=",
"3200... | Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param | [
"Perform",
"a",
"radar",
"search",
"using",
"the",
"Google",
"Places",
"API",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L403-L468 | train | 203,052 |
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.checkin | def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response) | python | def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response) | [
"def",
"checkin",
"(",
"self",
",",
"place_id",
",",
"sensor",
"=",
"False",
")",
":",
"data",
"=",
"{",
"'placeid'",
":",
"place_id",
"}",
"url",
",",
"checkin_response",
"=",
"_fetch_remote_json",
"(",
"GooglePlaces",
".",
"CHECKIN_API_URL",
"%",
"(",
"s... | Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False). | [
"Checks",
"in",
"a",
"user",
"to",
"a",
"place",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L470-L482 | train | 203,053 |
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.get_place | def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details) | python | def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details) | [
"def",
"get_place",
"(",
"self",
",",
"place_id",
",",
"sensor",
"=",
"False",
",",
"language",
"=",
"lang",
".",
"ENGLISH",
")",
":",
"place_details",
"=",
"_get_place_details",
"(",
"place_id",
",",
"self",
".",
"api_key",
",",
"sensor",
",",
"language",... | Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH) | [
"Gets",
"a",
"detailed",
"place",
"object",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L484-L496 | train | 203,054 |
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.add_place | def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']} | python | def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']} | [
"def",
"add_place",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"required_kwargs",
"=",
"{",
"'name'",
":",
"[",
"str",
"]",
",",
"'lat_lng'",
":",
"[",
"dict",
"]",
",",
"'accuracy'",
":",
"[",
"int",
"]",
",",
"'types'",
":",
"[",
"str",
",... | Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False). | [
"Adds",
"a",
"place",
"to",
"the",
"Google",
"Places",
"database",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L498-L565 | train | 203,055 |
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.delete_place | def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response) | python | def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response) | [
"def",
"delete_place",
"(",
"self",
",",
"place_id",
",",
"sensor",
"=",
"False",
")",
":",
"request_params",
"=",
"{",
"'place_id'",
":",
"place_id",
"}",
"url",
",",
"delete_response",
"=",
"_fetch_remote_json",
"(",
"GooglePlaces",
".",
"DELETE_API_URL",
"%... | Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False). | [
"Deletes",
"a",
"place",
"from",
"the",
"Google",
"Places",
"database",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L567-L581 | train | 203,056 |
slimkrazy/python-google-places | googleplaces/__init__.py | Prediction.types | def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types | python | def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types | [
"def",
"types",
"(",
"self",
")",
":",
"if",
"self",
".",
"_types",
"==",
"''",
"and",
"self",
".",
"details",
"!=",
"None",
"and",
"'types'",
"in",
"self",
".",
"details",
":",
"self",
".",
"_icon",
"=",
"self",
".",
"details",
"[",
"'types'",
"]"... | Returns a list of feature types describing the given result. | [
"Returns",
"a",
"list",
"of",
"feature",
"types",
"describing",
"the",
"given",
"result",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L723-L729 | train | 203,057 |
slimkrazy/python-google-places | googleplaces/__init__.py | Place.icon | def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon | python | def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"if",
"self",
".",
"_icon",
"==",
"''",
"and",
"self",
".",
"details",
"!=",
"None",
"and",
"'icon'",
"in",
"self",
".",
"details",
":",
"self",
".",
"_icon",
"=",
"self",
".",
"details",
"[",
"'icon'",
"]",
... | Returns the URL of a recommended icon for display. | [
"Returns",
"the",
"URL",
"of",
"a",
"recommended",
"icon",
"for",
"display",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L893-L897 | train | 203,058 |
slimkrazy/python-google-places | googleplaces/__init__.py | Place.name | def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name | python | def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
"==",
"''",
"and",
"self",
".",
"details",
"!=",
"None",
"and",
"'name'",
"in",
"self",
".",
"details",
":",
"self",
".",
"_name",
"=",
"self",
".",
"details",
"[",
"'name'",
"]",
... | Returns the human-readable name of the place. | [
"Returns",
"the",
"human",
"-",
"readable",
"name",
"of",
"the",
"place",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L915-L919 | train | 203,059 |
slimkrazy/python-google-places | googleplaces/__init__.py | Place.vicinity | def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity | python | def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity | [
"def",
"vicinity",
"(",
"self",
")",
":",
"if",
"self",
".",
"_vicinity",
"==",
"''",
"and",
"self",
".",
"details",
"!=",
"None",
"and",
"'vicinity'",
"in",
"self",
".",
"details",
":",
"self",
".",
"_vicinity",
"=",
"self",
".",
"details",
"[",
"'v... | Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results. | [
"Returns",
"a",
"feature",
"name",
"of",
"a",
"nearby",
"location",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L922-L930 | train | 203,060 |
slimkrazy/python-google-places | googleplaces/__init__.py | Place.rating | def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating | python | def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating | [
"def",
"rating",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rating",
"==",
"''",
"and",
"self",
".",
"details",
"!=",
"None",
"and",
"'rating'",
"in",
"self",
".",
"details",
":",
"self",
".",
"_rating",
"=",
"self",
".",
"details",
"[",
"'rating'",... | Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating. | [
"Returns",
"the",
"Place",
"s",
"rating",
"from",
"0",
".",
"0",
"to",
"5",
".",
"0",
"based",
"on",
"user",
"reviews",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L933-L940 | train | 203,061 |
slimkrazy/python-google-places | googleplaces/__init__.py | Place.checkin | def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor) | python | def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor) | [
"def",
"checkin",
"(",
"self",
")",
":",
"self",
".",
"_query_instance",
".",
"checkin",
"(",
"self",
".",
"place_id",
",",
"self",
".",
"_query_instance",
".",
"sensor",
")"
] | Checks in an anonymous user in. | [
"Checks",
"in",
"an",
"anonymous",
"user",
"in",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L1006-L1009 | train | 203,062 |
slimkrazy/python-google-places | googleplaces/__init__.py | Photo.get | def get(self, maxheight=None, maxwidth=None, sensor=False):
"""Fetch photo from API."""
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result | python | def get(self, maxheight=None, maxwidth=None, sensor=False):
"""Fetch photo from API."""
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result | [
"def",
"get",
"(",
"self",
",",
"maxheight",
"=",
"None",
",",
"maxwidth",
"=",
"None",
",",
"sensor",
"=",
"False",
")",
":",
"if",
"not",
"maxheight",
"and",
"not",
"maxwidth",
":",
"raise",
"GooglePlacesError",
"(",
"'You must specify maxheight or maxwidth!... | Fetch photo from API. | [
"Fetch",
"photo",
"from",
"API",
"."
] | d4b7363e1655cdc091a6253379f6d2a95b827881 | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L1063-L1073 | train | 203,063 |
BoboTiG/python-mss | mss/tools.py | to_png | def to_png(data, size, level=6, output=None):
# type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]
"""
Dump data to a PNG file. If `output` is `None`, create no file but return
the whole PNG data.
:param bytes data: RGBRGB...RGB data.
:param tuple size: The (width, height) pair.
:param int level: PNG compression level.
:param str output: Output file name.
"""
width, height = size
line = width * 3
png_filter = struct.pack(">B", 0)
scanlines = b"".join(
[png_filter + data[y * line : y * line + line] for y in range(height)]
)
magic = struct.pack(">8B", 137, 80, 78, 71, 13, 10, 26, 10)
# Header: size, marker, data, CRC32
ihdr = [b"", b"IHDR", b"", b""]
ihdr[2] = struct.pack(">2I5B", width, height, 8, 2, 0, 0, 0)
ihdr[3] = struct.pack(">I", zlib.crc32(b"".join(ihdr[1:3])) & 0xFFFFFFFF)
ihdr[0] = struct.pack(">I", len(ihdr[2]))
# Data: size, marker, data, CRC32
idat = [b"", b"IDAT", zlib.compress(scanlines, level), b""]
idat[3] = struct.pack(">I", zlib.crc32(b"".join(idat[1:3])) & 0xFFFFFFFF)
idat[0] = struct.pack(">I", len(idat[2]))
# Footer: size, marker, None, CRC32
iend = [b"", b"IEND", b"", b""]
iend[3] = struct.pack(">I", zlib.crc32(iend[1]) & 0xFFFFFFFF)
iend[0] = struct.pack(">I", len(iend[2]))
if not output:
# Returns raw bytes of the whole PNG data
return magic + b"".join(ihdr + idat + iend)
with open(output, "wb") as fileh:
fileh.write(magic)
fileh.write(b"".join(ihdr))
fileh.write(b"".join(idat))
fileh.write(b"".join(iend))
return None | python | def to_png(data, size, level=6, output=None):
# type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]
"""
Dump data to a PNG file. If `output` is `None`, create no file but return
the whole PNG data.
:param bytes data: RGBRGB...RGB data.
:param tuple size: The (width, height) pair.
:param int level: PNG compression level.
:param str output: Output file name.
"""
width, height = size
line = width * 3
png_filter = struct.pack(">B", 0)
scanlines = b"".join(
[png_filter + data[y * line : y * line + line] for y in range(height)]
)
magic = struct.pack(">8B", 137, 80, 78, 71, 13, 10, 26, 10)
# Header: size, marker, data, CRC32
ihdr = [b"", b"IHDR", b"", b""]
ihdr[2] = struct.pack(">2I5B", width, height, 8, 2, 0, 0, 0)
ihdr[3] = struct.pack(">I", zlib.crc32(b"".join(ihdr[1:3])) & 0xFFFFFFFF)
ihdr[0] = struct.pack(">I", len(ihdr[2]))
# Data: size, marker, data, CRC32
idat = [b"", b"IDAT", zlib.compress(scanlines, level), b""]
idat[3] = struct.pack(">I", zlib.crc32(b"".join(idat[1:3])) & 0xFFFFFFFF)
idat[0] = struct.pack(">I", len(idat[2]))
# Footer: size, marker, None, CRC32
iend = [b"", b"IEND", b"", b""]
iend[3] = struct.pack(">I", zlib.crc32(iend[1]) & 0xFFFFFFFF)
iend[0] = struct.pack(">I", len(iend[2]))
if not output:
# Returns raw bytes of the whole PNG data
return magic + b"".join(ihdr + idat + iend)
with open(output, "wb") as fileh:
fileh.write(magic)
fileh.write(b"".join(ihdr))
fileh.write(b"".join(idat))
fileh.write(b"".join(iend))
return None | [
"def",
"to_png",
"(",
"data",
",",
"size",
",",
"level",
"=",
"6",
",",
"output",
"=",
"None",
")",
":",
"# type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]",
"width",
",",
"height",
"=",
"size",
"line",
"=",
"width",
"*",
"3",
"png_filter",... | Dump data to a PNG file. If `output` is `None`, create no file but return
the whole PNG data.
:param bytes data: RGBRGB...RGB data.
:param tuple size: The (width, height) pair.
:param int level: PNG compression level.
:param str output: Output file name. | [
"Dump",
"data",
"to",
"a",
"PNG",
"file",
".",
"If",
"output",
"is",
"None",
"create",
"no",
"file",
"but",
"return",
"the",
"whole",
"PNG",
"data",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/tools.py#L14-L61 | train | 203,064 |
BoboTiG/python-mss | mss/screenshot.py | ScreenShot.from_size | def from_size(cls, data, width, height):
# type: (bytearray, int, int) -> ScreenShot
""" Instantiate a new class given only screen shot's data and size. """
monitor = {"left": 0, "top": 0, "width": width, "height": height}
return cls(data, monitor) | python | def from_size(cls, data, width, height):
# type: (bytearray, int, int) -> ScreenShot
""" Instantiate a new class given only screen shot's data and size. """
monitor = {"left": 0, "top": 0, "width": width, "height": height}
return cls(data, monitor) | [
"def",
"from_size",
"(",
"cls",
",",
"data",
",",
"width",
",",
"height",
")",
":",
"# type: (bytearray, int, int) -> ScreenShot",
"monitor",
"=",
"{",
"\"left\"",
":",
"0",
",",
"\"top\"",
":",
"0",
",",
"\"width\"",
":",
"width",
",",
"\"height\"",
":",
... | Instantiate a new class given only screen shot's data and size. | [
"Instantiate",
"a",
"new",
"class",
"given",
"only",
"screen",
"shot",
"s",
"data",
"and",
"size",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/screenshot.py#L71-L76 | train | 203,065 |
BoboTiG/python-mss | mss/screenshot.py | ScreenShot.rgb | def rgb(self):
# type: () -> bytes
"""
Compute RGB values from the BGRA raw pixels.
:return bytes: RGB pixels.
"""
if not self.__rgb:
rgb = bytearray(self.height * self.width * 3)
raw = self.raw
rgb[0::3] = raw[2::4]
rgb[1::3] = raw[1::4]
rgb[2::3] = raw[0::4]
self.__rgb = bytes(rgb)
return self.__rgb | python | def rgb(self):
# type: () -> bytes
"""
Compute RGB values from the BGRA raw pixels.
:return bytes: RGB pixels.
"""
if not self.__rgb:
rgb = bytearray(self.height * self.width * 3)
raw = self.raw
rgb[0::3] = raw[2::4]
rgb[1::3] = raw[1::4]
rgb[2::3] = raw[0::4]
self.__rgb = bytes(rgb)
return self.__rgb | [
"def",
"rgb",
"(",
"self",
")",
":",
"# type: () -> bytes",
"if",
"not",
"self",
".",
"__rgb",
":",
"rgb",
"=",
"bytearray",
"(",
"self",
".",
"height",
"*",
"self",
".",
"width",
"*",
"3",
")",
"raw",
"=",
"self",
".",
"raw",
"rgb",
"[",
"0",
":... | Compute RGB values from the BGRA raw pixels.
:return bytes: RGB pixels. | [
"Compute",
"RGB",
"values",
"from",
"the",
"BGRA",
"raw",
"pixels",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/screenshot.py#L112-L128 | train | 203,066 |
BoboTiG/python-mss | mss/screenshot.py | ScreenShot.pixel | def pixel(self, coord_x, coord_y):
# type: (int, int) -> Pixel
"""
Returns the pixel value at a given position.
:param int coord_x: The x coordinate.
:param int coord_y: The y coordinate.
:return tuple: The pixel value as (R, G, B).
"""
try:
return self.pixels[coord_y][coord_x] # type: ignore
except IndexError:
raise ScreenShotError(
"Pixel location ({}, {}) is out of range.".format(coord_x, coord_y)
) | python | def pixel(self, coord_x, coord_y):
# type: (int, int) -> Pixel
"""
Returns the pixel value at a given position.
:param int coord_x: The x coordinate.
:param int coord_y: The y coordinate.
:return tuple: The pixel value as (R, G, B).
"""
try:
return self.pixels[coord_y][coord_x] # type: ignore
except IndexError:
raise ScreenShotError(
"Pixel location ({}, {}) is out of range.".format(coord_x, coord_y)
) | [
"def",
"pixel",
"(",
"self",
",",
"coord_x",
",",
"coord_y",
")",
":",
"# type: (int, int) -> Pixel",
"try",
":",
"return",
"self",
".",
"pixels",
"[",
"coord_y",
"]",
"[",
"coord_x",
"]",
"# type: ignore",
"except",
"IndexError",
":",
"raise",
"ScreenShotErro... | Returns the pixel value at a given position.
:param int coord_x: The x coordinate.
:param int coord_y: The y coordinate.
:return tuple: The pixel value as (R, G, B). | [
"Returns",
"the",
"pixel",
"value",
"at",
"a",
"given",
"position",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/screenshot.py#L142-L157 | train | 203,067 |
BoboTiG/python-mss | mss/__main__.py | main | def main(args=None):
# type: (Optional[List[str]]) -> int
""" Main logic. """
cli_args = ArgumentParser()
cli_args.add_argument(
"-c",
"--coordinates",
default="",
type=str,
help="the part of the screen to capture: top, left, width, height",
)
cli_args.add_argument(
"-l",
"--level",
default=6,
type=int,
choices=list(range(10)),
help="the PNG compression level",
)
cli_args.add_argument(
"-m", "--monitor", default=0, type=int, help="the monitor to screen shot"
)
cli_args.add_argument(
"-o", "--output", default="monitor-{mon}.png", help="the output file name"
)
cli_args.add_argument(
"-q",
"--quiet",
default=False,
action="store_true",
help="do not print created files",
)
cli_args.add_argument("-v", "--version", action="version", version=__version__)
options = cli_args.parse_args(args)
kwargs = {"mon": options.monitor, "output": options.output}
if options.coordinates:
try:
top, left, width, height = options.coordinates.split(",")
except ValueError:
print("Coordinates syntax: top, left, width, height")
return 2
kwargs["mon"] = {
"top": int(top),
"left": int(left),
"width": int(width),
"height": int(height),
}
if options.output == "monitor-{mon}.png":
kwargs["output"] = "sct-{top}x{left}_{width}x{height}.png"
try:
with mss() as sct:
if options.coordinates:
output = kwargs["output"].format(**kwargs["mon"])
sct_img = sct.grab(kwargs["mon"])
to_png(sct_img.rgb, sct_img.size, level=options.level, output=output)
if not options.quiet:
print(os.path.realpath(output))
else:
for file_name in sct.save(**kwargs):
if not options.quiet:
print(os.path.realpath(file_name))
return 0
except ScreenShotError:
return 1 | python | def main(args=None):
# type: (Optional[List[str]]) -> int
""" Main logic. """
cli_args = ArgumentParser()
cli_args.add_argument(
"-c",
"--coordinates",
default="",
type=str,
help="the part of the screen to capture: top, left, width, height",
)
cli_args.add_argument(
"-l",
"--level",
default=6,
type=int,
choices=list(range(10)),
help="the PNG compression level",
)
cli_args.add_argument(
"-m", "--monitor", default=0, type=int, help="the monitor to screen shot"
)
cli_args.add_argument(
"-o", "--output", default="monitor-{mon}.png", help="the output file name"
)
cli_args.add_argument(
"-q",
"--quiet",
default=False,
action="store_true",
help="do not print created files",
)
cli_args.add_argument("-v", "--version", action="version", version=__version__)
options = cli_args.parse_args(args)
kwargs = {"mon": options.monitor, "output": options.output}
if options.coordinates:
try:
top, left, width, height = options.coordinates.split(",")
except ValueError:
print("Coordinates syntax: top, left, width, height")
return 2
kwargs["mon"] = {
"top": int(top),
"left": int(left),
"width": int(width),
"height": int(height),
}
if options.output == "monitor-{mon}.png":
kwargs["output"] = "sct-{top}x{left}_{width}x{height}.png"
try:
with mss() as sct:
if options.coordinates:
output = kwargs["output"].format(**kwargs["mon"])
sct_img = sct.grab(kwargs["mon"])
to_png(sct_img.rgb, sct_img.size, level=options.level, output=output)
if not options.quiet:
print(os.path.realpath(output))
else:
for file_name in sct.save(**kwargs):
if not options.quiet:
print(os.path.realpath(file_name))
return 0
except ScreenShotError:
return 1 | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"# type: (Optional[List[str]]) -> int",
"cli_args",
"=",
"ArgumentParser",
"(",
")",
"cli_args",
".",
"add_argument",
"(",
"\"-c\"",
",",
"\"--coordinates\"",
",",
"default",
"=",
"\"\"",
",",
"type",
"=",
"st... | Main logic. | [
"Main",
"logic",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/__main__.py#L20-L87 | train | 203,068 |
BoboTiG/python-mss | mss/linux.py | error_handler | def error_handler(_, event):
# type: (Any, Any) -> int
""" Specifies the program's supplied error handler. """
evt = event.contents
ERROR.details = {
"type": evt.type,
"serial": evt.serial,
"error_code": evt.error_code,
"request_code": evt.request_code,
"minor_code": evt.minor_code,
}
return 0 | python | def error_handler(_, event):
# type: (Any, Any) -> int
""" Specifies the program's supplied error handler. """
evt = event.contents
ERROR.details = {
"type": evt.type,
"serial": evt.serial,
"error_code": evt.error_code,
"request_code": evt.request_code,
"minor_code": evt.minor_code,
}
return 0 | [
"def",
"error_handler",
"(",
"_",
",",
"event",
")",
":",
"# type: (Any, Any) -> int",
"evt",
"=",
"event",
".",
"contents",
"ERROR",
".",
"details",
"=",
"{",
"\"type\"",
":",
"evt",
".",
"type",
",",
"\"serial\"",
":",
"evt",
".",
"serial",
",",
"\"err... | Specifies the program's supplied error handler. | [
"Specifies",
"the",
"program",
"s",
"supplied",
"error",
"handler",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/linux.py#L151-L163 | train | 203,069 |
BoboTiG/python-mss | mss/linux.py | validate | def validate(retval, func, args):
# type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]]
""" Validate the returned value of a Xlib or XRANDR function. """
if retval != 0 and not ERROR.details:
return args
err = "{}() failed".format(func.__name__)
details = {"retval": retval, "args": args}
raise ScreenShotError(err, details=details) | python | def validate(retval, func, args):
# type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]]
""" Validate the returned value of a Xlib or XRANDR function. """
if retval != 0 and not ERROR.details:
return args
err = "{}() failed".format(func.__name__)
details = {"retval": retval, "args": args}
raise ScreenShotError(err, details=details) | [
"def",
"validate",
"(",
"retval",
",",
"func",
",",
"args",
")",
":",
"# type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]]",
"if",
"retval",
"!=",
"0",
"and",
"not",
"ERROR",
".",
"details",
":",
"return",
"args",
"err",
"=",
"\"{}() failed\"",
".",
... | Validate the returned value of a Xlib or XRANDR function. | [
"Validate",
"the",
"returned",
"value",
"of",
"a",
"Xlib",
"or",
"XRANDR",
"function",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/linux.py#L166-L175 | train | 203,070 |
BoboTiG/python-mss | mss/linux.py | MSS.get_error_details | def get_error_details(self):
# type: () -> Optional[Dict[str, Any]]
""" Get more information about the latest X server error. """
details = {} # type: Dict[str, Any]
if ERROR.details:
details = {"xerror_details": ERROR.details}
ERROR.details = None
xserver_error = ctypes.create_string_buffer(1024)
self.xlib.XGetErrorText(
MSS.display,
details.get("xerror_details", {}).get("error_code", 0),
xserver_error,
len(xserver_error),
)
xerror = xserver_error.value.decode("utf-8")
if xerror != "0":
details["xerror"] = xerror
return details | python | def get_error_details(self):
# type: () -> Optional[Dict[str, Any]]
""" Get more information about the latest X server error. """
details = {} # type: Dict[str, Any]
if ERROR.details:
details = {"xerror_details": ERROR.details}
ERROR.details = None
xserver_error = ctypes.create_string_buffer(1024)
self.xlib.XGetErrorText(
MSS.display,
details.get("xerror_details", {}).get("error_code", 0),
xserver_error,
len(xserver_error),
)
xerror = xserver_error.value.decode("utf-8")
if xerror != "0":
details["xerror"] = xerror
return details | [
"def",
"get_error_details",
"(",
"self",
")",
":",
"# type: () -> Optional[Dict[str, Any]]",
"details",
"=",
"{",
"}",
"# type: Dict[str, Any]",
"if",
"ERROR",
".",
"details",
":",
"details",
"=",
"{",
"\"xerror_details\"",
":",
"ERROR",
".",
"details",
"}",
"ERRO... | Get more information about the latest X server error. | [
"Get",
"more",
"information",
"about",
"the",
"latest",
"X",
"server",
"error",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/linux.py#L333-L353 | train | 203,071 |
BoboTiG/python-mss | docs/source/examples/callback.py | on_exists | def on_exists(fname):
# type: (str) -> None
"""
Callback example when we try to overwrite an existing screenshot.
"""
if os.path.isfile(fname):
newfile = fname + ".old"
print("{} -> {}".format(fname, newfile))
os.rename(fname, newfile) | python | def on_exists(fname):
# type: (str) -> None
"""
Callback example when we try to overwrite an existing screenshot.
"""
if os.path.isfile(fname):
newfile = fname + ".old"
print("{} -> {}".format(fname, newfile))
os.rename(fname, newfile) | [
"def",
"on_exists",
"(",
"fname",
")",
":",
"# type: (str) -> None",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fname",
")",
":",
"newfile",
"=",
"fname",
"+",
"\".old\"",
"print",
"(",
"\"{} -> {}\"",
".",
"format",
"(",
"fname",
",",
"newfile",
")",... | Callback example when we try to overwrite an existing screenshot. | [
"Callback",
"example",
"when",
"we",
"try",
"to",
"overwrite",
"an",
"existing",
"screenshot",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/docs/source/examples/callback.py#L14-L23 | train | 203,072 |
BoboTiG/python-mss | mss/base.py | MSSMixin.save | def save(self, mon=0, output="monitor-{mon}.png", callback=None):
# type: (int, str, Callable[[str], None]) -> Iterator[str]
"""
Grab a screen shot and save it to a file.
:param int mon: The monitor to screen shot (default=0).
-1: grab one screen shot of all monitors
0: grab one screen shot by monitor
N: grab the screen shot of the monitor N
:param str output: The output filename.
It can take several keywords to customize the filename:
- `{mon}`: the monitor number
- `{top}`: the screen shot y-coordinate of the upper-left corner
- `{left}`: the screen shot x-coordinate of the upper-left corner
- `{width}`: the screen shot's width
- `{height}`: the screen shot's height
- `{date}`: the current date using the default formatter
As it is using the `format()` function, you can specify
formatting options like `{date:%Y-%m-%s}`.
:param callable callback: Callback called before saving the
screen shot to a file. Take the `output` argument as parameter.
:return generator: Created file(s).
"""
monitors = self.monitors
if not monitors:
raise ScreenShotError("No monitor found.")
if mon == 0:
# One screen shot by monitor
for idx, monitor in enumerate(monitors[1:], 1):
fname = output.format(mon=idx, date=datetime.now(), **monitor)
if callable(callback):
callback(fname)
sct = self.grab(monitor)
to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)
yield fname
else:
# A screen shot of all monitors together or
# a screen shot of the monitor N.
mon = 0 if mon == -1 else mon
try:
monitor = monitors[mon]
except IndexError:
raise ScreenShotError("Monitor {!r} does not exist.".format(mon))
output = output.format(mon=mon, date=datetime.now(), **monitor)
if callable(callback):
callback(output)
sct = self.grab(monitor)
to_png(sct.rgb, sct.size, level=self.compression_level, output=output)
yield output | python | def save(self, mon=0, output="monitor-{mon}.png", callback=None):
# type: (int, str, Callable[[str], None]) -> Iterator[str]
"""
Grab a screen shot and save it to a file.
:param int mon: The monitor to screen shot (default=0).
-1: grab one screen shot of all monitors
0: grab one screen shot by monitor
N: grab the screen shot of the monitor N
:param str output: The output filename.
It can take several keywords to customize the filename:
- `{mon}`: the monitor number
- `{top}`: the screen shot y-coordinate of the upper-left corner
- `{left}`: the screen shot x-coordinate of the upper-left corner
- `{width}`: the screen shot's width
- `{height}`: the screen shot's height
- `{date}`: the current date using the default formatter
As it is using the `format()` function, you can specify
formatting options like `{date:%Y-%m-%s}`.
:param callable callback: Callback called before saving the
screen shot to a file. Take the `output` argument as parameter.
:return generator: Created file(s).
"""
monitors = self.monitors
if not monitors:
raise ScreenShotError("No monitor found.")
if mon == 0:
# One screen shot by monitor
for idx, monitor in enumerate(monitors[1:], 1):
fname = output.format(mon=idx, date=datetime.now(), **monitor)
if callable(callback):
callback(fname)
sct = self.grab(monitor)
to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)
yield fname
else:
# A screen shot of all monitors together or
# a screen shot of the monitor N.
mon = 0 if mon == -1 else mon
try:
monitor = monitors[mon]
except IndexError:
raise ScreenShotError("Monitor {!r} does not exist.".format(mon))
output = output.format(mon=mon, date=datetime.now(), **monitor)
if callable(callback):
callback(output)
sct = self.grab(monitor)
to_png(sct.rgb, sct.size, level=self.compression_level, output=output)
yield output | [
"def",
"save",
"(",
"self",
",",
"mon",
"=",
"0",
",",
"output",
"=",
"\"monitor-{mon}.png\"",
",",
"callback",
"=",
"None",
")",
":",
"# type: (int, str, Callable[[str], None]) -> Iterator[str]",
"monitors",
"=",
"self",
".",
"monitors",
"if",
"not",
"monitors",
... | Grab a screen shot and save it to a file.
:param int mon: The monitor to screen shot (default=0).
-1: grab one screen shot of all monitors
0: grab one screen shot by monitor
N: grab the screen shot of the monitor N
:param str output: The output filename.
It can take several keywords to customize the filename:
- `{mon}`: the monitor number
- `{top}`: the screen shot y-coordinate of the upper-left corner
- `{left}`: the screen shot x-coordinate of the upper-left corner
- `{width}`: the screen shot's width
- `{height}`: the screen shot's height
- `{date}`: the current date using the default formatter
As it is using the `format()` function, you can specify
formatting options like `{date:%Y-%m-%s}`.
:param callable callback: Callback called before saving the
screen shot to a file. Take the `output` argument as parameter.
:return generator: Created file(s). | [
"Grab",
"a",
"screen",
"shot",
"and",
"save",
"it",
"to",
"a",
"file",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/base.py#L83-L139 | train | 203,073 |
BoboTiG/python-mss | mss/base.py | MSSMixin.shot | def shot(self, **kwargs):
# type: (Any) -> str
"""
Helper to save the screen shot of the 1st monitor, by default.
You can pass the same arguments as for ``save``.
"""
kwargs["mon"] = kwargs.get("mon", 1)
return next(self.save(**kwargs)) | python | def shot(self, **kwargs):
# type: (Any) -> str
"""
Helper to save the screen shot of the 1st monitor, by default.
You can pass the same arguments as for ``save``.
"""
kwargs["mon"] = kwargs.get("mon", 1)
return next(self.save(**kwargs)) | [
"def",
"shot",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Any) -> str",
"kwargs",
"[",
"\"mon\"",
"]",
"=",
"kwargs",
".",
"get",
"(",
"\"mon\"",
",",
"1",
")",
"return",
"next",
"(",
"self",
".",
"save",
"(",
"*",
"*",
"kwargs",
")"... | Helper to save the screen shot of the 1st monitor, by default.
You can pass the same arguments as for ``save``. | [
"Helper",
"to",
"save",
"the",
"screen",
"shot",
"of",
"the",
"1st",
"monitor",
"by",
"default",
".",
"You",
"can",
"pass",
"the",
"same",
"arguments",
"as",
"for",
"save",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/base.py#L141-L149 | train | 203,074 |
BoboTiG/python-mss | mss/base.py | MSSMixin._cfactory | def _cfactory(attr, func, argtypes, restype, errcheck=None):
# type: (Any, str, List[Any], Any, Optional[Callable]) -> None
""" Factory to create a ctypes function and automatically manage errors. """
meth = getattr(attr, func)
meth.argtypes = argtypes
meth.restype = restype
if errcheck:
meth.errcheck = errcheck | python | def _cfactory(attr, func, argtypes, restype, errcheck=None):
# type: (Any, str, List[Any], Any, Optional[Callable]) -> None
""" Factory to create a ctypes function and automatically manage errors. """
meth = getattr(attr, func)
meth.argtypes = argtypes
meth.restype = restype
if errcheck:
meth.errcheck = errcheck | [
"def",
"_cfactory",
"(",
"attr",
",",
"func",
",",
"argtypes",
",",
"restype",
",",
"errcheck",
"=",
"None",
")",
":",
"# type: (Any, str, List[Any], Any, Optional[Callable]) -> None",
"meth",
"=",
"getattr",
"(",
"attr",
",",
"func",
")",
"meth",
".",
"argtypes... | Factory to create a ctypes function and automatically manage errors. | [
"Factory",
"to",
"create",
"a",
"ctypes",
"function",
"and",
"automatically",
"manage",
"errors",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/base.py#L152-L160 | train | 203,075 |
BoboTiG/python-mss | mss/windows.py | MSS._set_dpi_awareness | def _set_dpi_awareness(self):
""" Set DPI aware to capture full screen on Hi-DPI monitors. """
version = sys.getwindowsversion()[:2] # pylint: disable=no-member
if version >= (6, 3):
# Windows 8.1+
# Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:
# per monitor DPI aware. This app checks for the DPI when it is
# created and adjusts the scale factor whenever the DPI changes.
# These applications are not automatically scaled by the system.
ctypes.windll.shcore.SetProcessDpiAwareness(2)
elif (6, 0) <= version < (6, 3):
# Windows Vista, 7, 8 and Server 2012
self.user32.SetProcessDPIAware() | python | def _set_dpi_awareness(self):
""" Set DPI aware to capture full screen on Hi-DPI monitors. """
version = sys.getwindowsversion()[:2] # pylint: disable=no-member
if version >= (6, 3):
# Windows 8.1+
# Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:
# per monitor DPI aware. This app checks for the DPI when it is
# created and adjusts the scale factor whenever the DPI changes.
# These applications are not automatically scaled by the system.
ctypes.windll.shcore.SetProcessDpiAwareness(2)
elif (6, 0) <= version < (6, 3):
# Windows Vista, 7, 8 and Server 2012
self.user32.SetProcessDPIAware() | [
"def",
"_set_dpi_awareness",
"(",
"self",
")",
":",
"version",
"=",
"sys",
".",
"getwindowsversion",
"(",
")",
"[",
":",
"2",
"]",
"# pylint: disable=no-member",
"if",
"version",
">=",
"(",
"6",
",",
"3",
")",
":",
"# Windows 8.1+",
"# Here 2 = PROCESS_PER_MON... | Set DPI aware to capture full screen on Hi-DPI monitors. | [
"Set",
"DPI",
"aware",
"to",
"capture",
"full",
"screen",
"on",
"Hi",
"-",
"DPI",
"monitors",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/windows.py#L162-L175 | train | 203,076 |
BoboTiG/python-mss | mss/factory.py | mss | def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_)) | python | def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_)) | [
"def",
"mss",
"(",
"*",
"*",
"kwargs",
")",
":",
"# type: (Any) -> MSSMixin",
"os_",
"=",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"if",
"os_",
"==",
"\"darwin\"",
":",
"from",
".",
"import",
"darwin",
"return",
"darwin",
".",
"MSS"... | Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation. | [
"Factory",
"returning",
"a",
"proper",
"MSS",
"class",
"instance",
"."
] | 56347f781edb38a0e7a5104080bd683f49c6f074 | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/factory.py#L18-L47 | train | 203,077 |
vaab/colour | colour.py | hsl2rgb | def hsl2rgb(hsl):
"""Convert HSL representation towards RGB
:param h: Hue, position around the chromatic circle (h=1 equiv h=0)
:param s: Saturation, color saturation (0=full gray, 1=full color)
:param l: Ligthness, Overhaul lightness (0=full black, 1=full white)
:rtype: 3-uple for RGB values in float between 0 and 1
Hue, Saturation, Range from Lightness is a float between 0 and 1
Note that Hue can be set to any value but as it is a rotation
around the chromatic circle, any value above 1 or below 0 can
be expressed by a value between 0 and 1 (Note that h=0 is equiv
to h=1).
This algorithm came from:
http://www.easyrgb.com/index.php?X=MATH&H=19#text19
Here are some quick notion of HSL to RGB conversion:
>>> from colour import hsl2rgb
With a lightness put at 0, RGB is always rgbblack
>>> hsl2rgb((0.0, 0.0, 0.0))
(0.0, 0.0, 0.0)
>>> hsl2rgb((0.5, 0.0, 0.0))
(0.0, 0.0, 0.0)
>>> hsl2rgb((0.5, 0.5, 0.0))
(0.0, 0.0, 0.0)
Same for lightness put at 1, RGB is always rgbwhite
>>> hsl2rgb((0.0, 0.0, 1.0))
(1.0, 1.0, 1.0)
>>> hsl2rgb((0.5, 0.0, 1.0))
(1.0, 1.0, 1.0)
>>> hsl2rgb((0.5, 0.5, 1.0))
(1.0, 1.0, 1.0)
With saturation put at 0, the RGB should be equal to Lightness:
>>> hsl2rgb((0.0, 0.0, 0.25))
(0.25, 0.25, 0.25)
>>> hsl2rgb((0.5, 0.0, 0.5))
(0.5, 0.5, 0.5)
>>> hsl2rgb((0.5, 0.0, 0.75))
(0.75, 0.75, 0.75)
With saturation put at 1, and lightness put to 0.5, we can find
normal full red, green, blue colors:
>>> hsl2rgb((0 , 1.0, 0.5))
(1.0, 0.0, 0.0)
>>> hsl2rgb((1 , 1.0, 0.5))
(1.0, 0.0, 0.0)
>>> hsl2rgb((1.0/3 , 1.0, 0.5))
(0.0, 1.0, 0.0)
>>> hsl2rgb((2.0/3 , 1.0, 0.5))
(0.0, 0.0, 1.0)
Of course:
>>> hsl2rgb((0.0, 2.0, 0.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Saturation must be between 0 and 1.
And:
>>> hsl2rgb((0.0, 0.0, 1.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Lightness must be between 0 and 1.
"""
h, s, l = [float(v) for v in hsl]
if not (0.0 - FLOAT_ERROR <= s <= 1.0 + FLOAT_ERROR):
raise ValueError("Saturation must be between 0 and 1.")
if not (0.0 - FLOAT_ERROR <= l <= 1.0 + FLOAT_ERROR):
raise ValueError("Lightness must be between 0 and 1.")
if s == 0:
return l, l, l
if l < 0.5:
v2 = l * (1.0 + s)
else:
v2 = (l + s) - (s * l)
v1 = 2.0 * l - v2
r = _hue2rgb(v1, v2, h + (1.0 / 3))
g = _hue2rgb(v1, v2, h)
b = _hue2rgb(v1, v2, h - (1.0 / 3))
return r, g, b | python | def hsl2rgb(hsl):
"""Convert HSL representation towards RGB
:param h: Hue, position around the chromatic circle (h=1 equiv h=0)
:param s: Saturation, color saturation (0=full gray, 1=full color)
:param l: Ligthness, Overhaul lightness (0=full black, 1=full white)
:rtype: 3-uple for RGB values in float between 0 and 1
Hue, Saturation, Range from Lightness is a float between 0 and 1
Note that Hue can be set to any value but as it is a rotation
around the chromatic circle, any value above 1 or below 0 can
be expressed by a value between 0 and 1 (Note that h=0 is equiv
to h=1).
This algorithm came from:
http://www.easyrgb.com/index.php?X=MATH&H=19#text19
Here are some quick notion of HSL to RGB conversion:
>>> from colour import hsl2rgb
With a lightness put at 0, RGB is always rgbblack
>>> hsl2rgb((0.0, 0.0, 0.0))
(0.0, 0.0, 0.0)
>>> hsl2rgb((0.5, 0.0, 0.0))
(0.0, 0.0, 0.0)
>>> hsl2rgb((0.5, 0.5, 0.0))
(0.0, 0.0, 0.0)
Same for lightness put at 1, RGB is always rgbwhite
>>> hsl2rgb((0.0, 0.0, 1.0))
(1.0, 1.0, 1.0)
>>> hsl2rgb((0.5, 0.0, 1.0))
(1.0, 1.0, 1.0)
>>> hsl2rgb((0.5, 0.5, 1.0))
(1.0, 1.0, 1.0)
With saturation put at 0, the RGB should be equal to Lightness:
>>> hsl2rgb((0.0, 0.0, 0.25))
(0.25, 0.25, 0.25)
>>> hsl2rgb((0.5, 0.0, 0.5))
(0.5, 0.5, 0.5)
>>> hsl2rgb((0.5, 0.0, 0.75))
(0.75, 0.75, 0.75)
With saturation put at 1, and lightness put to 0.5, we can find
normal full red, green, blue colors:
>>> hsl2rgb((0 , 1.0, 0.5))
(1.0, 0.0, 0.0)
>>> hsl2rgb((1 , 1.0, 0.5))
(1.0, 0.0, 0.0)
>>> hsl2rgb((1.0/3 , 1.0, 0.5))
(0.0, 1.0, 0.0)
>>> hsl2rgb((2.0/3 , 1.0, 0.5))
(0.0, 0.0, 1.0)
Of course:
>>> hsl2rgb((0.0, 2.0, 0.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Saturation must be between 0 and 1.
And:
>>> hsl2rgb((0.0, 0.0, 1.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Lightness must be between 0 and 1.
"""
h, s, l = [float(v) for v in hsl]
if not (0.0 - FLOAT_ERROR <= s <= 1.0 + FLOAT_ERROR):
raise ValueError("Saturation must be between 0 and 1.")
if not (0.0 - FLOAT_ERROR <= l <= 1.0 + FLOAT_ERROR):
raise ValueError("Lightness must be between 0 and 1.")
if s == 0:
return l, l, l
if l < 0.5:
v2 = l * (1.0 + s)
else:
v2 = (l + s) - (s * l)
v1 = 2.0 * l - v2
r = _hue2rgb(v1, v2, h + (1.0 / 3))
g = _hue2rgb(v1, v2, h)
b = _hue2rgb(v1, v2, h - (1.0 / 3))
return r, g, b | [
"def",
"hsl2rgb",
"(",
"hsl",
")",
":",
"h",
",",
"s",
",",
"l",
"=",
"[",
"float",
"(",
"v",
")",
"for",
"v",
"in",
"hsl",
"]",
"if",
"not",
"(",
"0.0",
"-",
"FLOAT_ERROR",
"<=",
"s",
"<=",
"1.0",
"+",
"FLOAT_ERROR",
")",
":",
"raise",
"Valu... | Convert HSL representation towards RGB
:param h: Hue, position around the chromatic circle (h=1 equiv h=0)
:param s: Saturation, color saturation (0=full gray, 1=full color)
:param l: Ligthness, Overhaul lightness (0=full black, 1=full white)
:rtype: 3-uple for RGB values in float between 0 and 1
Hue, Saturation, Range from Lightness is a float between 0 and 1
Note that Hue can be set to any value but as it is a rotation
around the chromatic circle, any value above 1 or below 0 can
be expressed by a value between 0 and 1 (Note that h=0 is equiv
to h=1).
This algorithm came from:
http://www.easyrgb.com/index.php?X=MATH&H=19#text19
Here are some quick notion of HSL to RGB conversion:
>>> from colour import hsl2rgb
With a lightness put at 0, RGB is always rgbblack
>>> hsl2rgb((0.0, 0.0, 0.0))
(0.0, 0.0, 0.0)
>>> hsl2rgb((0.5, 0.0, 0.0))
(0.0, 0.0, 0.0)
>>> hsl2rgb((0.5, 0.5, 0.0))
(0.0, 0.0, 0.0)
Same for lightness put at 1, RGB is always rgbwhite
>>> hsl2rgb((0.0, 0.0, 1.0))
(1.0, 1.0, 1.0)
>>> hsl2rgb((0.5, 0.0, 1.0))
(1.0, 1.0, 1.0)
>>> hsl2rgb((0.5, 0.5, 1.0))
(1.0, 1.0, 1.0)
With saturation put at 0, the RGB should be equal to Lightness:
>>> hsl2rgb((0.0, 0.0, 0.25))
(0.25, 0.25, 0.25)
>>> hsl2rgb((0.5, 0.0, 0.5))
(0.5, 0.5, 0.5)
>>> hsl2rgb((0.5, 0.0, 0.75))
(0.75, 0.75, 0.75)
With saturation put at 1, and lightness put to 0.5, we can find
normal full red, green, blue colors:
>>> hsl2rgb((0 , 1.0, 0.5))
(1.0, 0.0, 0.0)
>>> hsl2rgb((1 , 1.0, 0.5))
(1.0, 0.0, 0.0)
>>> hsl2rgb((1.0/3 , 1.0, 0.5))
(0.0, 1.0, 0.0)
>>> hsl2rgb((2.0/3 , 1.0, 0.5))
(0.0, 0.0, 1.0)
Of course:
>>> hsl2rgb((0.0, 2.0, 0.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Saturation must be between 0 and 1.
And:
>>> hsl2rgb((0.0, 0.0, 1.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Lightness must be between 0 and 1. | [
"Convert",
"HSL",
"representation",
"towards",
"RGB"
] | 11f138eb7841d2045160b378a2eec0c2321144c0 | https://github.com/vaab/colour/blob/11f138eb7841d2045160b378a2eec0c2321144c0/colour.py#L272-L367 | train | 203,078 |
vaab/colour | colour.py | rgb2hsl | def rgb2hsl(rgb):
"""Convert RGB representation towards HSL
:param r: Red amount (float between 0 and 1)
:param g: Green amount (float between 0 and 1)
:param b: Blue amount (float between 0 and 1)
:rtype: 3-uple for HSL values in float between 0 and 1
This algorithm came from:
http://www.easyrgb.com/index.php?X=MATH&H=19#text19
Here are some quick notion of RGB to HSL conversion:
>>> from colour import rgb2hsl
Note that if red amount is equal to green and blue, then you
should have a gray value (from black to white).
>>> rgb2hsl((1.0, 1.0, 1.0)) # doctest: +ELLIPSIS
(..., 0.0, 1.0)
>>> rgb2hsl((0.5, 0.5, 0.5)) # doctest: +ELLIPSIS
(..., 0.0, 0.5)
>>> rgb2hsl((0.0, 0.0, 0.0)) # doctest: +ELLIPSIS
(..., 0.0, 0.0)
If only one color is different from the others, it defines the
direct Hue:
>>> rgb2hsl((0.5, 0.5, 1.0)) # doctest: +ELLIPSIS
(0.66..., 1.0, 0.75)
>>> rgb2hsl((0.2, 0.1, 0.1)) # doctest: +ELLIPSIS
(0.0, 0.33..., 0.15...)
Having only one value set, you can check that:
>>> rgb2hsl((1.0, 0.0, 0.0))
(0.0, 1.0, 0.5)
>>> rgb2hsl((0.0, 1.0, 0.0)) # doctest: +ELLIPSIS
(0.33..., 1.0, 0.5)
>>> rgb2hsl((0.0, 0.0, 1.0)) # doctest: +ELLIPSIS
(0.66..., 1.0, 0.5)
Regression check upon very close values in every component of
red, green and blue:
>>> rgb2hsl((0.9999999999999999, 1.0, 0.9999999999999994))
(0.0, 0.0, 0.999...)
Of course:
>>> rgb2hsl((0.0, 2.0, 0.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Green must be between 0 and 1. You provided 2.0.
And:
>>> rgb2hsl((0.0, 0.0, 1.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Blue must be between 0 and 1. You provided 1.5.
"""
r, g, b = [float(v) for v in rgb]
for name, v in {'Red': r, 'Green': g, 'Blue': b}.items():
if not (0 - FLOAT_ERROR <= v <= 1 + FLOAT_ERROR):
raise ValueError("%s must be between 0 and 1. You provided %r."
% (name, v))
vmin = min(r, g, b) ## Min. value of RGB
vmax = max(r, g, b) ## Max. value of RGB
diff = vmax - vmin ## Delta RGB value
vsum = vmin + vmax
l = vsum / 2
if diff < FLOAT_ERROR: ## This is a gray, no chroma...
return (0.0, 0.0, l)
##
## Chromatic data...
##
## Saturation
if l < 0.5:
s = diff / vsum
else:
s = diff / (2.0 - vsum)
dr = (((vmax - r) / 6) + (diff / 2)) / diff
dg = (((vmax - g) / 6) + (diff / 2)) / diff
db = (((vmax - b) / 6) + (diff / 2)) / diff
if r == vmax:
h = db - dg
elif g == vmax:
h = (1.0 / 3) + dr - db
elif b == vmax:
h = (2.0 / 3) + dg - dr
if h < 0: h += 1
if h > 1: h -= 1
return (h, s, l) | python | def rgb2hsl(rgb):
"""Convert RGB representation towards HSL
:param r: Red amount (float between 0 and 1)
:param g: Green amount (float between 0 and 1)
:param b: Blue amount (float between 0 and 1)
:rtype: 3-uple for HSL values in float between 0 and 1
This algorithm came from:
http://www.easyrgb.com/index.php?X=MATH&H=19#text19
Here are some quick notion of RGB to HSL conversion:
>>> from colour import rgb2hsl
Note that if red amount is equal to green and blue, then you
should have a gray value (from black to white).
>>> rgb2hsl((1.0, 1.0, 1.0)) # doctest: +ELLIPSIS
(..., 0.0, 1.0)
>>> rgb2hsl((0.5, 0.5, 0.5)) # doctest: +ELLIPSIS
(..., 0.0, 0.5)
>>> rgb2hsl((0.0, 0.0, 0.0)) # doctest: +ELLIPSIS
(..., 0.0, 0.0)
If only one color is different from the others, it defines the
direct Hue:
>>> rgb2hsl((0.5, 0.5, 1.0)) # doctest: +ELLIPSIS
(0.66..., 1.0, 0.75)
>>> rgb2hsl((0.2, 0.1, 0.1)) # doctest: +ELLIPSIS
(0.0, 0.33..., 0.15...)
Having only one value set, you can check that:
>>> rgb2hsl((1.0, 0.0, 0.0))
(0.0, 1.0, 0.5)
>>> rgb2hsl((0.0, 1.0, 0.0)) # doctest: +ELLIPSIS
(0.33..., 1.0, 0.5)
>>> rgb2hsl((0.0, 0.0, 1.0)) # doctest: +ELLIPSIS
(0.66..., 1.0, 0.5)
Regression check upon very close values in every component of
red, green and blue:
>>> rgb2hsl((0.9999999999999999, 1.0, 0.9999999999999994))
(0.0, 0.0, 0.999...)
Of course:
>>> rgb2hsl((0.0, 2.0, 0.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Green must be between 0 and 1. You provided 2.0.
And:
>>> rgb2hsl((0.0, 0.0, 1.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Blue must be between 0 and 1. You provided 1.5.
"""
r, g, b = [float(v) for v in rgb]
for name, v in {'Red': r, 'Green': g, 'Blue': b}.items():
if not (0 - FLOAT_ERROR <= v <= 1 + FLOAT_ERROR):
raise ValueError("%s must be between 0 and 1. You provided %r."
% (name, v))
vmin = min(r, g, b) ## Min. value of RGB
vmax = max(r, g, b) ## Max. value of RGB
diff = vmax - vmin ## Delta RGB value
vsum = vmin + vmax
l = vsum / 2
if diff < FLOAT_ERROR: ## This is a gray, no chroma...
return (0.0, 0.0, l)
##
## Chromatic data...
##
## Saturation
if l < 0.5:
s = diff / vsum
else:
s = diff / (2.0 - vsum)
dr = (((vmax - r) / 6) + (diff / 2)) / diff
dg = (((vmax - g) / 6) + (diff / 2)) / diff
db = (((vmax - b) / 6) + (diff / 2)) / diff
if r == vmax:
h = db - dg
elif g == vmax:
h = (1.0 / 3) + dr - db
elif b == vmax:
h = (2.0 / 3) + dg - dr
if h < 0: h += 1
if h > 1: h -= 1
return (h, s, l) | [
"def",
"rgb2hsl",
"(",
"rgb",
")",
":",
"r",
",",
"g",
",",
"b",
"=",
"[",
"float",
"(",
"v",
")",
"for",
"v",
"in",
"rgb",
"]",
"for",
"name",
",",
"v",
"in",
"{",
"'Red'",
":",
"r",
",",
"'Green'",
":",
"g",
",",
"'Blue'",
":",
"b",
"}"... | Convert RGB representation towards HSL
:param r: Red amount (float between 0 and 1)
:param g: Green amount (float between 0 and 1)
:param b: Blue amount (float between 0 and 1)
:rtype: 3-uple for HSL values in float between 0 and 1
This algorithm came from:
http://www.easyrgb.com/index.php?X=MATH&H=19#text19
Here are some quick notion of RGB to HSL conversion:
>>> from colour import rgb2hsl
Note that if red amount is equal to green and blue, then you
should have a gray value (from black to white).
>>> rgb2hsl((1.0, 1.0, 1.0)) # doctest: +ELLIPSIS
(..., 0.0, 1.0)
>>> rgb2hsl((0.5, 0.5, 0.5)) # doctest: +ELLIPSIS
(..., 0.0, 0.5)
>>> rgb2hsl((0.0, 0.0, 0.0)) # doctest: +ELLIPSIS
(..., 0.0, 0.0)
If only one color is different from the others, it defines the
direct Hue:
>>> rgb2hsl((0.5, 0.5, 1.0)) # doctest: +ELLIPSIS
(0.66..., 1.0, 0.75)
>>> rgb2hsl((0.2, 0.1, 0.1)) # doctest: +ELLIPSIS
(0.0, 0.33..., 0.15...)
Having only one value set, you can check that:
>>> rgb2hsl((1.0, 0.0, 0.0))
(0.0, 1.0, 0.5)
>>> rgb2hsl((0.0, 1.0, 0.0)) # doctest: +ELLIPSIS
(0.33..., 1.0, 0.5)
>>> rgb2hsl((0.0, 0.0, 1.0)) # doctest: +ELLIPSIS
(0.66..., 1.0, 0.5)
Regression check upon very close values in every component of
red, green and blue:
>>> rgb2hsl((0.9999999999999999, 1.0, 0.9999999999999994))
(0.0, 0.0, 0.999...)
Of course:
>>> rgb2hsl((0.0, 2.0, 0.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Green must be between 0 and 1. You provided 2.0.
And:
>>> rgb2hsl((0.0, 0.0, 1.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Blue must be between 0 and 1. You provided 1.5. | [
"Convert",
"RGB",
"representation",
"towards",
"HSL"
] | 11f138eb7841d2045160b378a2eec0c2321144c0 | https://github.com/vaab/colour/blob/11f138eb7841d2045160b378a2eec0c2321144c0/colour.py#L370-L475 | train | 203,079 |
vaab/colour | colour.py | rgb2hex | def rgb2hex(rgb, force_long=False):
"""Transform RGB tuple to hex RGB representation
:param rgb: RGB 3-uple of float between 0 and 1
:rtype: 3 hex char or 6 hex char string representation
Usage
-----
>>> from colour import rgb2hex
>>> rgb2hex((0.0,1.0,0.0))
'#0f0'
Rounding try to be as natural as possible:
>>> rgb2hex((0.0,0.999999,1.0))
'#0ff'
And if not possible, the 6 hex char representation is used:
>>> rgb2hex((0.23,1.0,1.0))
'#3bffff'
>>> rgb2hex((0.0,0.999999,1.0), force_long=True)
'#00ffff'
"""
hx = ''.join(["%02x" % int(c * 255 + 0.5 - FLOAT_ERROR)
for c in rgb])
if not force_long and hx[0::2] == hx[1::2]:
hx = ''.join(hx[0::2])
return "#%s" % hx | python | def rgb2hex(rgb, force_long=False):
"""Transform RGB tuple to hex RGB representation
:param rgb: RGB 3-uple of float between 0 and 1
:rtype: 3 hex char or 6 hex char string representation
Usage
-----
>>> from colour import rgb2hex
>>> rgb2hex((0.0,1.0,0.0))
'#0f0'
Rounding try to be as natural as possible:
>>> rgb2hex((0.0,0.999999,1.0))
'#0ff'
And if not possible, the 6 hex char representation is used:
>>> rgb2hex((0.23,1.0,1.0))
'#3bffff'
>>> rgb2hex((0.0,0.999999,1.0), force_long=True)
'#00ffff'
"""
hx = ''.join(["%02x" % int(c * 255 + 0.5 - FLOAT_ERROR)
for c in rgb])
if not force_long and hx[0::2] == hx[1::2]:
hx = ''.join(hx[0::2])
return "#%s" % hx | [
"def",
"rgb2hex",
"(",
"rgb",
",",
"force_long",
"=",
"False",
")",
":",
"hx",
"=",
"''",
".",
"join",
"(",
"[",
"\"%02x\"",
"%",
"int",
"(",
"c",
"*",
"255",
"+",
"0.5",
"-",
"FLOAT_ERROR",
")",
"for",
"c",
"in",
"rgb",
"]",
")",
"if",
"not",
... | Transform RGB tuple to hex RGB representation
:param rgb: RGB 3-uple of float between 0 and 1
:rtype: 3 hex char or 6 hex char string representation
Usage
-----
>>> from colour import rgb2hex
>>> rgb2hex((0.0,1.0,0.0))
'#0f0'
Rounding try to be as natural as possible:
>>> rgb2hex((0.0,0.999999,1.0))
'#0ff'
And if not possible, the 6 hex char representation is used:
>>> rgb2hex((0.23,1.0,1.0))
'#3bffff'
>>> rgb2hex((0.0,0.999999,1.0), force_long=True)
'#00ffff' | [
"Transform",
"RGB",
"tuple",
"to",
"hex",
"RGB",
"representation"
] | 11f138eb7841d2045160b378a2eec0c2321144c0 | https://github.com/vaab/colour/blob/11f138eb7841d2045160b378a2eec0c2321144c0/colour.py#L495-L530 | train | 203,080 |
vaab/colour | colour.py | hex2rgb | def hex2rgb(str_rgb):
"""Transform hex RGB representation to RGB tuple
:param str_rgb: 3 hex char or 6 hex char string representation
:rtype: RGB 3-uple of float between 0 and 1
>>> from colour import hex2rgb
>>> hex2rgb('#00ff00')
(0.0, 1.0, 0.0)
>>> hex2rgb('#0f0')
(0.0, 1.0, 0.0)
>>> hex2rgb('#aaa') # doctest: +ELLIPSIS
(0.66..., 0.66..., 0.66...)
>>> hex2rgb('#aa') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Invalid value '#aa' provided for rgb color.
"""
try:
rgb = str_rgb[1:]
if len(rgb) == 6:
r, g, b = rgb[0:2], rgb[2:4], rgb[4:6]
elif len(rgb) == 3:
r, g, b = rgb[0] * 2, rgb[1] * 2, rgb[2] * 2
else:
raise ValueError()
except:
raise ValueError("Invalid value %r provided for rgb color."
% str_rgb)
return tuple([float(int(v, 16)) / 255 for v in (r, g, b)]) | python | def hex2rgb(str_rgb):
"""Transform hex RGB representation to RGB tuple
:param str_rgb: 3 hex char or 6 hex char string representation
:rtype: RGB 3-uple of float between 0 and 1
>>> from colour import hex2rgb
>>> hex2rgb('#00ff00')
(0.0, 1.0, 0.0)
>>> hex2rgb('#0f0')
(0.0, 1.0, 0.0)
>>> hex2rgb('#aaa') # doctest: +ELLIPSIS
(0.66..., 0.66..., 0.66...)
>>> hex2rgb('#aa') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Invalid value '#aa' provided for rgb color.
"""
try:
rgb = str_rgb[1:]
if len(rgb) == 6:
r, g, b = rgb[0:2], rgb[2:4], rgb[4:6]
elif len(rgb) == 3:
r, g, b = rgb[0] * 2, rgb[1] * 2, rgb[2] * 2
else:
raise ValueError()
except:
raise ValueError("Invalid value %r provided for rgb color."
% str_rgb)
return tuple([float(int(v, 16)) / 255 for v in (r, g, b)]) | [
"def",
"hex2rgb",
"(",
"str_rgb",
")",
":",
"try",
":",
"rgb",
"=",
"str_rgb",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"rgb",
")",
"==",
"6",
":",
"r",
",",
"g",
",",
"b",
"=",
"rgb",
"[",
"0",
":",
"2",
"]",
",",
"rgb",
"[",
"2",
":",
"4... | Transform hex RGB representation to RGB tuple
:param str_rgb: 3 hex char or 6 hex char string representation
:rtype: RGB 3-uple of float between 0 and 1
>>> from colour import hex2rgb
>>> hex2rgb('#00ff00')
(0.0, 1.0, 0.0)
>>> hex2rgb('#0f0')
(0.0, 1.0, 0.0)
>>> hex2rgb('#aaa') # doctest: +ELLIPSIS
(0.66..., 0.66..., 0.66...)
>>> hex2rgb('#aa') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Invalid value '#aa' provided for rgb color. | [
"Transform",
"hex",
"RGB",
"representation",
"to",
"RGB",
"tuple"
] | 11f138eb7841d2045160b378a2eec0c2321144c0 | https://github.com/vaab/colour/blob/11f138eb7841d2045160b378a2eec0c2321144c0/colour.py#L533-L570 | train | 203,081 |
vaab/colour | colour.py | hex2web | def hex2web(hex):
"""Converts HEX representation to WEB
:param rgb: 3 hex char or 6 hex char string representation
:rtype: web string representation (human readable if possible)
WEB representation uses X11 rgb.txt to define conversion
between RGB and english color names.
Usage
=====
>>> from colour import hex2web
>>> hex2web('#ff0000')
'red'
>>> hex2web('#aaaaaa')
'#aaa'
>>> hex2web('#abc')
'#abc'
>>> hex2web('#acacac')
'#acacac'
"""
dec_rgb = tuple(int(v * 255) for v in hex2rgb(hex))
if dec_rgb in RGB_TO_COLOR_NAMES:
## take the first one
color_name = RGB_TO_COLOR_NAMES[dec_rgb][0]
## Enforce full lowercase for single worded color name.
return color_name if len(re.sub(r"[^A-Z]", "", color_name)) > 1 \
else color_name.lower()
# Hex format is verified by hex2rgb function. And should be 3 or 6 digit
if len(hex) == 7:
if hex[1] == hex[2] and \
hex[3] == hex[4] and \
hex[5] == hex[6]:
return '#' + hex[1] + hex[3] + hex[5]
return hex | python | def hex2web(hex):
"""Converts HEX representation to WEB
:param rgb: 3 hex char or 6 hex char string representation
:rtype: web string representation (human readable if possible)
WEB representation uses X11 rgb.txt to define conversion
between RGB and english color names.
Usage
=====
>>> from colour import hex2web
>>> hex2web('#ff0000')
'red'
>>> hex2web('#aaaaaa')
'#aaa'
>>> hex2web('#abc')
'#abc'
>>> hex2web('#acacac')
'#acacac'
"""
dec_rgb = tuple(int(v * 255) for v in hex2rgb(hex))
if dec_rgb in RGB_TO_COLOR_NAMES:
## take the first one
color_name = RGB_TO_COLOR_NAMES[dec_rgb][0]
## Enforce full lowercase for single worded color name.
return color_name if len(re.sub(r"[^A-Z]", "", color_name)) > 1 \
else color_name.lower()
# Hex format is verified by hex2rgb function. And should be 3 or 6 digit
if len(hex) == 7:
if hex[1] == hex[2] and \
hex[3] == hex[4] and \
hex[5] == hex[6]:
return '#' + hex[1] + hex[3] + hex[5]
return hex | [
"def",
"hex2web",
"(",
"hex",
")",
":",
"dec_rgb",
"=",
"tuple",
"(",
"int",
"(",
"v",
"*",
"255",
")",
"for",
"v",
"in",
"hex2rgb",
"(",
"hex",
")",
")",
"if",
"dec_rgb",
"in",
"RGB_TO_COLOR_NAMES",
":",
"## take the first one",
"color_name",
"=",
"RG... | Converts HEX representation to WEB
:param rgb: 3 hex char or 6 hex char string representation
:rtype: web string representation (human readable if possible)
WEB representation uses X11 rgb.txt to define conversion
between RGB and english color names.
Usage
=====
>>> from colour import hex2web
>>> hex2web('#ff0000')
'red'
>>> hex2web('#aaaaaa')
'#aaa'
>>> hex2web('#abc')
'#abc'
>>> hex2web('#acacac')
'#acacac' | [
"Converts",
"HEX",
"representation",
"to",
"WEB"
] | 11f138eb7841d2045160b378a2eec0c2321144c0 | https://github.com/vaab/colour/blob/11f138eb7841d2045160b378a2eec0c2321144c0/colour.py#L573-L614 | train | 203,082 |
vaab/colour | colour.py | web2hex | def web2hex(web, force_long=False):
"""Converts WEB representation to HEX
:param rgb: web string representation (human readable if possible)
:rtype: 3 hex char or 6 hex char string representation
WEB representation uses X11 rgb.txt to define conversion
between RGB and english color names.
Usage
=====
>>> from colour import web2hex
>>> web2hex('red')
'#f00'
>>> web2hex('#aaa')
'#aaa'
>>> web2hex('#foo') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: '#foo' is not in web format. Need 3 or 6 hex digit.
>>> web2hex('#aaa', force_long=True)
'#aaaaaa'
>>> web2hex('#aaaaaa')
'#aaaaaa'
>>> web2hex('#aaaa') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: '#aaaa' is not in web format. Need 3 or 6 hex digit.
>>> web2hex('pinky') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: 'pinky' is not a recognized color.
And color names are case insensitive:
>>> Color('RED')
<Color red>
"""
if web.startswith('#'):
if (LONG_HEX_COLOR.match(web) or
(not force_long and SHORT_HEX_COLOR.match(web))):
return web.lower()
elif SHORT_HEX_COLOR.match(web) and force_long:
return '#' + ''.join([("%s" % (t, )) * 2 for t in web[1:]])
raise AttributeError(
"%r is not in web format. Need 3 or 6 hex digit." % web)
web = web.lower()
if web not in COLOR_NAME_TO_RGB:
raise ValueError("%r is not a recognized color." % web)
## convert dec to hex:
return rgb2hex([float(int(v)) / 255 for v in COLOR_NAME_TO_RGB[web]],
force_long) | python | def web2hex(web, force_long=False):
"""Converts WEB representation to HEX
:param rgb: web string representation (human readable if possible)
:rtype: 3 hex char or 6 hex char string representation
WEB representation uses X11 rgb.txt to define conversion
between RGB and english color names.
Usage
=====
>>> from colour import web2hex
>>> web2hex('red')
'#f00'
>>> web2hex('#aaa')
'#aaa'
>>> web2hex('#foo') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: '#foo' is not in web format. Need 3 or 6 hex digit.
>>> web2hex('#aaa', force_long=True)
'#aaaaaa'
>>> web2hex('#aaaaaa')
'#aaaaaa'
>>> web2hex('#aaaa') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: '#aaaa' is not in web format. Need 3 or 6 hex digit.
>>> web2hex('pinky') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: 'pinky' is not a recognized color.
And color names are case insensitive:
>>> Color('RED')
<Color red>
"""
if web.startswith('#'):
if (LONG_HEX_COLOR.match(web) or
(not force_long and SHORT_HEX_COLOR.match(web))):
return web.lower()
elif SHORT_HEX_COLOR.match(web) and force_long:
return '#' + ''.join([("%s" % (t, )) * 2 for t in web[1:]])
raise AttributeError(
"%r is not in web format. Need 3 or 6 hex digit." % web)
web = web.lower()
if web not in COLOR_NAME_TO_RGB:
raise ValueError("%r is not a recognized color." % web)
## convert dec to hex:
return rgb2hex([float(int(v)) / 255 for v in COLOR_NAME_TO_RGB[web]],
force_long) | [
"def",
"web2hex",
"(",
"web",
",",
"force_long",
"=",
"False",
")",
":",
"if",
"web",
".",
"startswith",
"(",
"'#'",
")",
":",
"if",
"(",
"LONG_HEX_COLOR",
".",
"match",
"(",
"web",
")",
"or",
"(",
"not",
"force_long",
"and",
"SHORT_HEX_COLOR",
".",
... | Converts WEB representation to HEX
:param rgb: web string representation (human readable if possible)
:rtype: 3 hex char or 6 hex char string representation
WEB representation uses X11 rgb.txt to define conversion
between RGB and english color names.
Usage
=====
>>> from colour import web2hex
>>> web2hex('red')
'#f00'
>>> web2hex('#aaa')
'#aaa'
>>> web2hex('#foo') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: '#foo' is not in web format. Need 3 or 6 hex digit.
>>> web2hex('#aaa', force_long=True)
'#aaaaaa'
>>> web2hex('#aaaaaa')
'#aaaaaa'
>>> web2hex('#aaaa') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: '#aaaa' is not in web format. Need 3 or 6 hex digit.
>>> web2hex('pinky') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: 'pinky' is not a recognized color.
And color names are case insensitive:
>>> Color('RED')
<Color red> | [
"Converts",
"WEB",
"representation",
"to",
"HEX"
] | 11f138eb7841d2045160b378a2eec0c2321144c0 | https://github.com/vaab/colour/blob/11f138eb7841d2045160b378a2eec0c2321144c0/colour.py#L617-L680 | train | 203,083 |
vaab/colour | colour.py | color_scale | def color_scale(begin_hsl, end_hsl, nb):
"""Returns a list of nb color HSL tuples between begin_hsl and end_hsl
>>> from colour import color_scale
>>> [rgb2hex(hsl2rgb(hsl)) for hsl in color_scale((0, 1, 0.5),
... (1, 1, 0.5), 3)]
['#f00', '#0f0', '#00f', '#f00']
>>> [rgb2hex(hsl2rgb(hsl))
... for hsl in color_scale((0, 0, 0),
... (0, 0, 1),
... 15)] # doctest: +ELLIPSIS
['#000', '#111', '#222', ..., '#ccc', '#ddd', '#eee', '#fff']
Of course, asking for negative values is not supported:
>>> color_scale((0, 1, 0.5), (1, 1, 0.5), -2)
Traceback (most recent call last):
...
ValueError: Unsupported negative number of colors (nb=-2).
"""
if nb < 0:
raise ValueError(
"Unsupported negative number of colors (nb=%r)." % nb)
step = tuple([float(end_hsl[i] - begin_hsl[i]) / nb for i in range(0, 3)]) \
if nb > 0 else (0, 0, 0)
def mul(step, value):
return tuple([v * value for v in step])
def add_v(step, step2):
return tuple([v + step2[i] for i, v in enumerate(step)])
return [add_v(begin_hsl, mul(step, r)) for r in range(0, nb + 1)] | python | def color_scale(begin_hsl, end_hsl, nb):
"""Returns a list of nb color HSL tuples between begin_hsl and end_hsl
>>> from colour import color_scale
>>> [rgb2hex(hsl2rgb(hsl)) for hsl in color_scale((0, 1, 0.5),
... (1, 1, 0.5), 3)]
['#f00', '#0f0', '#00f', '#f00']
>>> [rgb2hex(hsl2rgb(hsl))
... for hsl in color_scale((0, 0, 0),
... (0, 0, 1),
... 15)] # doctest: +ELLIPSIS
['#000', '#111', '#222', ..., '#ccc', '#ddd', '#eee', '#fff']
Of course, asking for negative values is not supported:
>>> color_scale((0, 1, 0.5), (1, 1, 0.5), -2)
Traceback (most recent call last):
...
ValueError: Unsupported negative number of colors (nb=-2).
"""
if nb < 0:
raise ValueError(
"Unsupported negative number of colors (nb=%r)." % nb)
step = tuple([float(end_hsl[i] - begin_hsl[i]) / nb for i in range(0, 3)]) \
if nb > 0 else (0, 0, 0)
def mul(step, value):
return tuple([v * value for v in step])
def add_v(step, step2):
return tuple([v + step2[i] for i, v in enumerate(step)])
return [add_v(begin_hsl, mul(step, r)) for r in range(0, nb + 1)] | [
"def",
"color_scale",
"(",
"begin_hsl",
",",
"end_hsl",
",",
"nb",
")",
":",
"if",
"nb",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Unsupported negative number of colors (nb=%r).\"",
"%",
"nb",
")",
"step",
"=",
"tuple",
"(",
"[",
"float",
"(",
"end_hsl",... | Returns a list of nb color HSL tuples between begin_hsl and end_hsl
>>> from colour import color_scale
>>> [rgb2hex(hsl2rgb(hsl)) for hsl in color_scale((0, 1, 0.5),
... (1, 1, 0.5), 3)]
['#f00', '#0f0', '#00f', '#f00']
>>> [rgb2hex(hsl2rgb(hsl))
... for hsl in color_scale((0, 0, 0),
... (0, 0, 1),
... 15)] # doctest: +ELLIPSIS
['#000', '#111', '#222', ..., '#ccc', '#ddd', '#eee', '#fff']
Of course, asking for negative values is not supported:
>>> color_scale((0, 1, 0.5), (1, 1, 0.5), -2)
Traceback (most recent call last):
...
ValueError: Unsupported negative number of colors (nb=-2). | [
"Returns",
"a",
"list",
"of",
"nb",
"color",
"HSL",
"tuples",
"between",
"begin_hsl",
"and",
"end_hsl"
] | 11f138eb7841d2045160b378a2eec0c2321144c0 | https://github.com/vaab/colour/blob/11f138eb7841d2045160b378a2eec0c2321144c0/colour.py#L693-L730 | train | 203,084 |
vaab/colour | colour.py | RGB_color_picker | def RGB_color_picker(obj):
"""Build a color representation from the string representation of an object
This allows to quickly get a color from some data, with the
additional benefit that the color will be the same as long as the
(string representation of the) data is the same::
>>> from colour import RGB_color_picker, Color
Same inputs produce the same result::
>>> RGB_color_picker("Something") == RGB_color_picker("Something")
True
... but different inputs produce different colors::
>>> RGB_color_picker("Something") != RGB_color_picker("Something else")
True
In any case, we still get a ``Color`` object::
>>> isinstance(RGB_color_picker("Something"), Color)
True
"""
## Turn the input into a by 3-dividable string. SHA-384 is good because it
## divides into 3 components of the same size, which will be used to
## represent the RGB values of the color.
digest = hashlib.sha384(str(obj).encode('utf-8')).hexdigest()
## Split the digest into 3 sub-strings of equivalent size.
subsize = int(len(digest) / 3)
splitted_digest = [digest[i * subsize: (i + 1) * subsize]
for i in range(3)]
## Convert those hexadecimal sub-strings into integer and scale them down
## to the 0..1 range.
max_value = float(int("f" * subsize, 16))
components = (
int(d, 16) ## Make a number from a list with hex digits
/ max_value ## Scale it down to [0.0, 1.0]
for d in splitted_digest)
return Color(rgb2hex(components)) | python | def RGB_color_picker(obj):
"""Build a color representation from the string representation of an object
This allows to quickly get a color from some data, with the
additional benefit that the color will be the same as long as the
(string representation of the) data is the same::
>>> from colour import RGB_color_picker, Color
Same inputs produce the same result::
>>> RGB_color_picker("Something") == RGB_color_picker("Something")
True
... but different inputs produce different colors::
>>> RGB_color_picker("Something") != RGB_color_picker("Something else")
True
In any case, we still get a ``Color`` object::
>>> isinstance(RGB_color_picker("Something"), Color)
True
"""
## Turn the input into a by 3-dividable string. SHA-384 is good because it
## divides into 3 components of the same size, which will be used to
## represent the RGB values of the color.
digest = hashlib.sha384(str(obj).encode('utf-8')).hexdigest()
## Split the digest into 3 sub-strings of equivalent size.
subsize = int(len(digest) / 3)
splitted_digest = [digest[i * subsize: (i + 1) * subsize]
for i in range(3)]
## Convert those hexadecimal sub-strings into integer and scale them down
## to the 0..1 range.
max_value = float(int("f" * subsize, 16))
components = (
int(d, 16) ## Make a number from a list with hex digits
/ max_value ## Scale it down to [0.0, 1.0]
for d in splitted_digest)
return Color(rgb2hex(components)) | [
"def",
"RGB_color_picker",
"(",
"obj",
")",
":",
"## Turn the input into a by 3-dividable string. SHA-384 is good because it",
"## divides into 3 components of the same size, which will be used to",
"## represent the RGB values of the color.",
"digest",
"=",
"hashlib",
".",
"sha384",
"("... | Build a color representation from the string representation of an object
This allows to quickly get a color from some data, with the
additional benefit that the color will be the same as long as the
(string representation of the) data is the same::
>>> from colour import RGB_color_picker, Color
Same inputs produce the same result::
>>> RGB_color_picker("Something") == RGB_color_picker("Something")
True
... but different inputs produce different colors::
>>> RGB_color_picker("Something") != RGB_color_picker("Something else")
True
In any case, we still get a ``Color`` object::
>>> isinstance(RGB_color_picker("Something"), Color)
True | [
"Build",
"a",
"color",
"representation",
"from",
"the",
"string",
"representation",
"of",
"an",
"object"
] | 11f138eb7841d2045160b378a2eec0c2321144c0 | https://github.com/vaab/colour/blob/11f138eb7841d2045160b378a2eec0c2321144c0/colour.py#L737-L781 | train | 203,085 |
sarugaku/requirementslib | src/requirementslib/models/markers.py | _strip_marker_elem | def _strip_marker_elem(elem_name, elements):
"""Remove the supplied element from the marker.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The element's operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator associated with it.
"""
extra_indexes = []
preceding_operators = ["and"] if elem_name == "extra" else ["and", "or"]
for i, element in enumerate(elements):
if isinstance(element, list):
cancelled = _strip_marker_elem(elem_name, element)
if cancelled:
extra_indexes.append(i)
elif isinstance(element, tuple) and element[0].value == elem_name:
extra_indexes.append(i)
for i in reversed(extra_indexes):
del elements[i]
if i > 0 and elements[i - 1] in preceding_operators:
# Remove the "and" before it.
del elements[i - 1]
elif elements:
# This shouldn't ever happen, but is included for completeness.
# If there is not an "and" before this element, try to remove the
# operator after it.
del elements[0]
return not elements | python | def _strip_marker_elem(elem_name, elements):
"""Remove the supplied element from the marker.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The element's operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator associated with it.
"""
extra_indexes = []
preceding_operators = ["and"] if elem_name == "extra" else ["and", "or"]
for i, element in enumerate(elements):
if isinstance(element, list):
cancelled = _strip_marker_elem(elem_name, element)
if cancelled:
extra_indexes.append(i)
elif isinstance(element, tuple) and element[0].value == elem_name:
extra_indexes.append(i)
for i in reversed(extra_indexes):
del elements[i]
if i > 0 and elements[i - 1] in preceding_operators:
# Remove the "and" before it.
del elements[i - 1]
elif elements:
# This shouldn't ever happen, but is included for completeness.
# If there is not an "and" before this element, try to remove the
# operator after it.
del elements[0]
return not elements | [
"def",
"_strip_marker_elem",
"(",
"elem_name",
",",
"elements",
")",
":",
"extra_indexes",
"=",
"[",
"]",
"preceding_operators",
"=",
"[",
"\"and\"",
"]",
"if",
"elem_name",
"==",
"\"extra\"",
"else",
"[",
"\"and\"",
",",
"\"or\"",
"]",
"for",
"i",
",",
"e... | Remove the supplied element from the marker.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The element's operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator associated with it. | [
"Remove",
"the",
"supplied",
"element",
"from",
"the",
"marker",
"."
] | de78a01e8abc1fc47155516a96008d97035e8063 | https://github.com/sarugaku/requirementslib/blob/de78a01e8abc1fc47155516a96008d97035e8063/src/requirementslib/models/markers.py#L310-L338 | train | 203,086 |
sarugaku/requirementslib | src/requirementslib/models/markers.py | _get_stripped_marker | def _get_stripped_marker(marker, strip_func):
"""Build a new marker which is cleaned according to `strip_func`"""
if not marker:
return None
marker = _ensure_marker(marker)
elements = marker._markers
strip_func(elements)
if elements:
return marker
return None | python | def _get_stripped_marker(marker, strip_func):
"""Build a new marker which is cleaned according to `strip_func`"""
if not marker:
return None
marker = _ensure_marker(marker)
elements = marker._markers
strip_func(elements)
if elements:
return marker
return None | [
"def",
"_get_stripped_marker",
"(",
"marker",
",",
"strip_func",
")",
":",
"if",
"not",
"marker",
":",
"return",
"None",
"marker",
"=",
"_ensure_marker",
"(",
"marker",
")",
"elements",
"=",
"marker",
".",
"_markers",
"strip_func",
"(",
"elements",
")",
"if"... | Build a new marker which is cleaned according to `strip_func` | [
"Build",
"a",
"new",
"marker",
"which",
"is",
"cleaned",
"according",
"to",
"strip_func"
] | de78a01e8abc1fc47155516a96008d97035e8063 | https://github.com/sarugaku/requirementslib/blob/de78a01e8abc1fc47155516a96008d97035e8063/src/requirementslib/models/markers.py#L341-L351 | train | 203,087 |
sarugaku/requirementslib | src/requirementslib/models/markers.py | get_contained_pyversions | def get_contained_pyversions(marker):
"""Collect all `python_version` operands from a marker.
"""
collection = []
if not marker:
return set()
marker = _ensure_marker(marker)
# Collect the (Variable, Op, Value) tuples and string joiners from the marker
_markers_collect_pyversions(marker._markers, collection)
marker_str = " and ".join(sorted(collection))
if not marker_str:
return set()
# Use the distlib dictionary parser to create a dictionary 'trie' which is a bit
# easier to reason about
marker_dict = distlib.markers.parse_marker(marker_str)[0]
version_set = set()
pyversions, _ = parse_marker_dict(marker_dict)
if isinstance(pyversions, set):
version_set.update(pyversions)
elif pyversions is not None:
version_set.add(pyversions)
# Each distinct element in the set was separated by an "and" operator in the marker
# So we will need to reduce them with an intersection here rather than a union
# in order to find the boundaries
versions = set()
if version_set:
versions = reduce(lambda x, y: x & y, version_set)
return versions | python | def get_contained_pyversions(marker):
"""Collect all `python_version` operands from a marker.
"""
collection = []
if not marker:
return set()
marker = _ensure_marker(marker)
# Collect the (Variable, Op, Value) tuples and string joiners from the marker
_markers_collect_pyversions(marker._markers, collection)
marker_str = " and ".join(sorted(collection))
if not marker_str:
return set()
# Use the distlib dictionary parser to create a dictionary 'trie' which is a bit
# easier to reason about
marker_dict = distlib.markers.parse_marker(marker_str)[0]
version_set = set()
pyversions, _ = parse_marker_dict(marker_dict)
if isinstance(pyversions, set):
version_set.update(pyversions)
elif pyversions is not None:
version_set.add(pyversions)
# Each distinct element in the set was separated by an "and" operator in the marker
# So we will need to reduce them with an intersection here rather than a union
# in order to find the boundaries
versions = set()
if version_set:
versions = reduce(lambda x, y: x & y, version_set)
return versions | [
"def",
"get_contained_pyversions",
"(",
"marker",
")",
":",
"collection",
"=",
"[",
"]",
"if",
"not",
"marker",
":",
"return",
"set",
"(",
")",
"marker",
"=",
"_ensure_marker",
"(",
"marker",
")",
"# Collect the (Variable, Op, Value) tuples and string joiners from the... | Collect all `python_version` operands from a marker. | [
"Collect",
"all",
"python_version",
"operands",
"from",
"a",
"marker",
"."
] | de78a01e8abc1fc47155516a96008d97035e8063 | https://github.com/sarugaku/requirementslib/blob/de78a01e8abc1fc47155516a96008d97035e8063/src/requirementslib/models/markers.py#L433-L461 | train | 203,088 |
sarugaku/requirementslib | src/requirementslib/models/markers.py | contains_pyversion | def contains_pyversion(marker):
"""Check whether a marker contains a python_version operand.
"""
if not marker:
return False
marker = _ensure_marker(marker)
return _markers_contains_pyversion(marker._markers) | python | def contains_pyversion(marker):
"""Check whether a marker contains a python_version operand.
"""
if not marker:
return False
marker = _ensure_marker(marker)
return _markers_contains_pyversion(marker._markers) | [
"def",
"contains_pyversion",
"(",
"marker",
")",
":",
"if",
"not",
"marker",
":",
"return",
"False",
"marker",
"=",
"_ensure_marker",
"(",
"marker",
")",
"return",
"_markers_contains_pyversion",
"(",
"marker",
".",
"_markers",
")"
] | Check whether a marker contains a python_version operand. | [
"Check",
"whether",
"a",
"marker",
"contains",
"a",
"python_version",
"operand",
"."
] | de78a01e8abc1fc47155516a96008d97035e8063 | https://github.com/sarugaku/requirementslib/blob/de78a01e8abc1fc47155516a96008d97035e8063/src/requirementslib/models/markers.py#L475-L482 | train | 203,089 |
perrygeo/simanneal | examples/salesman.py | distance | def distance(a, b):
"""Calculates distance between two latitude-longitude coordinates."""
R = 3963 # radius of Earth (miles)
lat1, lon1 = math.radians(a[0]), math.radians(a[1])
lat2, lon2 = math.radians(b[0]), math.radians(b[1])
return math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) * math.cos(lon1 - lon2)) * R | python | def distance(a, b):
"""Calculates distance between two latitude-longitude coordinates."""
R = 3963 # radius of Earth (miles)
lat1, lon1 = math.radians(a[0]), math.radians(a[1])
lat2, lon2 = math.radians(b[0]), math.radians(b[1])
return math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) * math.cos(lon1 - lon2)) * R | [
"def",
"distance",
"(",
"a",
",",
"b",
")",
":",
"R",
"=",
"3963",
"# radius of Earth (miles)",
"lat1",
",",
"lon1",
"=",
"math",
".",
"radians",
"(",
"a",
"[",
"0",
"]",
")",
",",
"math",
".",
"radians",
"(",
"a",
"[",
"1",
"]",
")",
"lat2",
"... | Calculates distance between two latitude-longitude coordinates. | [
"Calculates",
"distance",
"between",
"two",
"latitude",
"-",
"longitude",
"coordinates",
"."
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/salesman.py#L7-L13 | train | 203,090 |
perrygeo/simanneal | examples/salesman.py | TravellingSalesmanProblem.energy | def energy(self):
"""Calculates the length of the route."""
e = 0
for i in range(len(self.state)):
e += self.distance_matrix[self.state[i-1]][self.state[i]]
return e | python | def energy(self):
"""Calculates the length of the route."""
e = 0
for i in range(len(self.state)):
e += self.distance_matrix[self.state[i-1]][self.state[i]]
return e | [
"def",
"energy",
"(",
"self",
")",
":",
"e",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"state",
")",
")",
":",
"e",
"+=",
"self",
".",
"distance_matrix",
"[",
"self",
".",
"state",
"[",
"i",
"-",
"1",
"]",
"]",
"[",
... | Calculates the length of the route. | [
"Calculates",
"the",
"length",
"of",
"the",
"route",
"."
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/salesman.py#L32-L37 | train | 203,091 |
perrygeo/simanneal | simanneal/anneal.py | round_figures | def round_figures(x, n):
"""Returns x rounded to n significant figures."""
return round(x, int(n - math.ceil(math.log10(abs(x))))) | python | def round_figures(x, n):
"""Returns x rounded to n significant figures."""
return round(x, int(n - math.ceil(math.log10(abs(x))))) | [
"def",
"round_figures",
"(",
"x",
",",
"n",
")",
":",
"return",
"round",
"(",
"x",
",",
"int",
"(",
"n",
"-",
"math",
".",
"ceil",
"(",
"math",
".",
"log10",
"(",
"abs",
"(",
"x",
")",
")",
")",
")",
")"
] | Returns x rounded to n significant figures. | [
"Returns",
"x",
"rounded",
"to",
"n",
"significant",
"figures",
"."
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/simanneal/anneal.py#L16-L18 | train | 203,092 |
perrygeo/simanneal | simanneal/anneal.py | Annealer.save_state | def save_state(self, fname=None):
"""Saves state to pickle"""
if not fname:
date = datetime.datetime.now().strftime("%Y-%m-%dT%Hh%Mm%Ss")
fname = date + "_energy_" + str(self.energy()) + ".state"
with open(fname, "wb") as fh:
pickle.dump(self.state, fh) | python | def save_state(self, fname=None):
"""Saves state to pickle"""
if not fname:
date = datetime.datetime.now().strftime("%Y-%m-%dT%Hh%Mm%Ss")
fname = date + "_energy_" + str(self.energy()) + ".state"
with open(fname, "wb") as fh:
pickle.dump(self.state, fh) | [
"def",
"save_state",
"(",
"self",
",",
"fname",
"=",
"None",
")",
":",
"if",
"not",
"fname",
":",
"date",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y-%m-%dT%Hh%Mm%Ss\"",
")",
"fname",
"=",
"date",
"+",
"\"_energy... | Saves state to pickle | [
"Saves",
"state",
"to",
"pickle"
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/simanneal/anneal.py#L63-L69 | train | 203,093 |
perrygeo/simanneal | simanneal/anneal.py | Annealer.load_state | def load_state(self, fname=None):
"""Loads state from pickle"""
with open(fname, 'rb') as fh:
self.state = pickle.load(fh) | python | def load_state(self, fname=None):
"""Loads state from pickle"""
with open(fname, 'rb') as fh:
self.state = pickle.load(fh) | [
"def",
"load_state",
"(",
"self",
",",
"fname",
"=",
"None",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'rb'",
")",
"as",
"fh",
":",
"self",
".",
"state",
"=",
"pickle",
".",
"load",
"(",
"fh",
")"
] | Loads state from pickle | [
"Loads",
"state",
"from",
"pickle"
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/simanneal/anneal.py#L71-L74 | train | 203,094 |
perrygeo/simanneal | simanneal/anneal.py | Annealer.set_schedule | def set_schedule(self, schedule):
"""Takes the output from `auto` and sets the attributes
"""
self.Tmax = schedule['tmax']
self.Tmin = schedule['tmin']
self.steps = int(schedule['steps'])
self.updates = int(schedule['updates']) | python | def set_schedule(self, schedule):
"""Takes the output from `auto` and sets the attributes
"""
self.Tmax = schedule['tmax']
self.Tmin = schedule['tmin']
self.steps = int(schedule['steps'])
self.updates = int(schedule['updates']) | [
"def",
"set_schedule",
"(",
"self",
",",
"schedule",
")",
":",
"self",
".",
"Tmax",
"=",
"schedule",
"[",
"'tmax'",
"]",
"self",
".",
"Tmin",
"=",
"schedule",
"[",
"'tmin'",
"]",
"self",
".",
"steps",
"=",
"int",
"(",
"schedule",
"[",
"'steps'",
"]",... | Takes the output from `auto` and sets the attributes | [
"Takes",
"the",
"output",
"from",
"auto",
"and",
"sets",
"the",
"attributes"
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/simanneal/anneal.py#L91-L97 | train | 203,095 |
perrygeo/simanneal | simanneal/anneal.py | Annealer.copy_state | def copy_state(self, state):
"""Returns an exact copy of the provided state
Implemented according to self.copy_strategy, one of
* deepcopy : use copy.deepcopy (slow but reliable)
* slice: use list slices (faster but only works if state is list-like)
* method: use the state's copy() method
"""
if self.copy_strategy == 'deepcopy':
return copy.deepcopy(state)
elif self.copy_strategy == 'slice':
return state[:]
elif self.copy_strategy == 'method':
return state.copy()
else:
raise RuntimeError('No implementation found for ' +
'the self.copy_strategy "%s"' %
self.copy_strategy) | python | def copy_state(self, state):
"""Returns an exact copy of the provided state
Implemented according to self.copy_strategy, one of
* deepcopy : use copy.deepcopy (slow but reliable)
* slice: use list slices (faster but only works if state is list-like)
* method: use the state's copy() method
"""
if self.copy_strategy == 'deepcopy':
return copy.deepcopy(state)
elif self.copy_strategy == 'slice':
return state[:]
elif self.copy_strategy == 'method':
return state.copy()
else:
raise RuntimeError('No implementation found for ' +
'the self.copy_strategy "%s"' %
self.copy_strategy) | [
"def",
"copy_state",
"(",
"self",
",",
"state",
")",
":",
"if",
"self",
".",
"copy_strategy",
"==",
"'deepcopy'",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"state",
")",
"elif",
"self",
".",
"copy_strategy",
"==",
"'slice'",
":",
"return",
"state",
"[... | Returns an exact copy of the provided state
Implemented according to self.copy_strategy, one of
* deepcopy : use copy.deepcopy (slow but reliable)
* slice: use list slices (faster but only works if state is list-like)
* method: use the state's copy() method | [
"Returns",
"an",
"exact",
"copy",
"of",
"the",
"provided",
"state",
"Implemented",
"according",
"to",
"self",
".",
"copy_strategy",
"one",
"of"
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/simanneal/anneal.py#L99-L116 | train | 203,096 |
perrygeo/simanneal | simanneal/anneal.py | Annealer.default_update | def default_update(self, step, T, E, acceptance, improvement):
"""Default update, outputs to stderr.
Prints the current temperature, energy, acceptance rate,
improvement rate, elapsed time, and remaining time.
The acceptance rate indicates the percentage of moves since the last
update that were accepted by the Metropolis algorithm. It includes
moves that decreased the energy, moves that left the energy
unchanged, and moves that increased the energy yet were reached by
thermal excitation.
The improvement rate indicates the percentage of moves since the
last update that strictly decreased the energy. At high
temperatures it will include both moves that improved the overall
state and moves that simply undid previously accepted moves that
increased the energy by thermal excititation. At low temperatures
it will tend toward zero as the moves that can decrease the energy
are exhausted and moves that would increase the energy are no longer
thermally accessible."""
elapsed = time.time() - self.start
if step == 0:
print(' Temperature Energy Accept Improve Elapsed Remaining',
file=sys.stderr)
print('\r%12.5f %12.2f %s ' %
(T, E, time_string(elapsed)), file=sys.stderr, end="\r")
sys.stderr.flush()
else:
remain = (self.steps - step) * (elapsed / step)
print('\r%12.5f %12.2f %7.2f%% %7.2f%% %s %s\r' %
(T, E, 100.0 * acceptance, 100.0 * improvement,
time_string(elapsed), time_string(remain)), file=sys.stderr, end="\r")
sys.stderr.flush() | python | def default_update(self, step, T, E, acceptance, improvement):
"""Default update, outputs to stderr.
Prints the current temperature, energy, acceptance rate,
improvement rate, elapsed time, and remaining time.
The acceptance rate indicates the percentage of moves since the last
update that were accepted by the Metropolis algorithm. It includes
moves that decreased the energy, moves that left the energy
unchanged, and moves that increased the energy yet were reached by
thermal excitation.
The improvement rate indicates the percentage of moves since the
last update that strictly decreased the energy. At high
temperatures it will include both moves that improved the overall
state and moves that simply undid previously accepted moves that
increased the energy by thermal excititation. At low temperatures
it will tend toward zero as the moves that can decrease the energy
are exhausted and moves that would increase the energy are no longer
thermally accessible."""
elapsed = time.time() - self.start
if step == 0:
print(' Temperature Energy Accept Improve Elapsed Remaining',
file=sys.stderr)
print('\r%12.5f %12.2f %s ' %
(T, E, time_string(elapsed)), file=sys.stderr, end="\r")
sys.stderr.flush()
else:
remain = (self.steps - step) * (elapsed / step)
print('\r%12.5f %12.2f %7.2f%% %7.2f%% %s %s\r' %
(T, E, 100.0 * acceptance, 100.0 * improvement,
time_string(elapsed), time_string(remain)), file=sys.stderr, end="\r")
sys.stderr.flush() | [
"def",
"default_update",
"(",
"self",
",",
"step",
",",
"T",
",",
"E",
",",
"acceptance",
",",
"improvement",
")",
":",
"elapsed",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"start",
"if",
"step",
"==",
"0",
":",
"print",
"(",
"' Tempera... | Default update, outputs to stderr.
Prints the current temperature, energy, acceptance rate,
improvement rate, elapsed time, and remaining time.
The acceptance rate indicates the percentage of moves since the last
update that were accepted by the Metropolis algorithm. It includes
moves that decreased the energy, moves that left the energy
unchanged, and moves that increased the energy yet were reached by
thermal excitation.
The improvement rate indicates the percentage of moves since the
last update that strictly decreased the energy. At high
temperatures it will include both moves that improved the overall
state and moves that simply undid previously accepted moves that
increased the energy by thermal excititation. At low temperatures
it will tend toward zero as the moves that can decrease the energy
are exhausted and moves that would increase the energy are no longer
thermally accessible. | [
"Default",
"update",
"outputs",
"to",
"stderr",
"."
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/simanneal/anneal.py#L127-L160 | train | 203,097 |
perrygeo/simanneal | simanneal/anneal.py | Annealer.anneal | def anneal(self):
"""Minimizes the energy of a system by simulated annealing.
Parameters
state : an initial arrangement of the system
Returns
(state, energy): the best state and energy found.
"""
step = 0
self.start = time.time()
# Precompute factor for exponential cooling from Tmax to Tmin
if self.Tmin <= 0.0:
raise Exception('Exponential cooling requires a minimum "\
"temperature greater than zero.')
Tfactor = -math.log(self.Tmax / self.Tmin)
# Note initial state
T = self.Tmax
E = self.energy()
prevState = self.copy_state(self.state)
prevEnergy = E
self.best_state = self.copy_state(self.state)
self.best_energy = E
trials, accepts, improves = 0, 0, 0
if self.updates > 0:
updateWavelength = self.steps / self.updates
self.update(step, T, E, None, None)
# Attempt moves to new states
while step < self.steps and not self.user_exit:
step += 1
T = self.Tmax * math.exp(Tfactor * step / self.steps)
self.move()
E = self.energy()
dE = E - prevEnergy
trials += 1
if dE > 0.0 and math.exp(-dE / T) < random.random():
# Restore previous state
self.state = self.copy_state(prevState)
E = prevEnergy
else:
# Accept new state and compare to best state
accepts += 1
if dE < 0.0:
improves += 1
prevState = self.copy_state(self.state)
prevEnergy = E
if E < self.best_energy:
self.best_state = self.copy_state(self.state)
self.best_energy = E
if self.updates > 1:
if (step // updateWavelength) > ((step - 1) // updateWavelength):
self.update(
step, T, E, accepts / trials, improves / trials)
trials, accepts, improves = 0, 0, 0
self.state = self.copy_state(self.best_state)
if self.save_state_on_exit:
self.save_state()
# Return best state and energy
return self.best_state, self.best_energy | python | def anneal(self):
"""Minimizes the energy of a system by simulated annealing.
Parameters
state : an initial arrangement of the system
Returns
(state, energy): the best state and energy found.
"""
step = 0
self.start = time.time()
# Precompute factor for exponential cooling from Tmax to Tmin
if self.Tmin <= 0.0:
raise Exception('Exponential cooling requires a minimum "\
"temperature greater than zero.')
Tfactor = -math.log(self.Tmax / self.Tmin)
# Note initial state
T = self.Tmax
E = self.energy()
prevState = self.copy_state(self.state)
prevEnergy = E
self.best_state = self.copy_state(self.state)
self.best_energy = E
trials, accepts, improves = 0, 0, 0
if self.updates > 0:
updateWavelength = self.steps / self.updates
self.update(step, T, E, None, None)
# Attempt moves to new states
while step < self.steps and not self.user_exit:
step += 1
T = self.Tmax * math.exp(Tfactor * step / self.steps)
self.move()
E = self.energy()
dE = E - prevEnergy
trials += 1
if dE > 0.0 and math.exp(-dE / T) < random.random():
# Restore previous state
self.state = self.copy_state(prevState)
E = prevEnergy
else:
# Accept new state and compare to best state
accepts += 1
if dE < 0.0:
improves += 1
prevState = self.copy_state(self.state)
prevEnergy = E
if E < self.best_energy:
self.best_state = self.copy_state(self.state)
self.best_energy = E
if self.updates > 1:
if (step // updateWavelength) > ((step - 1) // updateWavelength):
self.update(
step, T, E, accepts / trials, improves / trials)
trials, accepts, improves = 0, 0, 0
self.state = self.copy_state(self.best_state)
if self.save_state_on_exit:
self.save_state()
# Return best state and energy
return self.best_state, self.best_energy | [
"def",
"anneal",
"(",
"self",
")",
":",
"step",
"=",
"0",
"self",
".",
"start",
"=",
"time",
".",
"time",
"(",
")",
"# Precompute factor for exponential cooling from Tmax to Tmin",
"if",
"self",
".",
"Tmin",
"<=",
"0.0",
":",
"raise",
"Exception",
"(",
"'Exp... | Minimizes the energy of a system by simulated annealing.
Parameters
state : an initial arrangement of the system
Returns
(state, energy): the best state and energy found. | [
"Minimizes",
"the",
"energy",
"of",
"a",
"system",
"by",
"simulated",
"annealing",
"."
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/simanneal/anneal.py#L162-L225 | train | 203,098 |
perrygeo/simanneal | simanneal/anneal.py | Annealer.auto | def auto(self, minutes, steps=2000):
"""Explores the annealing landscape and
estimates optimal temperature settings.
Returns a dictionary suitable for the `set_schedule` method.
"""
def run(T, steps):
"""Anneals a system at constant temperature and returns the state,
energy, rate of acceptance, and rate of improvement."""
E = self.energy()
prevState = self.copy_state(self.state)
prevEnergy = E
accepts, improves = 0, 0
for _ in range(steps):
self.move()
E = self.energy()
dE = E - prevEnergy
if dE > 0.0 and math.exp(-dE / T) < random.random():
self.state = self.copy_state(prevState)
E = prevEnergy
else:
accepts += 1
if dE < 0.0:
improves += 1
prevState = self.copy_state(self.state)
prevEnergy = E
return E, float(accepts) / steps, float(improves) / steps
step = 0
self.start = time.time()
# Attempting automatic simulated anneal...
# Find an initial guess for temperature
T = 0.0
E = self.energy()
self.update(step, T, E, None, None)
while T == 0.0:
step += 1
self.move()
T = abs(self.energy() - E)
# Search for Tmax - a temperature that gives 98% acceptance
E, acceptance, improvement = run(T, steps)
step += steps
while acceptance > 0.98:
T = round_figures(T / 1.5, 2)
E, acceptance, improvement = run(T, steps)
step += steps
self.update(step, T, E, acceptance, improvement)
while acceptance < 0.98:
T = round_figures(T * 1.5, 2)
E, acceptance, improvement = run(T, steps)
step += steps
self.update(step, T, E, acceptance, improvement)
Tmax = T
# Search for Tmin - a temperature that gives 0% improvement
while improvement > 0.0:
T = round_figures(T / 1.5, 2)
E, acceptance, improvement = run(T, steps)
step += steps
self.update(step, T, E, acceptance, improvement)
Tmin = T
# Calculate anneal duration
elapsed = time.time() - self.start
duration = round_figures(int(60.0 * minutes * step / elapsed), 2)
# Don't perform anneal, just return params
return {'tmax': Tmax, 'tmin': Tmin, 'steps': duration, 'updates': self.updates} | python | def auto(self, minutes, steps=2000):
"""Explores the annealing landscape and
estimates optimal temperature settings.
Returns a dictionary suitable for the `set_schedule` method.
"""
def run(T, steps):
"""Anneals a system at constant temperature and returns the state,
energy, rate of acceptance, and rate of improvement."""
E = self.energy()
prevState = self.copy_state(self.state)
prevEnergy = E
accepts, improves = 0, 0
for _ in range(steps):
self.move()
E = self.energy()
dE = E - prevEnergy
if dE > 0.0 and math.exp(-dE / T) < random.random():
self.state = self.copy_state(prevState)
E = prevEnergy
else:
accepts += 1
if dE < 0.0:
improves += 1
prevState = self.copy_state(self.state)
prevEnergy = E
return E, float(accepts) / steps, float(improves) / steps
step = 0
self.start = time.time()
# Attempting automatic simulated anneal...
# Find an initial guess for temperature
T = 0.0
E = self.energy()
self.update(step, T, E, None, None)
while T == 0.0:
step += 1
self.move()
T = abs(self.energy() - E)
# Search for Tmax - a temperature that gives 98% acceptance
E, acceptance, improvement = run(T, steps)
step += steps
while acceptance > 0.98:
T = round_figures(T / 1.5, 2)
E, acceptance, improvement = run(T, steps)
step += steps
self.update(step, T, E, acceptance, improvement)
while acceptance < 0.98:
T = round_figures(T * 1.5, 2)
E, acceptance, improvement = run(T, steps)
step += steps
self.update(step, T, E, acceptance, improvement)
Tmax = T
# Search for Tmin - a temperature that gives 0% improvement
while improvement > 0.0:
T = round_figures(T / 1.5, 2)
E, acceptance, improvement = run(T, steps)
step += steps
self.update(step, T, E, acceptance, improvement)
Tmin = T
# Calculate anneal duration
elapsed = time.time() - self.start
duration = round_figures(int(60.0 * minutes * step / elapsed), 2)
# Don't perform anneal, just return params
return {'tmax': Tmax, 'tmin': Tmin, 'steps': duration, 'updates': self.updates} | [
"def",
"auto",
"(",
"self",
",",
"minutes",
",",
"steps",
"=",
"2000",
")",
":",
"def",
"run",
"(",
"T",
",",
"steps",
")",
":",
"\"\"\"Anneals a system at constant temperature and returns the state,\n energy, rate of acceptance, and rate of improvement.\"\"\"",
... | Explores the annealing landscape and
estimates optimal temperature settings.
Returns a dictionary suitable for the `set_schedule` method. | [
"Explores",
"the",
"annealing",
"landscape",
"and",
"estimates",
"optimal",
"temperature",
"settings",
"."
] | 293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881 | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/simanneal/anneal.py#L227-L298 | train | 203,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.