repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
StorjOld/heartbeat | heartbeat/PySwizzle/PySwizzle.py | PySwizzle.verify | def verify(self, proof, chal, state):
"""This returns True if the proof matches the challenge and file state
:param proof: the proof that was returned from the server
:param chal: the challenge sent to the server
:param state: the state of the file, which can be encrypted
"""
state.decrypt(self.key)
index = KeyedPRF(chal.key, state.chunks)
v = KeyedPRF(chal.key, chal.v_max)
f = KeyedPRF(state.f_key, self.prime)
alpha = KeyedPRF(state.alpha_key, self.prime)
rhs = 0
for i in range(0, chal.chunks):
rhs += v.eval(i) * f.eval(index.eval(i))
for j in range(0, self.sectors):
rhs += alpha.eval(j) * proof.mu[j]
rhs %= self.prime
return proof.sigma == rhs | python | def verify(self, proof, chal, state):
"""This returns True if the proof matches the challenge and file state
:param proof: the proof that was returned from the server
:param chal: the challenge sent to the server
:param state: the state of the file, which can be encrypted
"""
state.decrypt(self.key)
index = KeyedPRF(chal.key, state.chunks)
v = KeyedPRF(chal.key, chal.v_max)
f = KeyedPRF(state.f_key, self.prime)
alpha = KeyedPRF(state.alpha_key, self.prime)
rhs = 0
for i in range(0, chal.chunks):
rhs += v.eval(i) * f.eval(index.eval(i))
for j in range(0, self.sectors):
rhs += alpha.eval(j) * proof.mu[j]
rhs %= self.prime
return proof.sigma == rhs | [
"def",
"verify",
"(",
"self",
",",
"proof",
",",
"chal",
",",
"state",
")",
":",
"state",
".",
"decrypt",
"(",
"self",
".",
"key",
")",
"index",
"=",
"KeyedPRF",
"(",
"chal",
".",
"key",
",",
"state",
".",
"chunks",
")",
"v",
"=",
"KeyedPRF",
"("... | This returns True if the proof matches the challenge and file state
:param proof: the proof that was returned from the server
:param chal: the challenge sent to the server
:param state: the state of the file, which can be encrypted | [
"This",
"returns",
"True",
"if",
"the",
"proof",
"matches",
"the",
"challenge",
"and",
"file",
"state"
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L372-L395 |
Locu/chronology | pykronos/pykronos/client.py | KronosClient.put | def put(self, event_dict, namespace=None):
"""
Sends a dictionary of `event_dict` of the form {stream_name:
[event, ...], ...} to the server.
"""
# Copy the input, in case we need to modify it by adding a timestamp.
event_dict = copy.deepcopy(event_dict)
# Ensure that all events have a timestamp.
timestamp = kronos_time_now()
for events in event_dict.itervalues():
for event in events:
if TIMESTAMP_FIELD not in event:
event[TIMESTAMP_FIELD] = timestamp
else:
if isinstance(event[TIMESTAMP_FIELD], types.StringTypes):
event[TIMESTAMP_FIELD] = parse(event[TIMESTAMP_FIELD])
if isinstance(event[TIMESTAMP_FIELD], datetime):
event[TIMESTAMP_FIELD] = datetime_to_kronos_time(
event[TIMESTAMP_FIELD])
event[LIBRARY_FIELD] = {
'version': pykronos.__version__,
'name': 'pykronos'
}
namespace = namespace or self.namespace
if self._blocking:
return self._put(namespace, event_dict)
else:
with self._put_lock:
self._put_queue.append((namespace, event_dict)) | python | def put(self, event_dict, namespace=None):
"""
Sends a dictionary of `event_dict` of the form {stream_name:
[event, ...], ...} to the server.
"""
# Copy the input, in case we need to modify it by adding a timestamp.
event_dict = copy.deepcopy(event_dict)
# Ensure that all events have a timestamp.
timestamp = kronos_time_now()
for events in event_dict.itervalues():
for event in events:
if TIMESTAMP_FIELD not in event:
event[TIMESTAMP_FIELD] = timestamp
else:
if isinstance(event[TIMESTAMP_FIELD], types.StringTypes):
event[TIMESTAMP_FIELD] = parse(event[TIMESTAMP_FIELD])
if isinstance(event[TIMESTAMP_FIELD], datetime):
event[TIMESTAMP_FIELD] = datetime_to_kronos_time(
event[TIMESTAMP_FIELD])
event[LIBRARY_FIELD] = {
'version': pykronos.__version__,
'name': 'pykronos'
}
namespace = namespace or self.namespace
if self._blocking:
return self._put(namespace, event_dict)
else:
with self._put_lock:
self._put_queue.append((namespace, event_dict)) | [
"def",
"put",
"(",
"self",
",",
"event_dict",
",",
"namespace",
"=",
"None",
")",
":",
"# Copy the input, in case we need to modify it by adding a timestamp.",
"event_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"event_dict",
")",
"# Ensure that all events have a timestamp.",
... | Sends a dictionary of `event_dict` of the form {stream_name:
[event, ...], ...} to the server. | [
"Sends",
"a",
"dictionary",
"of",
"event_dict",
"of",
"the",
"form",
"{",
"stream_name",
":",
"[",
"event",
"...",
"]",
"...",
"}",
"to",
"the",
"server",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/client.py#L162-L193 |
Locu/chronology | pykronos/pykronos/client.py | KronosClient.get | def get(self, stream, start_time, end_time, start_id=None, limit=None,
order=ResultOrder.ASCENDING, namespace=None, timeout=None):
"""
Queries a stream with name `stream` for all events between `start_time` and
`end_time` (both inclusive). An optional `start_id` allows the client to
restart from a failure, specifying the last ID they read; all events that
happened after that ID will be returned. An optional `limit` limits the
maximum number of events returned. An optional `order` requests results in
`ASCENDING` or `DESCENDING` order.
"""
if isinstance(start_time, types.StringTypes):
start_time = parse(start_time)
if isinstance(end_time, types.StringTypes):
end_time = parse(end_time)
if isinstance(start_time, datetime):
start_time = datetime_to_kronos_time(start_time)
if isinstance(end_time, datetime):
end_time = datetime_to_kronos_time(end_time)
request_dict = {
'stream': stream,
'end_time': end_time,
'order': order,
}
if start_id is not None:
request_dict['start_id'] = start_id
else:
request_dict['start_time'] = start_time
if limit is not None:
request_dict['limit'] = limit
namespace = namespace or self.namespace
if namespace is not None:
request_dict['namespace'] = namespace
errors = []
last_id = None
while True:
try:
response = self._make_request(self._get_url,
data=request_dict,
stream=True,
timeout=timeout)
for line in response.iter_lines(chunk_size=self._chunk_size):
if line:
# Python's json adds a lot of overhead when decoding a large
# number of events; ujson fares better. However ujson won't work
# on PyPy since it's a C extension.
event = ujson.loads(line, precise_float=True)
last_id = event[ID_FIELD]
yield event
break
except Exception, e:
if isinstance(e, requests.exceptions.Timeout):
raise KronosClientError('Request timed out.')
errors.append(e)
if len(errors) == 10:
raise KronosClientError(errors)
if last_id is not None:
request_dict.pop('start_time', None)
request_dict['start_id'] = last_id
time.sleep(len(errors) * 0.1) | python | def get(self, stream, start_time, end_time, start_id=None, limit=None,
order=ResultOrder.ASCENDING, namespace=None, timeout=None):
"""
Queries a stream with name `stream` for all events between `start_time` and
`end_time` (both inclusive). An optional `start_id` allows the client to
restart from a failure, specifying the last ID they read; all events that
happened after that ID will be returned. An optional `limit` limits the
maximum number of events returned. An optional `order` requests results in
`ASCENDING` or `DESCENDING` order.
"""
if isinstance(start_time, types.StringTypes):
start_time = parse(start_time)
if isinstance(end_time, types.StringTypes):
end_time = parse(end_time)
if isinstance(start_time, datetime):
start_time = datetime_to_kronos_time(start_time)
if isinstance(end_time, datetime):
end_time = datetime_to_kronos_time(end_time)
request_dict = {
'stream': stream,
'end_time': end_time,
'order': order,
}
if start_id is not None:
request_dict['start_id'] = start_id
else:
request_dict['start_time'] = start_time
if limit is not None:
request_dict['limit'] = limit
namespace = namespace or self.namespace
if namespace is not None:
request_dict['namespace'] = namespace
errors = []
last_id = None
while True:
try:
response = self._make_request(self._get_url,
data=request_dict,
stream=True,
timeout=timeout)
for line in response.iter_lines(chunk_size=self._chunk_size):
if line:
# Python's json adds a lot of overhead when decoding a large
# number of events; ujson fares better. However ujson won't work
# on PyPy since it's a C extension.
event = ujson.loads(line, precise_float=True)
last_id = event[ID_FIELD]
yield event
break
except Exception, e:
if isinstance(e, requests.exceptions.Timeout):
raise KronosClientError('Request timed out.')
errors.append(e)
if len(errors) == 10:
raise KronosClientError(errors)
if last_id is not None:
request_dict.pop('start_time', None)
request_dict['start_id'] = last_id
time.sleep(len(errors) * 0.1) | [
"def",
"get",
"(",
"self",
",",
"stream",
",",
"start_time",
",",
"end_time",
",",
"start_id",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"order",
"=",
"ResultOrder",
".",
"ASCENDING",
",",
"namespace",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
... | Queries a stream with name `stream` for all events between `start_time` and
`end_time` (both inclusive). An optional `start_id` allows the client to
restart from a failure, specifying the last ID they read; all events that
happened after that ID will be returned. An optional `limit` limits the
maximum number of events returned. An optional `order` requests results in
`ASCENDING` or `DESCENDING` order. | [
"Queries",
"a",
"stream",
"with",
"name",
"stream",
"for",
"all",
"events",
"between",
"start_time",
"and",
"end_time",
"(",
"both",
"inclusive",
")",
".",
"An",
"optional",
"start_id",
"allows",
"the",
"client",
"to",
"restart",
"from",
"a",
"failure",
"spe... | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/client.py#L202-L264 |
Locu/chronology | pykronos/pykronos/client.py | KronosClient.delete | def delete(self, stream, start_time, end_time, start_id=None, namespace=None):
"""
Delete events in the stream with name `stream` that occurred between
`start_time` and `end_time` (both inclusive). An optional `start_id` allows
the client to delete events starting from after an ID rather than starting
at a timestamp.
"""
if isinstance(start_time, types.StringTypes):
start_time = parse(start_time)
if isinstance(end_time, types.StringTypes):
end_time = parse(end_time)
if isinstance(start_time, datetime):
start_time = datetime_to_kronos_time(start_time)
if isinstance(end_time, datetime):
end_time = datetime_to_kronos_time(end_time)
request_dict = {
'stream': stream,
'end_time': end_time
}
if start_id:
request_dict['start_id'] = start_id
else:
request_dict['start_time'] = start_time
namespace = namespace or self.namespace
if namespace is not None:
request_dict['namespace'] = namespace
return self._make_request(self._delete_url, data=request_dict) | python | def delete(self, stream, start_time, end_time, start_id=None, namespace=None):
"""
Delete events in the stream with name `stream` that occurred between
`start_time` and `end_time` (both inclusive). An optional `start_id` allows
the client to delete events starting from after an ID rather than starting
at a timestamp.
"""
if isinstance(start_time, types.StringTypes):
start_time = parse(start_time)
if isinstance(end_time, types.StringTypes):
end_time = parse(end_time)
if isinstance(start_time, datetime):
start_time = datetime_to_kronos_time(start_time)
if isinstance(end_time, datetime):
end_time = datetime_to_kronos_time(end_time)
request_dict = {
'stream': stream,
'end_time': end_time
}
if start_id:
request_dict['start_id'] = start_id
else:
request_dict['start_time'] = start_time
namespace = namespace or self.namespace
if namespace is not None:
request_dict['namespace'] = namespace
return self._make_request(self._delete_url, data=request_dict) | [
"def",
"delete",
"(",
"self",
",",
"stream",
",",
"start_time",
",",
"end_time",
",",
"start_id",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"start_time",
",",
"types",
".",
"StringTypes",
")",
":",
"start_time",
"=",
... | Delete events in the stream with name `stream` that occurred between
`start_time` and `end_time` (both inclusive). An optional `start_id` allows
the client to delete events starting from after an ID rather than starting
at a timestamp. | [
"Delete",
"events",
"in",
"the",
"stream",
"with",
"name",
"stream",
"that",
"occurred",
"between",
"start_time",
"and",
"end_time",
"(",
"both",
"inclusive",
")",
".",
"An",
"optional",
"start_id",
"allows",
"the",
"client",
"to",
"delete",
"events",
"startin... | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/client.py#L266-L294 |
Locu/chronology | pykronos/pykronos/client.py | KronosClient.get_streams | def get_streams(self, namespace=None):
"""
Queries the Kronos server and fetches a list of streams available to be
read.
"""
request_dict = {}
namespace = namespace or self.namespace
if namespace is not None:
request_dict['namespace'] = namespace
response = self._make_request(self._streams_url,
data=request_dict,
stream=True)
for line in response.iter_lines():
if line:
yield line | python | def get_streams(self, namespace=None):
"""
Queries the Kronos server and fetches a list of streams available to be
read.
"""
request_dict = {}
namespace = namespace or self.namespace
if namespace is not None:
request_dict['namespace'] = namespace
response = self._make_request(self._streams_url,
data=request_dict,
stream=True)
for line in response.iter_lines():
if line:
yield line | [
"def",
"get_streams",
"(",
"self",
",",
"namespace",
"=",
"None",
")",
":",
"request_dict",
"=",
"{",
"}",
"namespace",
"=",
"namespace",
"or",
"self",
".",
"namespace",
"if",
"namespace",
"is",
"not",
"None",
":",
"request_dict",
"[",
"'namespace'",
"]",
... | Queries the Kronos server and fetches a list of streams available to be
read. | [
"Queries",
"the",
"Kronos",
"server",
"and",
"fetches",
"a",
"list",
"of",
"streams",
"available",
"to",
"be",
"read",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/client.py#L296-L310 |
Locu/chronology | pykronos/pykronos/client.py | KronosClient.infer_schema | def infer_schema(self, stream, namespace=None):
"""
Queries the Kronos server and fetches the inferred schema for the
requested stream.
"""
return self._make_request(self._infer_schema_url,
data={'stream': stream,
'namespace': namespace or self.namespace}) | python | def infer_schema(self, stream, namespace=None):
"""
Queries the Kronos server and fetches the inferred schema for the
requested stream.
"""
return self._make_request(self._infer_schema_url,
data={'stream': stream,
'namespace': namespace or self.namespace}) | [
"def",
"infer_schema",
"(",
"self",
",",
"stream",
",",
"namespace",
"=",
"None",
")",
":",
"return",
"self",
".",
"_make_request",
"(",
"self",
".",
"_infer_schema_url",
",",
"data",
"=",
"{",
"'stream'",
":",
"stream",
",",
"'namespace'",
":",
"namespace... | Queries the Kronos server and fetches the inferred schema for the
requested stream. | [
"Queries",
"the",
"Kronos",
"server",
"and",
"fetches",
"the",
"inferred",
"schema",
"for",
"the",
"requested",
"stream",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/client.py#L312-L319 |
Locu/chronology | pykronos/pykronos/client.py | KronosClient.log_function | def log_function(self, stream_name, properties={},
log_function_stack_trace=False,
log_exception_stack_trace=False,
namespace=None):
"""
Logs each call to the function as an event in the stream with name
`stream_name`. If `log_stack_trace` is set, it will log the stack trace
under the `stack_trace` key. `properties` is an optional mapping fron key
name to some function which expects the same arguments as the function
`function` being decorated. The event will be populated with keys in
`properties` mapped to the return values of the
`properties[key_name](*args, **kwargs)`.
Usage:
@kronos_client.log_function('mystreamname',
properties={'a': lambda x, y: x,
'b': lambda x, y: y})
def myfunction(a, b):
<some code here>
"""
namespace = namespace or self.namespace
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
event = {}
start_time = time.time()
if log_function_stack_trace:
event['stack_trace'] = traceback.extract_stack()
try:
return function(*args, **kwargs)
except Exception as exception:
self._log_exception(event, exception,
(sys.last_traceback if log_exception_stack_trace
else None))
raise exception
finally:
event['duration'] = time.time() - start_time
for key, value_getter in properties.iteritems():
event[key] = value_getter(*args, **kwargs)
self.put({stream_name: [event]}, namespace=namespace)
return wrapper
return decorator | python | def log_function(self, stream_name, properties={},
log_function_stack_trace=False,
log_exception_stack_trace=False,
namespace=None):
"""
Logs each call to the function as an event in the stream with name
`stream_name`. If `log_stack_trace` is set, it will log the stack trace
under the `stack_trace` key. `properties` is an optional mapping fron key
name to some function which expects the same arguments as the function
`function` being decorated. The event will be populated with keys in
`properties` mapped to the return values of the
`properties[key_name](*args, **kwargs)`.
Usage:
@kronos_client.log_function('mystreamname',
properties={'a': lambda x, y: x,
'b': lambda x, y: y})
def myfunction(a, b):
<some code here>
"""
namespace = namespace or self.namespace
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
event = {}
start_time = time.time()
if log_function_stack_trace:
event['stack_trace'] = traceback.extract_stack()
try:
return function(*args, **kwargs)
except Exception as exception:
self._log_exception(event, exception,
(sys.last_traceback if log_exception_stack_trace
else None))
raise exception
finally:
event['duration'] = time.time() - start_time
for key, value_getter in properties.iteritems():
event[key] = value_getter(*args, **kwargs)
self.put({stream_name: [event]}, namespace=namespace)
return wrapper
return decorator | [
"def",
"log_function",
"(",
"self",
",",
"stream_name",
",",
"properties",
"=",
"{",
"}",
",",
"log_function_stack_trace",
"=",
"False",
",",
"log_exception_stack_trace",
"=",
"False",
",",
"namespace",
"=",
"None",
")",
":",
"namespace",
"=",
"namespace",
"or... | Logs each call to the function as an event in the stream with name
`stream_name`. If `log_stack_trace` is set, it will log the stack trace
under the `stack_trace` key. `properties` is an optional mapping fron key
name to some function which expects the same arguments as the function
`function` being decorated. The event will be populated with keys in
`properties` mapped to the return values of the
`properties[key_name](*args, **kwargs)`.
Usage:
@kronos_client.log_function('mystreamname',
properties={'a': lambda x, y: x,
'b': lambda x, y: y})
def myfunction(a, b):
<some code here> | [
"Logs",
"each",
"call",
"to",
"the",
"function",
"as",
"an",
"event",
"in",
"the",
"stream",
"with",
"name",
"stream_name",
".",
"If",
"log_stack_trace",
"is",
"set",
"it",
"will",
"log",
"the",
"stack",
"trace",
"under",
"the",
"stack_trace",
"key",
".",
... | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/client.py#L321-L363 |
Locu/chronology | pykronos/pykronos/client.py | KronosClient.log_scope | def log_scope(self, stream_name, properties={}, log_scope_stack_trace=False,
log_exception_stack_trace=False, namespace=None):
"""
Identical to `log_function` except that `log_scope` is used to log blocks
of code. The API is identical except that keys in `properties` are mapped to
real values rather than getter functions. Usage:
with kronos_client.log_scope('mystreamname', properties={ 'lol':'cat' },
log_scope_stack_trace=True):
<some code here>
"""
start_time = time.time()
namespace = namespace or self.namespace
event = properties.copy()
if log_scope_stack_trace:
event['stack_trace'] = traceback.extract_stack()
try:
yield event
except Exception, exception:
self._log_exception(event, exception,
(sys.last_traceback if log_exception_stack_trace
else None))
event['duration'] = time.time() - start_time
self.put({stream_name: [event]}, namespace=namespace) | python | def log_scope(self, stream_name, properties={}, log_scope_stack_trace=False,
log_exception_stack_trace=False, namespace=None):
"""
Identical to `log_function` except that `log_scope` is used to log blocks
of code. The API is identical except that keys in `properties` are mapped to
real values rather than getter functions. Usage:
with kronos_client.log_scope('mystreamname', properties={ 'lol':'cat' },
log_scope_stack_trace=True):
<some code here>
"""
start_time = time.time()
namespace = namespace or self.namespace
event = properties.copy()
if log_scope_stack_trace:
event['stack_trace'] = traceback.extract_stack()
try:
yield event
except Exception, exception:
self._log_exception(event, exception,
(sys.last_traceback if log_exception_stack_trace
else None))
event['duration'] = time.time() - start_time
self.put({stream_name: [event]}, namespace=namespace) | [
"def",
"log_scope",
"(",
"self",
",",
"stream_name",
",",
"properties",
"=",
"{",
"}",
",",
"log_scope_stack_trace",
"=",
"False",
",",
"log_exception_stack_trace",
"=",
"False",
",",
"namespace",
"=",
"None",
")",
":",
"start_time",
"=",
"time",
".",
"time"... | Identical to `log_function` except that `log_scope` is used to log blocks
of code. The API is identical except that keys in `properties` are mapped to
real values rather than getter functions. Usage:
with kronos_client.log_scope('mystreamname', properties={ 'lol':'cat' },
log_scope_stack_trace=True):
<some code here> | [
"Identical",
"to",
"log_function",
"except",
"that",
"log_scope",
"is",
"used",
"to",
"log",
"blocks",
"of",
"code",
".",
"The",
"API",
"is",
"identical",
"except",
"that",
"keys",
"in",
"properties",
"are",
"mapped",
"to",
"real",
"values",
"rather",
"than"... | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/client.py#L366-L389 |
mwhooker/jones | jones/client.py | JonesClient._nodemap_changed | def _nodemap_changed(self, data, stat):
"""Called when the nodemap changes."""
if not stat:
raise EnvironmentNotFoundException(self.nodemap_path)
try:
conf_path = self._deserialize_nodemap(data)[self.hostname]
except KeyError:
conf_path = '/services/%s/conf' % self.service
self.config_watcher = DataWatch(
self.zk, conf_path,
self._config_changed
) | python | def _nodemap_changed(self, data, stat):
"""Called when the nodemap changes."""
if not stat:
raise EnvironmentNotFoundException(self.nodemap_path)
try:
conf_path = self._deserialize_nodemap(data)[self.hostname]
except KeyError:
conf_path = '/services/%s/conf' % self.service
self.config_watcher = DataWatch(
self.zk, conf_path,
self._config_changed
) | [
"def",
"_nodemap_changed",
"(",
"self",
",",
"data",
",",
"stat",
")",
":",
"if",
"not",
"stat",
":",
"raise",
"EnvironmentNotFoundException",
"(",
"self",
".",
"nodemap_path",
")",
"try",
":",
"conf_path",
"=",
"self",
".",
"_deserialize_nodemap",
"(",
"dat... | Called when the nodemap changes. | [
"Called",
"when",
"the",
"nodemap",
"changes",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/client.py#L56-L70 |
mwhooker/jones | jones/client.py | JonesClient._config_changed | def _config_changed(self, data, stat):
"""Called when config changes."""
self.config = json.loads(data)
if self.cb:
self.cb(self.config) | python | def _config_changed(self, data, stat):
"""Called when config changes."""
self.config = json.loads(data)
if self.cb:
self.cb(self.config) | [
"def",
"_config_changed",
"(",
"self",
",",
"data",
",",
"stat",
")",
":",
"self",
".",
"config",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"if",
"self",
".",
"cb",
":",
"self",
".",
"cb",
"(",
"self",
".",
"config",
")"
] | Called when config changes. | [
"Called",
"when",
"config",
"changes",
"."
] | train | https://github.com/mwhooker/jones/blob/121e89572ca063f456b8e94cbb8cbee26c307a8f/jones/client.py#L72-L78 |
Locu/chronology | kronos/kronos/storage/base.py | BaseStorage.retrieve | def retrieve(self, namespace, stream, start_time, end_time, start_id,
configuration, order=ResultOrder.ASCENDING, limit=sys.maxint):
"""
Retrieves all the events for `stream` from `start_time` (inclusive) till
`end_time` (inclusive). Alternatively to `start_time`, `start_id` can be
provided, and then all events from `start_id` (exclusive) till `end_time`
(inclusive) are returned. `start_id` should be used in cases when the client
got disconnected from the server before all the events in the requested
time window had been returned. `order` can be one of ResultOrder.ASCENDING
or ResultOrder.DESCENDING.
Returns an iterator over all JSON serialized (strings) events.
"""
if not start_id:
start_id = uuid_from_kronos_time(start_time, _type=UUIDType.LOWEST)
else:
start_id = TimeUUID(start_id)
if uuid_to_kronos_time(start_id) > end_time:
return []
return self._retrieve(namespace, stream, start_id, end_time, order, limit,
configuration) | python | def retrieve(self, namespace, stream, start_time, end_time, start_id,
configuration, order=ResultOrder.ASCENDING, limit=sys.maxint):
"""
Retrieves all the events for `stream` from `start_time` (inclusive) till
`end_time` (inclusive). Alternatively to `start_time`, `start_id` can be
provided, and then all events from `start_id` (exclusive) till `end_time`
(inclusive) are returned. `start_id` should be used in cases when the client
got disconnected from the server before all the events in the requested
time window had been returned. `order` can be one of ResultOrder.ASCENDING
or ResultOrder.DESCENDING.
Returns an iterator over all JSON serialized (strings) events.
"""
if not start_id:
start_id = uuid_from_kronos_time(start_time, _type=UUIDType.LOWEST)
else:
start_id = TimeUUID(start_id)
if uuid_to_kronos_time(start_id) > end_time:
return []
return self._retrieve(namespace, stream, start_id, end_time, order, limit,
configuration) | [
"def",
"retrieve",
"(",
"self",
",",
"namespace",
",",
"stream",
",",
"start_time",
",",
"end_time",
",",
"start_id",
",",
"configuration",
",",
"order",
"=",
"ResultOrder",
".",
"ASCENDING",
",",
"limit",
"=",
"sys",
".",
"maxint",
")",
":",
"if",
"not"... | Retrieves all the events for `stream` from `start_time` (inclusive) till
`end_time` (inclusive). Alternatively to `start_time`, `start_id` can be
provided, and then all events from `start_id` (exclusive) till `end_time`
(inclusive) are returned. `start_id` should be used in cases when the client
got disconnected from the server before all the events in the requested
time window had been returned. `order` can be one of ResultOrder.ASCENDING
or ResultOrder.DESCENDING.
Returns an iterator over all JSON serialized (strings) events. | [
"Retrieves",
"all",
"the",
"events",
"for",
"stream",
"from",
"start_time",
"(",
"inclusive",
")",
"till",
"end_time",
"(",
"inclusive",
")",
".",
"Alternatively",
"to",
"start_time",
"start_id",
"can",
"be",
"provided",
"and",
"then",
"all",
"events",
"from",... | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/base.py#L57-L77 |
volker48/flask-mandrill | flask_mandrill.py | Mandrill.send_email | def send_email(self, **kwargs):
"""
Sends an email using Mandrill's API. Returns a
Requests :class:`Response` object.
At a minimum kwargs must contain the keys to, from_email, and text.
Everything passed as kwargs except for the keywords 'key', 'async',
and 'ip_pool' will be sent as key-value pairs in the message object.
Reference https://mandrillapp.com/api/docs/messages.JSON.html#method=send
for all the available options.
"""
endpoint = self.messages_endpoint
data = {
'async': kwargs.pop('async', False),
'ip_pool': kwargs.pop('ip_pool', ''),
'key': kwargs.pop('key', self.api_key),
}
if not data.get('key', None):
raise ValueError('No Mandrill API key has been configured')
# Sending a template through Mandrill requires a couple extra args
# and a different endpoint.
if kwargs.get('template_name', None):
data['template_name'] = kwargs.pop('template_name')
data['template_content'] = kwargs.pop('template_content', [])
endpoint = self.templates_endpoint
data['message'] = kwargs
if self.app:
data['message'].setdefault(
'from_email',
self.app.config.get('MANDRILL_DEFAULT_FROM', None)
)
if endpoint != self.templates_endpoint and not data['message'].get('from_email', None):
raise ValueError(
'No from email was specified and no default was configured')
response = requests.post(endpoint,
data=json.dumps(data),
headers={'Content-Type': 'application/json'})
response.raise_for_status()
return response | python | def send_email(self, **kwargs):
"""
Sends an email using Mandrill's API. Returns a
Requests :class:`Response` object.
At a minimum kwargs must contain the keys to, from_email, and text.
Everything passed as kwargs except for the keywords 'key', 'async',
and 'ip_pool' will be sent as key-value pairs in the message object.
Reference https://mandrillapp.com/api/docs/messages.JSON.html#method=send
for all the available options.
"""
endpoint = self.messages_endpoint
data = {
'async': kwargs.pop('async', False),
'ip_pool': kwargs.pop('ip_pool', ''),
'key': kwargs.pop('key', self.api_key),
}
if not data.get('key', None):
raise ValueError('No Mandrill API key has been configured')
# Sending a template through Mandrill requires a couple extra args
# and a different endpoint.
if kwargs.get('template_name', None):
data['template_name'] = kwargs.pop('template_name')
data['template_content'] = kwargs.pop('template_content', [])
endpoint = self.templates_endpoint
data['message'] = kwargs
if self.app:
data['message'].setdefault(
'from_email',
self.app.config.get('MANDRILL_DEFAULT_FROM', None)
)
if endpoint != self.templates_endpoint and not data['message'].get('from_email', None):
raise ValueError(
'No from email was specified and no default was configured')
response = requests.post(endpoint,
data=json.dumps(data),
headers={'Content-Type': 'application/json'})
response.raise_for_status()
return response | [
"def",
"send_email",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint",
"=",
"self",
".",
"messages_endpoint",
"data",
"=",
"{",
"'async'",
":",
"kwargs",
".",
"pop",
"(",
"'async'",
",",
"False",
")",
",",
"'ip_pool'",
":",
"kwargs",
".",
"... | Sends an email using Mandrill's API. Returns a
Requests :class:`Response` object.
At a minimum kwargs must contain the keys to, from_email, and text.
Everything passed as kwargs except for the keywords 'key', 'async',
and 'ip_pool' will be sent as key-value pairs in the message object.
Reference https://mandrillapp.com/api/docs/messages.JSON.html#method=send
for all the available options. | [
"Sends",
"an",
"email",
"using",
"Mandrill",
"s",
"API",
".",
"Returns",
"a",
"Requests",
":",
"class",
":",
"Response",
"object",
".",
"At",
"a",
"minimum",
"kwargs",
"must",
"contain",
"the",
"keys",
"to",
"from_email",
"and",
"text",
".",
"Everything",
... | train | https://github.com/volker48/flask-mandrill/blob/85ec7756bf29a6b3c58da36b12f5ec9325975def/flask_mandrill.py#L17-L62 |
jrabbit/hitman | hitman.py | put_a_hit_out | def put_a_hit_out(name):
"""Download a feed's most recent enclosure that we don't have"""
feed = resolve_name(name)
if six.PY3:
feed = feed.decode()
d = feedparser.parse(feed)
# logger.info(d)
# logger.info(feed)
print(d['feed']['title'])
if d.entries[0].enclosures:
with Database("settings") as s:
if 'verbose' in s:
print(d.entries[0].enclosures[0])
# print d.feed.updated_parsed
# Doesn't work everywhere, may nest in try or
# use .headers['last-modified']
url = str(d.entries[0].enclosures[0]['href'])
with Database("downloads") as db:
if url.split('/')[-1] not in db:
with Database("settings") as settings:
if 'dl' in settings:
dl_dir = settings['dl']
else:
dl_dir = os.path.join(os.path.expanduser("~"), "Downloads")
requests_get(url, dl_dir)
db[url.split('/')[-1]] = json.dumps({'url': url, 'date': time.ctime(), 'feed': feed})
growl("Mission Complete: %s downloaded" % d.feed.title)
print("Mission Complete: %s downloaded" % d.feed.title)
else:
growl("Mission Aborted: %s already downloaded" % d.feed.title)
print("Mission Aborted: %s already downloaded" % d.feed.title) | python | def put_a_hit_out(name):
"""Download a feed's most recent enclosure that we don't have"""
feed = resolve_name(name)
if six.PY3:
feed = feed.decode()
d = feedparser.parse(feed)
# logger.info(d)
# logger.info(feed)
print(d['feed']['title'])
if d.entries[0].enclosures:
with Database("settings") as s:
if 'verbose' in s:
print(d.entries[0].enclosures[0])
# print d.feed.updated_parsed
# Doesn't work everywhere, may nest in try or
# use .headers['last-modified']
url = str(d.entries[0].enclosures[0]['href'])
with Database("downloads") as db:
if url.split('/')[-1] not in db:
with Database("settings") as settings:
if 'dl' in settings:
dl_dir = settings['dl']
else:
dl_dir = os.path.join(os.path.expanduser("~"), "Downloads")
requests_get(url, dl_dir)
db[url.split('/')[-1]] = json.dumps({'url': url, 'date': time.ctime(), 'feed': feed})
growl("Mission Complete: %s downloaded" % d.feed.title)
print("Mission Complete: %s downloaded" % d.feed.title)
else:
growl("Mission Aborted: %s already downloaded" % d.feed.title)
print("Mission Aborted: %s already downloaded" % d.feed.title) | [
"def",
"put_a_hit_out",
"(",
"name",
")",
":",
"feed",
"=",
"resolve_name",
"(",
"name",
")",
"if",
"six",
".",
"PY3",
":",
"feed",
"=",
"feed",
".",
"decode",
"(",
")",
"d",
"=",
"feedparser",
".",
"parse",
"(",
"feed",
")",
"# logger.info(d)",
"# l... | Download a feed's most recent enclosure that we don't have | [
"Download",
"a",
"feed",
"s",
"most",
"recent",
"enclosure",
"that",
"we",
"don",
"t",
"have"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L46-L78 |
jrabbit/hitman | hitman.py | selective_download | def selective_download(name, oldest, newest):
"""Note: RSS feeds are counted backwards, default newest is 0, the most recent."""
if six.PY3:
name = name.encode("utf-8")
feed = resolve_name(name)
if six.PY3:
feed = feed.decode()
d = feedparser.parse(feed)
logger.debug(d)
try:
d.entries[int(oldest)]
except IndexError:
print("Error feed does not contain this many items.")
print("Hitman thinks there are %d items in this feed." % len(d.entries))
return
for url in [q.enclosures[0]['href'] for q in d.entries[int(newest):int(oldest)]]:
# iterate over urls in feed from newest to oldest feed items.
url = str(url)
with Database("downloads") as db:
if url.split('/')[-1] not in db:
# download(url, name, feed)
with Database("settings") as settings:
if 'dl' in settings:
dl_dir = settings['dl']
else:
dl_dir = os.path.join(os.path.expanduser("~"), "Downloads")
requests_get(url, dl_dir) | python | def selective_download(name, oldest, newest):
"""Note: RSS feeds are counted backwards, default newest is 0, the most recent."""
if six.PY3:
name = name.encode("utf-8")
feed = resolve_name(name)
if six.PY3:
feed = feed.decode()
d = feedparser.parse(feed)
logger.debug(d)
try:
d.entries[int(oldest)]
except IndexError:
print("Error feed does not contain this many items.")
print("Hitman thinks there are %d items in this feed." % len(d.entries))
return
for url in [q.enclosures[0]['href'] for q in d.entries[int(newest):int(oldest)]]:
# iterate over urls in feed from newest to oldest feed items.
url = str(url)
with Database("downloads") as db:
if url.split('/')[-1] not in db:
# download(url, name, feed)
with Database("settings") as settings:
if 'dl' in settings:
dl_dir = settings['dl']
else:
dl_dir = os.path.join(os.path.expanduser("~"), "Downloads")
requests_get(url, dl_dir) | [
"def",
"selective_download",
"(",
"name",
",",
"oldest",
",",
"newest",
")",
":",
"if",
"six",
".",
"PY3",
":",
"name",
"=",
"name",
".",
"encode",
"(",
"\"utf-8\"",
")",
"feed",
"=",
"resolve_name",
"(",
"name",
")",
"if",
"six",
".",
"PY3",
":",
... | Note: RSS feeds are counted backwards, default newest is 0, the most recent. | [
"Note",
":",
"RSS",
"feeds",
"are",
"counted",
"backwards",
"default",
"newest",
"is",
"0",
"the",
"most",
"recent",
"."
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L85-L111 |
jrabbit/hitman | hitman.py | resolve_name | def resolve_name(name):
"""Takes a given input from a user and finds the url for it"""
logger.debug("resolve_name: %s", name)
with Database("feeds") as feeds, Database("aliases") as aliases:
if name in aliases.keys():
return feeds[aliases[name]]
elif name in feeds.keys():
return feeds[name]
else:
print("Cannot find feed named: %s" % name)
return | python | def resolve_name(name):
"""Takes a given input from a user and finds the url for it"""
logger.debug("resolve_name: %s", name)
with Database("feeds") as feeds, Database("aliases") as aliases:
if name in aliases.keys():
return feeds[aliases[name]]
elif name in feeds.keys():
return feeds[name]
else:
print("Cannot find feed named: %s" % name)
return | [
"def",
"resolve_name",
"(",
"name",
")",
":",
"logger",
".",
"debug",
"(",
"\"resolve_name: %s\"",
",",
"name",
")",
"with",
"Database",
"(",
"\"feeds\"",
")",
"as",
"feeds",
",",
"Database",
"(",
"\"aliases\"",
")",
"as",
"aliases",
":",
"if",
"name",
"... | Takes a given input from a user and finds the url for it | [
"Takes",
"a",
"given",
"input",
"from",
"a",
"user",
"and",
"finds",
"the",
"url",
"for",
"it"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L114-L124 |
jrabbit/hitman | hitman.py | hitsquad | def hitsquad(ctx):
"""'put a hit out' on all known rss feeds [Default action without arguements]"""
with Database("feeds") as feeds:
for name, feed in zip(list(feeds.keys()), list(feeds.values())):
logger.debug("calling put_a_hit_out: %s", name)
ctx.invoke(put_a_hit_out, name=name)
if len(list(feeds.keys())) == 0:
ctx.get_help() | python | def hitsquad(ctx):
"""'put a hit out' on all known rss feeds [Default action without arguements]"""
with Database("feeds") as feeds:
for name, feed in zip(list(feeds.keys()), list(feeds.values())):
logger.debug("calling put_a_hit_out: %s", name)
ctx.invoke(put_a_hit_out, name=name)
if len(list(feeds.keys())) == 0:
ctx.get_help() | [
"def",
"hitsquad",
"(",
"ctx",
")",
":",
"with",
"Database",
"(",
"\"feeds\"",
")",
"as",
"feeds",
":",
"for",
"name",
",",
"feed",
"in",
"zip",
"(",
"list",
"(",
"feeds",
".",
"keys",
"(",
")",
")",
",",
"list",
"(",
"feeds",
".",
"values",
"(",... | put a hit out' on all known rss feeds [Default action without arguements] | [
"put",
"a",
"hit",
"out",
"on",
"all",
"known",
"rss",
"feeds",
"[",
"Default",
"action",
"without",
"arguements",
"]"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L127-L134 |
jrabbit/hitman | hitman.py | growl | def growl(text):
"""send native notifications where supported. Growl is gone."""
if platform.system() == 'Darwin':
import pync
pync.Notifier.notify(text, title="Hitman")
elif platform.system() == 'Linux':
notified = False
try:
logger.debug("Trying to import pynotify")
import pynotify
pynotify.init("Hitman")
n = pynotify.Notification("Hitman Status Report", text)
n.set_timeout(pynotify.EXPIRES_DEFAULT)
n.show()
notified = True
except ImportError:
logger.debug("Trying notify-send")
# print("trying to notify-send")
if Popen(['which', 'notify-send'], stdout=PIPE).communicate()[0]:
# Do an OSD-Notify
# notify-send "Totem" "This is a superfluous notification"
os.system("notify-send \"Hitman\" \"%r\" " % str(text))
notified = True
if not notified:
try:
logger.info("notificatons gnome gi???")
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
Notify.init("Hitman")
# TODO have Icon as third argument.
notification = Notify.Notification.new("Hitman", text)
notification.show()
Notify.uninit()
notified = True
except ImportError:
logger.exception()
elif platform.system() == 'Haiku':
os.system("notify --type information --app Hitman --title 'Status Report' '%s'" % str(text))
elif platform.system() == 'Windows':
try:
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast(text, "Hitman")
# gntplib.publish("Hitman", "Status Update", "Hitman", text=text)
except Exception:
logger.exception() | python | def growl(text):
"""send native notifications where supported. Growl is gone."""
if platform.system() == 'Darwin':
import pync
pync.Notifier.notify(text, title="Hitman")
elif platform.system() == 'Linux':
notified = False
try:
logger.debug("Trying to import pynotify")
import pynotify
pynotify.init("Hitman")
n = pynotify.Notification("Hitman Status Report", text)
n.set_timeout(pynotify.EXPIRES_DEFAULT)
n.show()
notified = True
except ImportError:
logger.debug("Trying notify-send")
# print("trying to notify-send")
if Popen(['which', 'notify-send'], stdout=PIPE).communicate()[0]:
# Do an OSD-Notify
# notify-send "Totem" "This is a superfluous notification"
os.system("notify-send \"Hitman\" \"%r\" " % str(text))
notified = True
if not notified:
try:
logger.info("notificatons gnome gi???")
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
Notify.init("Hitman")
# TODO have Icon as third argument.
notification = Notify.Notification.new("Hitman", text)
notification.show()
Notify.uninit()
notified = True
except ImportError:
logger.exception()
elif platform.system() == 'Haiku':
os.system("notify --type information --app Hitman --title 'Status Report' '%s'" % str(text))
elif platform.system() == 'Windows':
try:
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast(text, "Hitman")
# gntplib.publish("Hitman", "Status Update", "Hitman", text=text)
except Exception:
logger.exception() | [
"def",
"growl",
"(",
"text",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
":",
"import",
"pync",
"pync",
".",
"Notifier",
".",
"notify",
"(",
"text",
",",
"title",
"=",
"\"Hitman\"",
")",
"elif",
"platform",
".",
"system",
"... | send native notifications where supported. Growl is gone. | [
"send",
"native",
"notifications",
"where",
"supported",
".",
"Growl",
"is",
"gone",
"."
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L137-L184 |
jrabbit/hitman | hitman.py | add_feed | def add_feed(url):
"""add to db"""
with Database("feeds") as db:
title = feedparser.parse(url).feed.title
name = str(title)
db[name] = url
return name | python | def add_feed(url):
"""add to db"""
with Database("feeds") as db:
title = feedparser.parse(url).feed.title
name = str(title)
db[name] = url
return name | [
"def",
"add_feed",
"(",
"url",
")",
":",
"with",
"Database",
"(",
"\"feeds\"",
")",
"as",
"db",
":",
"title",
"=",
"feedparser",
".",
"parse",
"(",
"url",
")",
".",
"feed",
".",
"title",
"name",
"=",
"str",
"(",
"title",
")",
"db",
"[",
"name",
"... | add to db | [
"add",
"to",
"db"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L211-L217 |
jrabbit/hitman | hitman.py | del_feed | def del_feed(name):
"""remove from database (and delete aliases)"""
with Database("aliases") as aliases, Database("feeds") as feeds:
if aliases[name]:
proper_name = aliases[name]
elif feeds[name]:
proper_name = feeds[name]
for k, v in aliases:
if v == proper_name:
del aliases[k]
# deleted from aliases
del feeds[proper_name] | python | def del_feed(name):
"""remove from database (and delete aliases)"""
with Database("aliases") as aliases, Database("feeds") as feeds:
if aliases[name]:
proper_name = aliases[name]
elif feeds[name]:
proper_name = feeds[name]
for k, v in aliases:
if v == proper_name:
del aliases[k]
# deleted from aliases
del feeds[proper_name] | [
"def",
"del_feed",
"(",
"name",
")",
":",
"with",
"Database",
"(",
"\"aliases\"",
")",
"as",
"aliases",
",",
"Database",
"(",
"\"feeds\"",
")",
"as",
"feeds",
":",
"if",
"aliases",
"[",
"name",
"]",
":",
"proper_name",
"=",
"aliases",
"[",
"name",
"]",... | remove from database (and delete aliases) | [
"remove",
"from",
"database",
"(",
"and",
"delete",
"aliases",
")"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L222-L233 |
jrabbit/hitman | hitman.py | del_alias | def del_alias(alias):
"""sometimes you goof up."""
with Database("aliases") as mydb:
try:
print("removing alias of %s to %s" % (alias, mydb.pop(alias)))
except KeyError:
print("No such alias key")
print("Check alias db:")
print(zip(list(mydb.keys()), list(mydb.values()))) | python | def del_alias(alias):
"""sometimes you goof up."""
with Database("aliases") as mydb:
try:
print("removing alias of %s to %s" % (alias, mydb.pop(alias)))
except KeyError:
print("No such alias key")
print("Check alias db:")
print(zip(list(mydb.keys()), list(mydb.values()))) | [
"def",
"del_alias",
"(",
"alias",
")",
":",
"with",
"Database",
"(",
"\"aliases\"",
")",
"as",
"mydb",
":",
"try",
":",
"print",
"(",
"\"removing alias of %s to %s\"",
"%",
"(",
"alias",
",",
"mydb",
".",
"pop",
"(",
"alias",
")",
")",
")",
"except",
"... | sometimes you goof up. | [
"sometimes",
"you",
"goof",
"up",
"."
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L239-L247 |
jrabbit/hitman | hitman.py | alias_feed | def alias_feed(name, alias):
"""write aliases to db"""
with Database("aliases") as db:
if alias in db:
print("Something has gone horribly wrong with your aliases! Try deleting the %s entry." % name)
return
else:
db[alias] = name | python | def alias_feed(name, alias):
"""write aliases to db"""
with Database("aliases") as db:
if alias in db:
print("Something has gone horribly wrong with your aliases! Try deleting the %s entry." % name)
return
else:
db[alias] = name | [
"def",
"alias_feed",
"(",
"name",
",",
"alias",
")",
":",
"with",
"Database",
"(",
"\"aliases\"",
")",
"as",
"db",
":",
"if",
"alias",
"in",
"db",
":",
"print",
"(",
"\"Something has gone horribly wrong with your aliases! Try deleting the %s entry.\"",
"%",
"name",
... | write aliases to db | [
"write",
"aliases",
"to",
"db"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L253-L260 |
jrabbit/hitman | hitman.py | list_feeds | def list_feeds():
"""List all feeds in plain text and give their aliases"""
with Database("feeds") as feeds, Database("aliases") as aliases_db:
for feed in feeds:
name = feed
url = feeds[feed]
aliases = []
for k, v in zip(list(aliases_db.keys()), list(aliases_db.values())):
if v == name:
aliases.append(k)
if aliases:
print(name, " : %s Aliases: %s" % (url, aliases))
else:
print(name, " : %s" % url) | python | def list_feeds():
"""List all feeds in plain text and give their aliases"""
with Database("feeds") as feeds, Database("aliases") as aliases_db:
for feed in feeds:
name = feed
url = feeds[feed]
aliases = []
for k, v in zip(list(aliases_db.keys()), list(aliases_db.values())):
if v == name:
aliases.append(k)
if aliases:
print(name, " : %s Aliases: %s" % (url, aliases))
else:
print(name, " : %s" % url) | [
"def",
"list_feeds",
"(",
")",
":",
"with",
"Database",
"(",
"\"feeds\"",
")",
"as",
"feeds",
",",
"Database",
"(",
"\"aliases\"",
")",
"as",
"aliases_db",
":",
"for",
"feed",
"in",
"feeds",
":",
"name",
"=",
"feed",
"url",
"=",
"feeds",
"[",
"feed",
... | List all feeds in plain text and give their aliases | [
"List",
"all",
"feeds",
"in",
"plain",
"text",
"and",
"give",
"their",
"aliases"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L282-L295 |
jrabbit/hitman | hitman.py | export_opml | def export_opml():
"""Export an OPML feed list"""
with Database("feeds") as feeds:
# Thanks to the canto project- used under the GPL
print("""<opml version="1.0">""")
print("""<body>""")
# Accurate but slow.
for name in list(feeds.keys()):
kind = feedparser.parse(feeds[name]).version
if kind[:4] == 'atom':
t = 'pie'
elif kind[:3] == 'rss':
t = 'rss'
print("""\t<outline text="%s" xmlUrl="%s" type="%s" />""" % (name, feeds[name], t))
print("""</body>""")
print("""</opml>""") | python | def export_opml():
"""Export an OPML feed list"""
with Database("feeds") as feeds:
# Thanks to the canto project- used under the GPL
print("""<opml version="1.0">""")
print("""<body>""")
# Accurate but slow.
for name in list(feeds.keys()):
kind = feedparser.parse(feeds[name]).version
if kind[:4] == 'atom':
t = 'pie'
elif kind[:3] == 'rss':
t = 'rss'
print("""\t<outline text="%s" xmlUrl="%s" type="%s" />""" % (name, feeds[name], t))
print("""</body>""")
print("""</opml>""") | [
"def",
"export_opml",
"(",
")",
":",
"with",
"Database",
"(",
"\"feeds\"",
")",
"as",
"feeds",
":",
"# Thanks to the canto project- used under the GPL",
"print",
"(",
"\"\"\"<opml version=\"1.0\">\"\"\"",
")",
"print",
"(",
"\"\"\"<body>\"\"\"",
")",
"# Accurate but slow.... | Export an OPML feed list | [
"Export",
"an",
"OPML",
"feed",
"list"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L299-L314 |
jrabbit/hitman | hitman.py | import_opml | def import_opml(url):
"""Import an OPML file locally or from a URL. Uses your text attributes as aliases."""
# Test if URL given is local, then open, parse out feed urls,
# add feeds, set text= to aliases and report success, list feeds added
from bs4 import BeautifulSoup
try:
f = file(url).read()
except IOError:
f = requests.get(url).text
soup = BeautifulSoup(f, "xml")
links = soup.find_all('outline', type="rss" or "pie")
# This is very slow, might cache this info on add
for link in links:
# print link
add_feed(link['xmlUrl'])
print("Added " + link['text']) | python | def import_opml(url):
"""Import an OPML file locally or from a URL. Uses your text attributes as aliases."""
# Test if URL given is local, then open, parse out feed urls,
# add feeds, set text= to aliases and report success, list feeds added
from bs4 import BeautifulSoup
try:
f = file(url).read()
except IOError:
f = requests.get(url).text
soup = BeautifulSoup(f, "xml")
links = soup.find_all('outline', type="rss" or "pie")
# This is very slow, might cache this info on add
for link in links:
# print link
add_feed(link['xmlUrl'])
print("Added " + link['text']) | [
"def",
"import_opml",
"(",
"url",
")",
":",
"# Test if URL given is local, then open, parse out feed urls,",
"# add feeds, set text= to aliases and report success, list feeds added",
"from",
"bs4",
"import",
"BeautifulSoup",
"try",
":",
"f",
"=",
"file",
"(",
"url",
")",
".",... | Import an OPML file locally or from a URL. Uses your text attributes as aliases. | [
"Import",
"an",
"OPML",
"file",
"locally",
"or",
"from",
"a",
"URL",
".",
"Uses",
"your",
"text",
"attributes",
"as",
"aliases",
"."
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L320-L335 |
jrabbit/hitman | hitman.py | directory | def directory():
"""Construct hitman_dir from os name"""
home = os.path.expanduser('~')
if platform.system() == 'Linux':
hitman_dir = os.path.join(home, '.hitman')
elif platform.system() == 'Darwin':
hitman_dir = os.path.join(home, 'Library', 'Application Support',
'hitman')
elif platform.system() == 'Windows':
hitman_dir = os.path.join(os.environ['appdata'], 'hitman')
else:
hitman_dir = os.path.join(home, '.hitman')
if not os.path.isdir(hitman_dir):
os.mkdir(hitman_dir)
return hitman_dir | python | def directory():
"""Construct hitman_dir from os name"""
home = os.path.expanduser('~')
if platform.system() == 'Linux':
hitman_dir = os.path.join(home, '.hitman')
elif platform.system() == 'Darwin':
hitman_dir = os.path.join(home, 'Library', 'Application Support',
'hitman')
elif platform.system() == 'Windows':
hitman_dir = os.path.join(os.environ['appdata'], 'hitman')
else:
hitman_dir = os.path.join(home, '.hitman')
if not os.path.isdir(hitman_dir):
os.mkdir(hitman_dir)
return hitman_dir | [
"def",
"directory",
"(",
")",
":",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Linux'",
":",
"hitman_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"'.hitman'"... | Construct hitman_dir from os name | [
"Construct",
"hitman_dir",
"from",
"os",
"name"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L348-L362 |
jrabbit/hitman | hitman.py | add | def add(url, force=False):
"""Add a atom or RSS feed by url.
If it doesn't end in .atom or .rss we'll do some guessing."""
if url[-3:] == 'xml' or url[1][-4:] == 'atom':
print("Added your feed as %s" % str(add_feed(url)))
elif is_feed(url):
print("Added your feed as %s" % str(add_feed(url)))
elif force:
print("Added your feed as %s" % str(add_feed(url)))
else:
print("Hitman doesn't think that url is a feed; if you're sure it is rerun with --force") | python | def add(url, force=False):
"""Add a atom or RSS feed by url.
If it doesn't end in .atom or .rss we'll do some guessing."""
if url[-3:] == 'xml' or url[1][-4:] == 'atom':
print("Added your feed as %s" % str(add_feed(url)))
elif is_feed(url):
print("Added your feed as %s" % str(add_feed(url)))
elif force:
print("Added your feed as %s" % str(add_feed(url)))
else:
print("Hitman doesn't think that url is a feed; if you're sure it is rerun with --force") | [
"def",
"add",
"(",
"url",
",",
"force",
"=",
"False",
")",
":",
"if",
"url",
"[",
"-",
"3",
":",
"]",
"==",
"'xml'",
"or",
"url",
"[",
"1",
"]",
"[",
"-",
"4",
":",
"]",
"==",
"'atom'",
":",
"print",
"(",
"\"Added your feed as %s\"",
"%",
"str"... | Add a atom or RSS feed by url.
If it doesn't end in .atom or .rss we'll do some guessing. | [
"Add",
"a",
"atom",
"or",
"RSS",
"feed",
"by",
"url",
".",
"If",
"it",
"doesn",
"t",
"end",
"in",
".",
"atom",
"or",
".",
"rss",
"we",
"ll",
"do",
"some",
"guessing",
"."
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L368-L378 |
jrabbit/hitman | hitman.py | set_settings | def set_settings(key, value):
"""Set Hitman internal settings."""
with Database("settings") as settings:
if value in ['0', 'false', 'no', 'off', 'False']:
del settings[key]
print("Disabled setting")
else:
print(value)
settings[key] = value
print("Setting saved") | python | def set_settings(key, value):
"""Set Hitman internal settings."""
with Database("settings") as settings:
if value in ['0', 'false', 'no', 'off', 'False']:
del settings[key]
print("Disabled setting")
else:
print(value)
settings[key] = value
print("Setting saved") | [
"def",
"set_settings",
"(",
"key",
",",
"value",
")",
":",
"with",
"Database",
"(",
"\"settings\"",
")",
"as",
"settings",
":",
"if",
"value",
"in",
"[",
"'0'",
",",
"'false'",
",",
"'no'",
",",
"'off'",
",",
"'False'",
"]",
":",
"del",
"settings",
"... | Set Hitman internal settings. | [
"Set",
"Hitman",
"internal",
"settings",
"."
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L384-L393 |
jrabbit/hitman | hitman.py | get_settings | def get_settings(all,key):
"""View Hitman internal settings. Use 'all' for all keys"""
with Database("settings") as s:
if all:
for k, v in zip(list(s.keys()), list(s.values())):
print("{} = {}".format(k, v))
elif key:
print("{} = {}".format(key, s[key]))
else:
print("Don't know what you want? Try --all") | python | def get_settings(all,key):
"""View Hitman internal settings. Use 'all' for all keys"""
with Database("settings") as s:
if all:
for k, v in zip(list(s.keys()), list(s.values())):
print("{} = {}".format(k, v))
elif key:
print("{} = {}".format(key, s[key]))
else:
print("Don't know what you want? Try --all") | [
"def",
"get_settings",
"(",
"all",
",",
"key",
")",
":",
"with",
"Database",
"(",
"\"settings\"",
")",
"as",
"s",
":",
"if",
"all",
":",
"for",
"k",
",",
"v",
"in",
"zip",
"(",
"list",
"(",
"s",
".",
"keys",
"(",
")",
")",
",",
"list",
"(",
"... | View Hitman internal settings. Use 'all' for all keys | [
"View",
"Hitman",
"internal",
"settings",
".",
"Use",
"all",
"for",
"all",
"keys"
] | train | https://github.com/jrabbit/hitman/blob/407351cb729956e2e1673d0aae741e1fa5f61b31/hitman.py#L399-L408 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | Challenge.fromdict | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Challenge
object from the dictionary.
:param dict: the dictionary to convert
"""
seed = hb_decode(dict['seed'])
index = dict['index']
return Challenge(seed, index) | python | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Challenge
object from the dictionary.
:param dict: the dictionary to convert
"""
seed = hb_decode(dict['seed'])
index = dict['index']
return Challenge(seed, index) | [
"def",
"fromdict",
"(",
"dict",
")",
":",
"seed",
"=",
"hb_decode",
"(",
"dict",
"[",
"'seed'",
"]",
")",
"index",
"=",
"dict",
"[",
"'index'",
"]",
"return",
"Challenge",
"(",
"seed",
",",
"index",
")"
] | Takes a dictionary as an argument and returns a new Challenge
object from the dictionary.
:param dict: the dictionary to convert | [
"Takes",
"a",
"dictionary",
"as",
"an",
"argument",
"and",
"returns",
"a",
"new",
"Challenge",
"object",
"from",
"the",
"dictionary",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L75-L83 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | Tag.fromdict | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Tag object
from the dictionary.
:param dict: the dictionary to convert
"""
tree = MerkleTree.fromdict(dict['tree'])
chunksz = dict['chunksz']
filesz = dict['filesz']
return Tag(tree, chunksz, filesz) | python | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Tag object
from the dictionary.
:param dict: the dictionary to convert
"""
tree = MerkleTree.fromdict(dict['tree'])
chunksz = dict['chunksz']
filesz = dict['filesz']
return Tag(tree, chunksz, filesz) | [
"def",
"fromdict",
"(",
"dict",
")",
":",
"tree",
"=",
"MerkleTree",
".",
"fromdict",
"(",
"dict",
"[",
"'tree'",
"]",
")",
"chunksz",
"=",
"dict",
"[",
"'chunksz'",
"]",
"filesz",
"=",
"dict",
"[",
"'filesz'",
"]",
"return",
"Tag",
"(",
"tree",
",",... | Takes a dictionary as an argument and returns a new Tag object
from the dictionary.
:param dict: the dictionary to convert | [
"Takes",
"a",
"dictionary",
"as",
"an",
"argument",
"and",
"returns",
"a",
"new",
"Tag",
"object",
"from",
"the",
"dictionary",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L122-L131 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | State.todict | def todict(self):
"""Returns a dictionary fully representing the state of this object
"""
return {'index': self.index,
'seed': hb_encode(self.seed),
'n': self.n,
'root': hb_encode(self.root),
'hmac': hb_encode(self.hmac),
'timestamp': self.timestamp} | python | def todict(self):
"""Returns a dictionary fully representing the state of this object
"""
return {'index': self.index,
'seed': hb_encode(self.seed),
'n': self.n,
'root': hb_encode(self.root),
'hmac': hb_encode(self.hmac),
'timestamp': self.timestamp} | [
"def",
"todict",
"(",
"self",
")",
":",
"return",
"{",
"'index'",
":",
"self",
".",
"index",
",",
"'seed'",
":",
"hb_encode",
"(",
"self",
".",
"seed",
")",
",",
"'n'",
":",
"self",
".",
"n",
",",
"'root'",
":",
"hb_encode",
"(",
"self",
".",
"ro... | Returns a dictionary fully representing the state of this object | [
"Returns",
"a",
"dictionary",
"fully",
"representing",
"the",
"state",
"of",
"this",
"object"
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L183-L191 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | State.fromdict | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new State object
from the dictionary.
:param dict: the dictionary to convert
"""
index = dict['index']
seed = hb_decode(dict['seed'])
n = dict['n']
root = hb_decode(dict['root'])
hmac = hb_decode(dict['hmac'])
timestamp = dict['timestamp']
self = State(index, seed, n, root, hmac, timestamp)
return self | python | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new State object
from the dictionary.
:param dict: the dictionary to convert
"""
index = dict['index']
seed = hb_decode(dict['seed'])
n = dict['n']
root = hb_decode(dict['root'])
hmac = hb_decode(dict['hmac'])
timestamp = dict['timestamp']
self = State(index, seed, n, root, hmac, timestamp)
return self | [
"def",
"fromdict",
"(",
"dict",
")",
":",
"index",
"=",
"dict",
"[",
"'index'",
"]",
"seed",
"=",
"hb_decode",
"(",
"dict",
"[",
"'seed'",
"]",
")",
"n",
"=",
"dict",
"[",
"'n'",
"]",
"root",
"=",
"hb_decode",
"(",
"dict",
"[",
"'root'",
"]",
")"... | Takes a dictionary as an argument and returns a new State object
from the dictionary.
:param dict: the dictionary to convert | [
"Takes",
"a",
"dictionary",
"as",
"an",
"argument",
"and",
"returns",
"a",
"new",
"State",
"object",
"from",
"the",
"dictionary",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L194-L207 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | State.get_hmac | def get_hmac(self, key):
"""Returns the keyed HMAC for authentication of this state data.
:param key: the key for the keyed hash function
"""
h = HMAC.new(key, None, SHA256)
h.update(str(self.index).encode())
h.update(self.seed)
h.update(str(self.n).encode())
h.update(self.root)
h.update(str(self.timestamp).encode())
return h.digest() | python | def get_hmac(self, key):
"""Returns the keyed HMAC for authentication of this state data.
:param key: the key for the keyed hash function
"""
h = HMAC.new(key, None, SHA256)
h.update(str(self.index).encode())
h.update(self.seed)
h.update(str(self.n).encode())
h.update(self.root)
h.update(str(self.timestamp).encode())
return h.digest() | [
"def",
"get_hmac",
"(",
"self",
",",
"key",
")",
":",
"h",
"=",
"HMAC",
".",
"new",
"(",
"key",
",",
"None",
",",
"SHA256",
")",
"h",
".",
"update",
"(",
"str",
"(",
"self",
".",
"index",
")",
".",
"encode",
"(",
")",
")",
"h",
".",
"update",... | Returns the keyed HMAC for authentication of this state data.
:param key: the key for the keyed hash function | [
"Returns",
"the",
"keyed",
"HMAC",
"for",
"authentication",
"of",
"this",
"state",
"data",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L209-L220 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | Merkle.fromdict | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Proof object
from the dictionary.
:param dict: the dictionary to convert
"""
key = hb_decode(dict['key'])
check_fraction = dict['check_fraction']
return Merkle(check_fraction, key) | python | def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Proof object
from the dictionary.
:param dict: the dictionary to convert
"""
key = hb_decode(dict['key'])
check_fraction = dict['check_fraction']
return Merkle(check_fraction, key) | [
"def",
"fromdict",
"(",
"dict",
")",
":",
"key",
"=",
"hb_decode",
"(",
"dict",
"[",
"'key'",
"]",
")",
"check_fraction",
"=",
"dict",
"[",
"'check_fraction'",
"]",
"return",
"Merkle",
"(",
"check_fraction",
",",
"key",
")"
] | Takes a dictionary as an argument and returns a new Proof object
from the dictionary.
:param dict: the dictionary to convert | [
"Takes",
"a",
"dictionary",
"as",
"an",
"argument",
"and",
"returns",
"a",
"new",
"Proof",
"object",
"from",
"the",
"dictionary",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L308-L316 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | Merkle.encode | def encode(self,
file,
n=DEFAULT_CHALLENGE_COUNT,
seed=None,
chunksz=None,
filesz=None):
"""This function generates a merkle tree with the leaves as seed file
hashes, the seed for each leaf being a deterministic seed generated
from a key.
:param file: a file like object that supports the `read()`, `seek()`
and `tell()` methods
:param n: the number of challenges to generate
:param seed: the root seed for this batch of challenges. by default
generates a random seed
:param chunksz: the chunk size for breaking up the file: the amount
of the file that will be checked by each challenge. defaults
to the chunk size defined by check_fraction
:param filesz: optional size of the file. if not specified, file size
will be detected by seeking to the end of the file and reading the
position
"""
if (seed is None):
seed = os.urandom(DEFAULT_KEY_SIZE)
if (filesz is None):
file.seek(0, 2)
filesz = file.tell()
if (chunksz is None):
if (self.check_fraction is not None):
chunksz = int(self.check_fraction * filesz)
else:
chunksz = DEFAULT_CHUNK_SIZE
mt = MerkleTree()
state = State(0, seed, n)
seed = MerkleHelper.get_next_seed(self.key, state.seed)
for i in range(0, n):
leaf = MerkleHelper.get_chunk_hash(file, seed, filesz, chunksz)
mt.add_leaf(leaf)
seed = MerkleHelper.get_next_seed(self.key, seed)
mt.build()
state.root = mt.get_root()
mt.strip_leaves()
tag = Tag(mt, chunksz, filesz)
state.sign(self.key)
return (tag, state) | python | def encode(self,
file,
n=DEFAULT_CHALLENGE_COUNT,
seed=None,
chunksz=None,
filesz=None):
"""This function generates a merkle tree with the leaves as seed file
hashes, the seed for each leaf being a deterministic seed generated
from a key.
:param file: a file like object that supports the `read()`, `seek()`
and `tell()` methods
:param n: the number of challenges to generate
:param seed: the root seed for this batch of challenges. by default
generates a random seed
:param chunksz: the chunk size for breaking up the file: the amount
of the file that will be checked by each challenge. defaults
to the chunk size defined by check_fraction
:param filesz: optional size of the file. if not specified, file size
will be detected by seeking to the end of the file and reading the
position
"""
if (seed is None):
seed = os.urandom(DEFAULT_KEY_SIZE)
if (filesz is None):
file.seek(0, 2)
filesz = file.tell()
if (chunksz is None):
if (self.check_fraction is not None):
chunksz = int(self.check_fraction * filesz)
else:
chunksz = DEFAULT_CHUNK_SIZE
mt = MerkleTree()
state = State(0, seed, n)
seed = MerkleHelper.get_next_seed(self.key, state.seed)
for i in range(0, n):
leaf = MerkleHelper.get_chunk_hash(file, seed, filesz, chunksz)
mt.add_leaf(leaf)
seed = MerkleHelper.get_next_seed(self.key, seed)
mt.build()
state.root = mt.get_root()
mt.strip_leaves()
tag = Tag(mt, chunksz, filesz)
state.sign(self.key)
return (tag, state) | [
"def",
"encode",
"(",
"self",
",",
"file",
",",
"n",
"=",
"DEFAULT_CHALLENGE_COUNT",
",",
"seed",
"=",
"None",
",",
"chunksz",
"=",
"None",
",",
"filesz",
"=",
"None",
")",
":",
"if",
"(",
"seed",
"is",
"None",
")",
":",
"seed",
"=",
"os",
".",
"... | This function generates a merkle tree with the leaves as seed file
hashes, the seed for each leaf being a deterministic seed generated
from a key.
:param file: a file like object that supports the `read()`, `seek()`
and `tell()` methods
:param n: the number of challenges to generate
:param seed: the root seed for this batch of challenges. by default
generates a random seed
:param chunksz: the chunk size for breaking up the file: the amount
of the file that will be checked by each challenge. defaults
to the chunk size defined by check_fraction
:param filesz: optional size of the file. if not specified, file size
will be detected by seeking to the end of the file and reading the
position | [
"This",
"function",
"generates",
"a",
"merkle",
"tree",
"with",
"the",
"leaves",
"as",
"seed",
"file",
"hashes",
"the",
"seed",
"for",
"each",
"leaf",
"being",
"a",
"deterministic",
"seed",
"generated",
"from",
"a",
"key",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L323-L367 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | Merkle.gen_challenge | def gen_challenge(self, state):
"""returns the next challenge and increments the seed and index
in the state.
:param state: the state to use for generating the challenge. will
verify the integrity of the state object before using it to generate
a challenge. it will then modify the state by incrementing the seed
and index and resign the state for passing back to the server for
storage
"""
state.checksig(self.key)
if (state.index >= state.n):
raise HeartbeatError("Out of challenges.")
state.seed = MerkleHelper.get_next_seed(self.key, state.seed)
chal = Challenge(state.seed, state.index)
state.index += 1
state.sign(self.key)
return chal | python | def gen_challenge(self, state):
"""returns the next challenge and increments the seed and index
in the state.
:param state: the state to use for generating the challenge. will
verify the integrity of the state object before using it to generate
a challenge. it will then modify the state by incrementing the seed
and index and resign the state for passing back to the server for
storage
"""
state.checksig(self.key)
if (state.index >= state.n):
raise HeartbeatError("Out of challenges.")
state.seed = MerkleHelper.get_next_seed(self.key, state.seed)
chal = Challenge(state.seed, state.index)
state.index += 1
state.sign(self.key)
return chal | [
"def",
"gen_challenge",
"(",
"self",
",",
"state",
")",
":",
"state",
".",
"checksig",
"(",
"self",
".",
"key",
")",
"if",
"(",
"state",
".",
"index",
">=",
"state",
".",
"n",
")",
":",
"raise",
"HeartbeatError",
"(",
"\"Out of challenges.\"",
")",
"st... | returns the next challenge and increments the seed and index
in the state.
:param state: the state to use for generating the challenge. will
verify the integrity of the state object before using it to generate
a challenge. it will then modify the state by incrementing the seed
and index and resign the state for passing back to the server for
storage | [
"returns",
"the",
"next",
"challenge",
"and",
"increments",
"the",
"seed",
"and",
"index",
"in",
"the",
"state",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L369-L386 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | Merkle.prove | def prove(self, file, challenge, tag):
"""Returns a proof of ownership of the given file based on the
challenge. The proof consists of a hash of the specified file chunk
and the complete merkle branch.
:param file: a file that supports `read()`, `seek()` and `tell()`
:param challenge: the challenge to use for generating this proof
:param tag: the file tag as provided from the client
:param filesz: optional filesz parameter. if not specified, the
filesz will be detected by seeking to the end of the stream
"""
leaf = MerkleLeaf(challenge.index,
MerkleHelper.get_chunk_hash(file,
challenge.seed,
filesz=tag.filesz,
chunksz=tag.chunksz))
return Proof(leaf, tag.tree.get_branch(challenge.index)) | python | def prove(self, file, challenge, tag):
"""Returns a proof of ownership of the given file based on the
challenge. The proof consists of a hash of the specified file chunk
and the complete merkle branch.
:param file: a file that supports `read()`, `seek()` and `tell()`
:param challenge: the challenge to use for generating this proof
:param tag: the file tag as provided from the client
:param filesz: optional filesz parameter. if not specified, the
filesz will be detected by seeking to the end of the stream
"""
leaf = MerkleLeaf(challenge.index,
MerkleHelper.get_chunk_hash(file,
challenge.seed,
filesz=tag.filesz,
chunksz=tag.chunksz))
return Proof(leaf, tag.tree.get_branch(challenge.index)) | [
"def",
"prove",
"(",
"self",
",",
"file",
",",
"challenge",
",",
"tag",
")",
":",
"leaf",
"=",
"MerkleLeaf",
"(",
"challenge",
".",
"index",
",",
"MerkleHelper",
".",
"get_chunk_hash",
"(",
"file",
",",
"challenge",
".",
"seed",
",",
"filesz",
"=",
"ta... | Returns a proof of ownership of the given file based on the
challenge. The proof consists of a hash of the specified file chunk
and the complete merkle branch.
:param file: a file that supports `read()`, `seek()` and `tell()`
:param challenge: the challenge to use for generating this proof
:param tag: the file tag as provided from the client
:param filesz: optional filesz parameter. if not specified, the
filesz will be detected by seeking to the end of the stream | [
"Returns",
"a",
"proof",
"of",
"ownership",
"of",
"the",
"given",
"file",
"based",
"on",
"the",
"challenge",
".",
"The",
"proof",
"consists",
"of",
"a",
"hash",
"of",
"the",
"specified",
"file",
"chunk",
"and",
"the",
"complete",
"merkle",
"branch",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L388-L404 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | Merkle.verify | def verify(self, proof, challenge, state):
"""returns true if the proof matches the challenge. verifies that the
server possesses the encoded file.
:param proof: the proof that was returned from the server
:param challenge: the challenge provided to the server
:param state: the state of the file, which includes the merkle root of
of the merkle tree, for verification.
"""
state.checksig(self.key)
if (proof.leaf.index != challenge.index):
return False
return MerkleTree.verify_branch(proof.leaf,
proof.branch,
state.root) | python | def verify(self, proof, challenge, state):
"""returns true if the proof matches the challenge. verifies that the
server possesses the encoded file.
:param proof: the proof that was returned from the server
:param challenge: the challenge provided to the server
:param state: the state of the file, which includes the merkle root of
of the merkle tree, for verification.
"""
state.checksig(self.key)
if (proof.leaf.index != challenge.index):
return False
return MerkleTree.verify_branch(proof.leaf,
proof.branch,
state.root) | [
"def",
"verify",
"(",
"self",
",",
"proof",
",",
"challenge",
",",
"state",
")",
":",
"state",
".",
"checksig",
"(",
"self",
".",
"key",
")",
"if",
"(",
"proof",
".",
"leaf",
".",
"index",
"!=",
"challenge",
".",
"index",
")",
":",
"return",
"False... | returns true if the proof matches the challenge. verifies that the
server possesses the encoded file.
:param proof: the proof that was returned from the server
:param challenge: the challenge provided to the server
:param state: the state of the file, which includes the merkle root of
of the merkle tree, for verification. | [
"returns",
"true",
"if",
"the",
"proof",
"matches",
"the",
"challenge",
".",
"verifies",
"that",
"the",
"server",
"possesses",
"the",
"encoded",
"file",
"."
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L406-L420 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | MerkleHelper.get_next_seed | def get_next_seed(key, seed):
"""This takes a seed and generates the next seed in the sequence.
it simply calculates the hmac of the seed with the key. It returns
the next seed
:param key: the key to use for the HMAC
:param seed: the seed to permutate
"""
return hmac.new(key, seed, hashlib.sha256).digest() | python | def get_next_seed(key, seed):
"""This takes a seed and generates the next seed in the sequence.
it simply calculates the hmac of the seed with the key. It returns
the next seed
:param key: the key to use for the HMAC
:param seed: the seed to permutate
"""
return hmac.new(key, seed, hashlib.sha256).digest() | [
"def",
"get_next_seed",
"(",
"key",
",",
"seed",
")",
":",
"return",
"hmac",
".",
"new",
"(",
"key",
",",
"seed",
",",
"hashlib",
".",
"sha256",
")",
".",
"digest",
"(",
")"
] | This takes a seed and generates the next seed in the sequence.
it simply calculates the hmac of the seed with the key. It returns
the next seed
:param key: the key to use for the HMAC
:param seed: the seed to permutate | [
"This",
"takes",
"a",
"seed",
"and",
"generates",
"the",
"next",
"seed",
"in",
"the",
"sequence",
".",
"it",
"simply",
"calculates",
"the",
"hmac",
"of",
"the",
"seed",
"with",
"the",
"key",
".",
"It",
"returns",
"the",
"next",
"seed"
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L452-L460 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | MerkleHelper.get_file_hash | def get_file_hash(file, seed, bufsz=DEFAULT_BUFFER_SIZE):
"""This method generates a secure hash of the given file. Returns the
hash
:param file: a file like object to get a hash of. should support
`read()`
:param seed: the seed to use for key of the HMAC function
:param bufsz: an optional buffer size to use for reading the file
"""
h = hmac.new(seed, None, hashlib.sha256)
while (True):
buffer = file.read(bufsz)
h.update(buffer)
if (len(buffer) != bufsz):
break
return h.digest() | python | def get_file_hash(file, seed, bufsz=DEFAULT_BUFFER_SIZE):
"""This method generates a secure hash of the given file. Returns the
hash
:param file: a file like object to get a hash of. should support
`read()`
:param seed: the seed to use for key of the HMAC function
:param bufsz: an optional buffer size to use for reading the file
"""
h = hmac.new(seed, None, hashlib.sha256)
while (True):
buffer = file.read(bufsz)
h.update(buffer)
if (len(buffer) != bufsz):
break
return h.digest() | [
"def",
"get_file_hash",
"(",
"file",
",",
"seed",
",",
"bufsz",
"=",
"DEFAULT_BUFFER_SIZE",
")",
":",
"h",
"=",
"hmac",
".",
"new",
"(",
"seed",
",",
"None",
",",
"hashlib",
".",
"sha256",
")",
"while",
"(",
"True",
")",
":",
"buffer",
"=",
"file",
... | This method generates a secure hash of the given file. Returns the
hash
:param file: a file like object to get a hash of. should support
`read()`
:param seed: the seed to use for key of the HMAC function
:param bufsz: an optional buffer size to use for reading the file | [
"This",
"method",
"generates",
"a",
"secure",
"hash",
"of",
"the",
"given",
"file",
".",
"Returns",
"the",
"hash"
] | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L463-L478 |
StorjOld/heartbeat | heartbeat/Merkle/Merkle.py | MerkleHelper.get_chunk_hash | def get_chunk_hash(file,
seed,
filesz=None,
chunksz=DEFAULT_CHUNK_SIZE,
bufsz=DEFAULT_BUFFER_SIZE):
"""returns a hash of a chunk of the file provided. the position of
the chunk is determined by the seed. additionally, the hmac of the
chunk is calculated from the seed.
:param file: a file like object to get the chunk hash from. should
support `read()`, `seek()` and `tell()`.
:param seed: the seed to use for calculating the chunk position and
chunk hash
:param chunksz: the size of the chunk to check
:param bufsz: an optional buffer size to use for reading the file.
"""
if (filesz is None):
file.seek(0, 2)
filesz = file.tell()
if (filesz < chunksz):
chunksz = filesz
prf = KeyedPRF(seed, filesz - chunksz + 1)
i = prf.eval(0)
file.seek(i)
h = hmac.new(seed, None, hashlib.sha256)
while (True):
if (chunksz < bufsz):
bufsz = chunksz
buffer = file.read(bufsz)
h.update(buffer)
chunksz -= len(buffer)
assert(chunksz >= 0)
if (chunksz == 0):
break
return h.digest() | python | def get_chunk_hash(file,
seed,
filesz=None,
chunksz=DEFAULT_CHUNK_SIZE,
bufsz=DEFAULT_BUFFER_SIZE):
"""returns a hash of a chunk of the file provided. the position of
the chunk is determined by the seed. additionally, the hmac of the
chunk is calculated from the seed.
:param file: a file like object to get the chunk hash from. should
support `read()`, `seek()` and `tell()`.
:param seed: the seed to use for calculating the chunk position and
chunk hash
:param chunksz: the size of the chunk to check
:param bufsz: an optional buffer size to use for reading the file.
"""
if (filesz is None):
file.seek(0, 2)
filesz = file.tell()
if (filesz < chunksz):
chunksz = filesz
prf = KeyedPRF(seed, filesz - chunksz + 1)
i = prf.eval(0)
file.seek(i)
h = hmac.new(seed, None, hashlib.sha256)
while (True):
if (chunksz < bufsz):
bufsz = chunksz
buffer = file.read(bufsz)
h.update(buffer)
chunksz -= len(buffer)
assert(chunksz >= 0)
if (chunksz == 0):
break
return h.digest() | [
"def",
"get_chunk_hash",
"(",
"file",
",",
"seed",
",",
"filesz",
"=",
"None",
",",
"chunksz",
"=",
"DEFAULT_CHUNK_SIZE",
",",
"bufsz",
"=",
"DEFAULT_BUFFER_SIZE",
")",
":",
"if",
"(",
"filesz",
"is",
"None",
")",
":",
"file",
".",
"seek",
"(",
"0",
",... | returns a hash of a chunk of the file provided. the position of
the chunk is determined by the seed. additionally, the hmac of the
chunk is calculated from the seed.
:param file: a file like object to get the chunk hash from. should
support `read()`, `seek()` and `tell()`.
:param seed: the seed to use for calculating the chunk position and
chunk hash
:param chunksz: the size of the chunk to check
:param bufsz: an optional buffer size to use for reading the file. | [
"returns",
"a",
"hash",
"of",
"a",
"chunk",
"of",
"the",
"file",
"provided",
".",
"the",
"position",
"of",
"the",
"chunk",
"is",
"determined",
"by",
"the",
"seed",
".",
"additionally",
"the",
"hmac",
"of",
"the",
"chunk",
"is",
"calculated",
"from",
"the... | train | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L481-L515 |
LasLabs/python-helpscout | helpscout/domain/__init__.py | Domain.from_tuple | def from_tuple(cls, queries):
"""Create a ``Domain`` given a set of complex query tuples.
Args:
queries (iter): An iterator of complex queries. Each iteration
should contain either:
* A data-set compatible with :func:`~domain.Domain.add_query`
* A string to switch the join type
Example::
[('subject', 'Test1'),
'OR',
('subject', 'Test2')',
('subject', 'Test3')',
]
# The above is equivalent to:
# subject:'Test1' OR subject:'Test2' OR subject:'Test3'
[('modified_at', datetime(2017, 01, 01)),
('status', 'active'),
]
# The above is equivalent to:
# modified_at:[2017-01-01T00:00:00Z TO *]
# AND status:"active"
Returns:
Domain: A domain representing the input queries.
"""
domain = cls()
join_with = cls.AND
for query in queries:
if query in [cls.OR, cls.AND]:
join_with = query
else:
domain.add_query(query, join_with)
return domain | python | def from_tuple(cls, queries):
"""Create a ``Domain`` given a set of complex query tuples.
Args:
queries (iter): An iterator of complex queries. Each iteration
should contain either:
* A data-set compatible with :func:`~domain.Domain.add_query`
* A string to switch the join type
Example::
[('subject', 'Test1'),
'OR',
('subject', 'Test2')',
('subject', 'Test3')',
]
# The above is equivalent to:
# subject:'Test1' OR subject:'Test2' OR subject:'Test3'
[('modified_at', datetime(2017, 01, 01)),
('status', 'active'),
]
# The above is equivalent to:
# modified_at:[2017-01-01T00:00:00Z TO *]
# AND status:"active"
Returns:
Domain: A domain representing the input queries.
"""
domain = cls()
join_with = cls.AND
for query in queries:
if query in [cls.OR, cls.AND]:
join_with = query
else:
domain.add_query(query, join_with)
return domain | [
"def",
"from_tuple",
"(",
"cls",
",",
"queries",
")",
":",
"domain",
"=",
"cls",
"(",
")",
"join_with",
"=",
"cls",
".",
"AND",
"for",
"query",
"in",
"queries",
":",
"if",
"query",
"in",
"[",
"cls",
".",
"OR",
",",
"cls",
".",
"AND",
"]",
":",
... | Create a ``Domain`` given a set of complex query tuples.
Args:
queries (iter): An iterator of complex queries. Each iteration
should contain either:
* A data-set compatible with :func:`~domain.Domain.add_query`
* A string to switch the join type
Example::
[('subject', 'Test1'),
'OR',
('subject', 'Test2')',
('subject', 'Test3')',
]
# The above is equivalent to:
# subject:'Test1' OR subject:'Test2' OR subject:'Test3'
[('modified_at', datetime(2017, 01, 01)),
('status', 'active'),
]
# The above is equivalent to:
# modified_at:[2017-01-01T00:00:00Z TO *]
# AND status:"active"
Returns:
Domain: A domain representing the input queries. | [
"Create",
"a",
"Domain",
"given",
"a",
"set",
"of",
"complex",
"query",
"tuples",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/domain/__init__.py#L26-L63 |
LasLabs/python-helpscout | helpscout/domain/__init__.py | Domain.add_query | def add_query(self, query, join_with=AND):
"""Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the interface defined in
:func:`~.domain.DomainCondition.from_tuple`.
join_with (str): The join string to apply, if other queries are
already on the stack.
"""
if not isinstance(query, DomainCondition):
query = DomainCondition.from_tuple(query)
if len(self.query):
self.query.append(join_with)
self.query.append(query) | python | def add_query(self, query, join_with=AND):
"""Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the interface defined in
:func:`~.domain.DomainCondition.from_tuple`.
join_with (str): The join string to apply, if other queries are
already on the stack.
"""
if not isinstance(query, DomainCondition):
query = DomainCondition.from_tuple(query)
if len(self.query):
self.query.append(join_with)
self.query.append(query) | [
"def",
"add_query",
"(",
"self",
",",
"query",
",",
"join_with",
"=",
"AND",
")",
":",
"if",
"not",
"isinstance",
"(",
"query",
",",
"DomainCondition",
")",
":",
"query",
"=",
"DomainCondition",
".",
"from_tuple",
"(",
"query",
")",
"if",
"len",
"(",
"... | Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the interface defined in
:func:`~.domain.DomainCondition.from_tuple`.
join_with (str): The join string to apply, if other queries are
already on the stack. | [
"Join",
"a",
"new",
"query",
"to",
"existing",
"queries",
"on",
"the",
"stack",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/domain/__init__.py#L65-L80 |
LasLabs/python-helpscout | helpscout/domain/__init__.py | DomainCondition.from_tuple | def from_tuple(cls, query):
"""Create a condition from a query tuple.
Args:
query (tuple or list): Tuple or list that contains a query domain
in the format of ``(field_name, field_value,
field_value_to)``. ``field_value_to`` is only applicable in
the case of a date search.
Returns:
DomainCondition: An instance of a domain condition. The specific
type will depend on the data type of the first value provided
in ``query``.
"""
field, query = query[0], query[1:]
try:
cls = TYPES[type(query[0])]
except KeyError:
# We just fallback to the base class if unknown type.
pass
return cls(field, *query) | python | def from_tuple(cls, query):
"""Create a condition from a query tuple.
Args:
query (tuple or list): Tuple or list that contains a query domain
in the format of ``(field_name, field_value,
field_value_to)``. ``field_value_to`` is only applicable in
the case of a date search.
Returns:
DomainCondition: An instance of a domain condition. The specific
type will depend on the data type of the first value provided
in ``query``.
"""
field, query = query[0], query[1:]
try:
cls = TYPES[type(query[0])]
except KeyError:
# We just fallback to the base class if unknown type.
pass
return cls(field, *query) | [
"def",
"from_tuple",
"(",
"cls",
",",
"query",
")",
":",
"field",
",",
"query",
"=",
"query",
"[",
"0",
"]",
",",
"query",
"[",
"1",
":",
"]",
"try",
":",
"cls",
"=",
"TYPES",
"[",
"type",
"(",
"query",
"[",
"0",
"]",
")",
"]",
"except",
"Key... | Create a condition from a query tuple.
Args:
query (tuple or list): Tuple or list that contains a query domain
in the format of ``(field_name, field_value,
field_value_to)``. ``field_value_to`` is only applicable in
the case of a date search.
Returns:
DomainCondition: An instance of a domain condition. The specific
type will depend on the data type of the first value provided
in ``query``. | [
"Create",
"a",
"condition",
"from",
"a",
"query",
"tuple",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/domain/__init__.py#L121-L144 |
Locu/chronology | kronos/kronos/storage/router.py | StorageRouter.load_backends | def load_backends(self):
"""
Loads all the backends setup in settings.py.
"""
for name, backend_settings in settings.storage.iteritems():
backend_path = backend_settings['backend']
backend_module, backend_cls = backend_path.rsplit('.', 1)
backend_module = import_module(backend_module)
# Create an instance of the configured backend.
backend_constructor = getattr(backend_module, backend_cls)
self.backends[name] = backend_constructor(name,
self.namespaces,
**backend_settings) | python | def load_backends(self):
"""
Loads all the backends setup in settings.py.
"""
for name, backend_settings in settings.storage.iteritems():
backend_path = backend_settings['backend']
backend_module, backend_cls = backend_path.rsplit('.', 1)
backend_module = import_module(backend_module)
# Create an instance of the configured backend.
backend_constructor = getattr(backend_module, backend_cls)
self.backends[name] = backend_constructor(name,
self.namespaces,
**backend_settings) | [
"def",
"load_backends",
"(",
"self",
")",
":",
"for",
"name",
",",
"backend_settings",
"in",
"settings",
".",
"storage",
".",
"iteritems",
"(",
")",
":",
"backend_path",
"=",
"backend_settings",
"[",
"'backend'",
"]",
"backend_module",
",",
"backend_cls",
"=",... | Loads all the backends setup in settings.py. | [
"Loads",
"all",
"the",
"backends",
"setup",
"in",
"settings",
".",
"py",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/router.py#L37-L49 |
Locu/chronology | kronos/kronos/storage/router.py | StorageRouter.get_matching_prefix | def get_matching_prefix(self, namespace, stream):
"""
We look at the stream prefixs configured in stream.yaml and match stream
to the longest prefix.
"""
validate_stream(stream)
default_prefix = ''
longest_prefix = default_prefix
for prefix in self.prefix_confs[namespace]:
if prefix == default_prefix:
continue
if not stream.startswith(prefix):
continue
if len(prefix) <= len(longest_prefix):
continue
longest_prefix = prefix
return longest_prefix | python | def get_matching_prefix(self, namespace, stream):
"""
We look at the stream prefixs configured in stream.yaml and match stream
to the longest prefix.
"""
validate_stream(stream)
default_prefix = ''
longest_prefix = default_prefix
for prefix in self.prefix_confs[namespace]:
if prefix == default_prefix:
continue
if not stream.startswith(prefix):
continue
if len(prefix) <= len(longest_prefix):
continue
longest_prefix = prefix
return longest_prefix | [
"def",
"get_matching_prefix",
"(",
"self",
",",
"namespace",
",",
"stream",
")",
":",
"validate_stream",
"(",
"stream",
")",
"default_prefix",
"=",
"''",
"longest_prefix",
"=",
"default_prefix",
"for",
"prefix",
"in",
"self",
".",
"prefix_confs",
"[",
"namespace... | We look at the stream prefixs configured in stream.yaml and match stream
to the longest prefix. | [
"We",
"look",
"at",
"the",
"stream",
"prefixs",
"configured",
"in",
"stream",
".",
"yaml",
"and",
"match",
"stream",
"to",
"the",
"longest",
"prefix",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/router.py#L83-L99 |
Locu/chronology | kronos/kronos/storage/router.py | StorageRouter.backends_to_mutate | def backends_to_mutate(self, namespace, stream):
"""
Return all the backends enabled for writing for `stream`.
"""
if namespace not in self.namespaces:
raise NamespaceMissing('`{}` namespace is not configured'
.format(namespace))
return self.prefix_confs[namespace][self.get_matching_prefix(namespace,
stream)] | python | def backends_to_mutate(self, namespace, stream):
"""
Return all the backends enabled for writing for `stream`.
"""
if namespace not in self.namespaces:
raise NamespaceMissing('`{}` namespace is not configured'
.format(namespace))
return self.prefix_confs[namespace][self.get_matching_prefix(namespace,
stream)] | [
"def",
"backends_to_mutate",
"(",
"self",
",",
"namespace",
",",
"stream",
")",
":",
"if",
"namespace",
"not",
"in",
"self",
".",
"namespaces",
":",
"raise",
"NamespaceMissing",
"(",
"'`{}` namespace is not configured'",
".",
"format",
"(",
"namespace",
")",
")"... | Return all the backends enabled for writing for `stream`. | [
"Return",
"all",
"the",
"backends",
"enabled",
"for",
"writing",
"for",
"stream",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/router.py#L101-L109 |
Locu/chronology | kronos/kronos/storage/router.py | StorageRouter.backend_to_retrieve | def backend_to_retrieve(self, namespace, stream):
"""
Return backend enabled for reading for `stream`.
"""
if namespace not in self.namespaces:
raise NamespaceMissing('`{}` namespace is not configured'
.format(namespace))
stream_prefix = self.get_matching_prefix(namespace, stream)
read_backend = self.prefix_read_backends[namespace][stream_prefix]
return (read_backend,
self.prefix_confs[namespace][stream_prefix][read_backend]) | python | def backend_to_retrieve(self, namespace, stream):
"""
Return backend enabled for reading for `stream`.
"""
if namespace not in self.namespaces:
raise NamespaceMissing('`{}` namespace is not configured'
.format(namespace))
stream_prefix = self.get_matching_prefix(namespace, stream)
read_backend = self.prefix_read_backends[namespace][stream_prefix]
return (read_backend,
self.prefix_confs[namespace][stream_prefix][read_backend]) | [
"def",
"backend_to_retrieve",
"(",
"self",
",",
"namespace",
",",
"stream",
")",
":",
"if",
"namespace",
"not",
"in",
"self",
".",
"namespaces",
":",
"raise",
"NamespaceMissing",
"(",
"'`{}` namespace is not configured'",
".",
"format",
"(",
"namespace",
")",
")... | Return backend enabled for reading for `stream`. | [
"Return",
"backend",
"enabled",
"for",
"reading",
"for",
"stream",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/router.py#L111-L121 |
LasLabs/python-helpscout | helpscout/apis/web_hook.py | WebHook.create | def create(cls, session, web_hook):
"""Create a web hook.
Note that creating a new web hook will overwrite the web hook that is
already configured for this company. There is also no way to
programmatically determine if a web hook already exists for the
company. This is a limitation of the HelpScout API and cannot be
circumvented.
Args:
session (requests.sessions.Session): Authenticated session.
web_hook (helpscout.models.WebHook): The web hook to be created.
Returns:
bool: ``True`` if the creation was a success. Errors otherwise.
"""
cls(
'/hooks.json',
data=web_hook.to_api(),
request_type=RequestPaginator.POST,
session=session,
)
return True | python | def create(cls, session, web_hook):
"""Create a web hook.
Note that creating a new web hook will overwrite the web hook that is
already configured for this company. There is also no way to
programmatically determine if a web hook already exists for the
company. This is a limitation of the HelpScout API and cannot be
circumvented.
Args:
session (requests.sessions.Session): Authenticated session.
web_hook (helpscout.models.WebHook): The web hook to be created.
Returns:
bool: ``True`` if the creation was a success. Errors otherwise.
"""
cls(
'/hooks.json',
data=web_hook.to_api(),
request_type=RequestPaginator.POST,
session=session,
)
return True | [
"def",
"create",
"(",
"cls",
",",
"session",
",",
"web_hook",
")",
":",
"cls",
"(",
"'/hooks.json'",
",",
"data",
"=",
"web_hook",
".",
"to_api",
"(",
")",
",",
"request_type",
"=",
"RequestPaginator",
".",
"POST",
",",
"session",
"=",
"session",
",",
... | Create a web hook.
Note that creating a new web hook will overwrite the web hook that is
already configured for this company. There is also no way to
programmatically determine if a web hook already exists for the
company. This is a limitation of the HelpScout API and cannot be
circumvented.
Args:
session (requests.sessions.Session): Authenticated session.
web_hook (helpscout.models.WebHook): The web hook to be created.
Returns:
bool: ``True`` if the creation was a success. Errors otherwise. | [
"Create",
"a",
"web",
"hook",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/apis/web_hook.py#L24-L46 |
LasLabs/python-helpscout | helpscout/models/attachment_data.py | AttachmentData.raw_data | def raw_data(self, value):
"""Set the base64 encoded data using a raw value or file object."""
if value:
try:
value = value.read()
except AttributeError:
pass
b64 = base64.b64encode(value.encode('utf-8'))
self.data = b64.decode('utf-8') | python | def raw_data(self, value):
"""Set the base64 encoded data using a raw value or file object."""
if value:
try:
value = value.read()
except AttributeError:
pass
b64 = base64.b64encode(value.encode('utf-8'))
self.data = b64.decode('utf-8') | [
"def",
"raw_data",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"try",
":",
"value",
"=",
"value",
".",
"read",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"b64",
"=",
"base64",
".",
"b64encode",
"(",
"value",
".",
"encode",
"(",
... | Set the base64 encoded data using a raw value or file object. | [
"Set",
"the",
"base64",
"encoded",
"data",
"using",
"a",
"raw",
"value",
"or",
"file",
"object",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/models/attachment_data.py#L23-L31 |
Locu/chronology | jia/scheduler/views.py | schedule | def schedule():
"""HTTP endpoint for scheduling tasks
If a task with the same code already exists, the one with the shorter
interval will be made active.
"""
code = request.form['code']
interval = int(request.form['interval'])
task_id = binascii.b2a_hex(os.urandom(5))
new_task = Task(id=task_id)
new_task.active = True
new_task.code = code
new_task.interval = interval
# TODO(derek): Assert there is only one other_task
other_task = Task.query.filter_by(code=code, active=True).first()
if other_task:
if other_task.interval <= new_task.interval:
new_task.active = False
else:
other_task.active = False
other_task.save()
current_app.scheduler.cancel(other_task.id)
if new_task.active:
print current_app.scheduler.schedule
current_app.scheduler.schedule({
'id': task_id,
'code': new_task.code,
'interval': new_task.interval
})
new_task.save()
return json.dumps({
'status': 'success',
'id': task_id,
}) | python | def schedule():
"""HTTP endpoint for scheduling tasks
If a task with the same code already exists, the one with the shorter
interval will be made active.
"""
code = request.form['code']
interval = int(request.form['interval'])
task_id = binascii.b2a_hex(os.urandom(5))
new_task = Task(id=task_id)
new_task.active = True
new_task.code = code
new_task.interval = interval
# TODO(derek): Assert there is only one other_task
other_task = Task.query.filter_by(code=code, active=True).first()
if other_task:
if other_task.interval <= new_task.interval:
new_task.active = False
else:
other_task.active = False
other_task.save()
current_app.scheduler.cancel(other_task.id)
if new_task.active:
print current_app.scheduler.schedule
current_app.scheduler.schedule({
'id': task_id,
'code': new_task.code,
'interval': new_task.interval
})
new_task.save()
return json.dumps({
'status': 'success',
'id': task_id,
}) | [
"def",
"schedule",
"(",
")",
":",
"code",
"=",
"request",
".",
"form",
"[",
"'code'",
"]",
"interval",
"=",
"int",
"(",
"request",
".",
"form",
"[",
"'interval'",
"]",
")",
"task_id",
"=",
"binascii",
".",
"b2a_hex",
"(",
"os",
".",
"urandom",
"(",
... | HTTP endpoint for scheduling tasks
If a task with the same code already exists, the one with the shorter
interval will be made active. | [
"HTTP",
"endpoint",
"for",
"scheduling",
"tasks"
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/jia/scheduler/views.py#L18-L57 |
Locu/chronology | jia/scheduler/views.py | cancel | def cancel():
"""HTTP endpoint for canceling tasks
If an active task is cancelled, an inactive task with the same code and the
smallest interval will be activated if it exists.
"""
task_id = request.form['id']
task = Task.query.get(task_id)
if not task:
return json.dumps({
'status': 'success',
'id': None,
})
task.delete()
if task.active:
current_app.scheduler.cancel(task_id)
code = task.code
other_task = Task.query.filter_by(code=code).order_by('interval').first()
if other_task:
other_task.active = True
other_task.save()
current_app.scheduler.schedule({
'id': other_task.id,
'code': other_task.code,
'interval': other_task.interval
})
return json.dumps({
'status': 'success',
'id': task_id,
}) | python | def cancel():
"""HTTP endpoint for canceling tasks
If an active task is cancelled, an inactive task with the same code and the
smallest interval will be activated if it exists.
"""
task_id = request.form['id']
task = Task.query.get(task_id)
if not task:
return json.dumps({
'status': 'success',
'id': None,
})
task.delete()
if task.active:
current_app.scheduler.cancel(task_id)
code = task.code
other_task = Task.query.filter_by(code=code).order_by('interval').first()
if other_task:
other_task.active = True
other_task.save()
current_app.scheduler.schedule({
'id': other_task.id,
'code': other_task.code,
'interval': other_task.interval
})
return json.dumps({
'status': 'success',
'id': task_id,
}) | [
"def",
"cancel",
"(",
")",
":",
"task_id",
"=",
"request",
".",
"form",
"[",
"'id'",
"]",
"task",
"=",
"Task",
".",
"query",
".",
"get",
"(",
"task_id",
")",
"if",
"not",
"task",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'status'",
":",
"'s... | HTTP endpoint for canceling tasks
If an active task is cancelled, an inactive task with the same code and the
smallest interval will be activated if it exists. | [
"HTTP",
"endpoint",
"for",
"canceling",
"tasks"
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/jia/scheduler/views.py#L62-L96 |
uberVU/mongo-oplogreplay | oplogreplay/oplogreplayer.py | OplogReplayer.insert | def insert(self, ns, docid, raw, **kw):
""" Perform a single insert operation.
{'docid': ObjectId('4e95ae77a20e6164850761cd'),
'ns': u'mydb.tweets',
'raw': {u'h': -1469300750073380169L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectId('4e95ae77a20e6164850761cd'),
u'content': u'Lorem ipsum',
u'nr': 16},
u'op': u'i',
u'ts': Timestamp(1318432375, 1)}}
"""
try:
self._dest_coll(ns).insert(raw['o'], safe=True)
except DuplicateKeyError, e:
logging.warning(e) | python | def insert(self, ns, docid, raw, **kw):
""" Perform a single insert operation.
{'docid': ObjectId('4e95ae77a20e6164850761cd'),
'ns': u'mydb.tweets',
'raw': {u'h': -1469300750073380169L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectId('4e95ae77a20e6164850761cd'),
u'content': u'Lorem ipsum',
u'nr': 16},
u'op': u'i',
u'ts': Timestamp(1318432375, 1)}}
"""
try:
self._dest_coll(ns).insert(raw['o'], safe=True)
except DuplicateKeyError, e:
logging.warning(e) | [
"def",
"insert",
"(",
"self",
",",
"ns",
",",
"docid",
",",
"raw",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"self",
".",
"_dest_coll",
"(",
"ns",
")",
".",
"insert",
"(",
"raw",
"[",
"'o'",
"]",
",",
"safe",
"=",
"True",
")",
"except",
"Dup... | Perform a single insert operation.
{'docid': ObjectId('4e95ae77a20e6164850761cd'),
'ns': u'mydb.tweets',
'raw': {u'h': -1469300750073380169L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectId('4e95ae77a20e6164850761cd'),
u'content': u'Lorem ipsum',
u'nr': 16},
u'op': u'i',
u'ts': Timestamp(1318432375, 1)}} | [
"Perform",
"a",
"single",
"insert",
"operation",
"."
] | train | https://github.com/uberVU/mongo-oplogreplay/blob/c1998663f3ccb93c778a7fe5baaf94884251cdc2/oplogreplay/oplogreplayer.py#L134-L150 |
uberVU/mongo-oplogreplay | oplogreplay/oplogreplayer.py | OplogReplayer.update | def update(self, ns, docid, raw, **kw):
""" Perform a single update operation.
{'docid': ObjectId('4e95ae3616692111bb000001'),
'ns': u'mydb.tweets',
'raw': {u'h': -5295451122737468990L,
u'ns': u'mydb.tweets',
u'o': {u'$set': {u'content': u'Lorem ipsum'}},
u'o2': {u'_id': ObjectId('4e95ae3616692111bb000001')},
u'op': u'u',
u'ts': Timestamp(1318432339, 1)}}
"""
self._dest_coll(ns).update(raw['o2'], raw['o'], safe=True) | python | def update(self, ns, docid, raw, **kw):
""" Perform a single update operation.
{'docid': ObjectId('4e95ae3616692111bb000001'),
'ns': u'mydb.tweets',
'raw': {u'h': -5295451122737468990L,
u'ns': u'mydb.tweets',
u'o': {u'$set': {u'content': u'Lorem ipsum'}},
u'o2': {u'_id': ObjectId('4e95ae3616692111bb000001')},
u'op': u'u',
u'ts': Timestamp(1318432339, 1)}}
"""
self._dest_coll(ns).update(raw['o2'], raw['o'], safe=True) | [
"def",
"update",
"(",
"self",
",",
"ns",
",",
"docid",
",",
"raw",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_dest_coll",
"(",
"ns",
")",
".",
"update",
"(",
"raw",
"[",
"'o2'",
"]",
",",
"raw",
"[",
"'o'",
"]",
",",
"safe",
"=",
"True",
... | Perform a single update operation.
{'docid': ObjectId('4e95ae3616692111bb000001'),
'ns': u'mydb.tweets',
'raw': {u'h': -5295451122737468990L,
u'ns': u'mydb.tweets',
u'o': {u'$set': {u'content': u'Lorem ipsum'}},
u'o2': {u'_id': ObjectId('4e95ae3616692111bb000001')},
u'op': u'u',
u'ts': Timestamp(1318432339, 1)}} | [
"Perform",
"a",
"single",
"update",
"operation",
"."
] | train | https://github.com/uberVU/mongo-oplogreplay/blob/c1998663f3ccb93c778a7fe5baaf94884251cdc2/oplogreplay/oplogreplayer.py#L152-L164 |
uberVU/mongo-oplogreplay | oplogreplay/oplogreplayer.py | OplogReplayer.delete | def delete(self, ns, docid, raw, **kw):
""" Perform a single delete operation.
{'docid': ObjectId('4e959ea11669210edc002902'),
'ns': u'mydb.tweets',
'raw': {u'b': True,
u'h': -8347418295715732480L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectId('4e959ea11669210edc002902')},
u'op': u'd',
u'ts': Timestamp(1318432261, 10499)}}
"""
self._dest_coll(ns).remove(raw['o'], safe=True) | python | def delete(self, ns, docid, raw, **kw):
""" Perform a single delete operation.
{'docid': ObjectId('4e959ea11669210edc002902'),
'ns': u'mydb.tweets',
'raw': {u'b': True,
u'h': -8347418295715732480L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectId('4e959ea11669210edc002902')},
u'op': u'd',
u'ts': Timestamp(1318432261, 10499)}}
"""
self._dest_coll(ns).remove(raw['o'], safe=True) | [
"def",
"delete",
"(",
"self",
",",
"ns",
",",
"docid",
",",
"raw",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_dest_coll",
"(",
"ns",
")",
".",
"remove",
"(",
"raw",
"[",
"'o'",
"]",
",",
"safe",
"=",
"True",
")"
] | Perform a single delete operation.
{'docid': ObjectId('4e959ea11669210edc002902'),
'ns': u'mydb.tweets',
'raw': {u'b': True,
u'h': -8347418295715732480L,
u'ns': u'mydb.tweets',
u'o': {u'_id': ObjectId('4e959ea11669210edc002902')},
u'op': u'd',
u'ts': Timestamp(1318432261, 10499)}} | [
"Perform",
"a",
"single",
"delete",
"operation",
"."
] | train | https://github.com/uberVU/mongo-oplogreplay/blob/c1998663f3ccb93c778a7fe5baaf94884251cdc2/oplogreplay/oplogreplayer.py#L166-L178 |
uberVU/mongo-oplogreplay | oplogreplay/oplogreplayer.py | OplogReplayer.drop_index | def drop_index(self, raw):
""" Executes a drop index command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "dropIndexes" : "testcoll",
"index" : "nuie_1" } }
"""
dbname = raw['ns'].split('.', 1)[0]
collname = raw['o']['dropIndexes']
self.dest[dbname][collname].drop_index(raw['o']['index']) | python | def drop_index(self, raw):
""" Executes a drop index command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "dropIndexes" : "testcoll",
"index" : "nuie_1" } }
"""
dbname = raw['ns'].split('.', 1)[0]
collname = raw['o']['dropIndexes']
self.dest[dbname][collname].drop_index(raw['o']['index']) | [
"def",
"drop_index",
"(",
"self",
",",
"raw",
")",
":",
"dbname",
"=",
"raw",
"[",
"'ns'",
"]",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"collname",
"=",
"raw",
"[",
"'o'",
"]",
"[",
"'dropIndexes'",
"]",
"self",
".",
"dest",
"["... | Executes a drop index command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "dropIndexes" : "testcoll",
"index" : "nuie_1" } } | [
"Executes",
"a",
"drop",
"index",
"command",
"."
] | train | https://github.com/uberVU/mongo-oplogreplay/blob/c1998663f3ccb93c778a7fe5baaf94884251cdc2/oplogreplay/oplogreplayer.py#L180-L190 |
uberVU/mongo-oplogreplay | oplogreplay/oplogreplayer.py | OplogReplayer.command | def command(self, ns, raw, **kw):
""" Executes command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "drop" : "fs.files"}
}
"""
try:
dbname = raw['ns'].split('.', 1)[0]
self.dest[dbname].command(raw['o'], check=True)
except OperationFailure, e:
logging.warning(e) | python | def command(self, ns, raw, **kw):
""" Executes command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "drop" : "fs.files"}
}
"""
try:
dbname = raw['ns'].split('.', 1)[0]
self.dest[dbname].command(raw['o'], check=True)
except OperationFailure, e:
logging.warning(e) | [
"def",
"command",
"(",
"self",
",",
"ns",
",",
"raw",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"dbname",
"=",
"raw",
"[",
"'ns'",
"]",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"self",
".",
"dest",
"[",
"dbname",
"]",
".",
... | Executes command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "drop" : "fs.files"}
} | [
"Executes",
"command",
"."
] | train | https://github.com/uberVU/mongo-oplogreplay/blob/c1998663f3ccb93c778a7fe5baaf94884251cdc2/oplogreplay/oplogreplayer.py#L192-L204 |
LasLabs/python-helpscout | helpscout/apis/mailboxes.py | Mailboxes.get_folders | def get_folders(cls, session, mailbox_or_id):
"""List the folders for the mailbox.
Args:
mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID
of the mailbox to get the folders for.
Returns:
RequestPaginator(output_type=helpscout.models.Folder): Folders
iterator.
"""
if isinstance(mailbox_or_id, Mailbox):
mailbox_or_id = mailbox_or_id.id
return cls(
'/mailboxes/%d/folders.json' % mailbox_or_id,
session=session,
out_type=Folder,
) | python | def get_folders(cls, session, mailbox_or_id):
"""List the folders for the mailbox.
Args:
mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID
of the mailbox to get the folders for.
Returns:
RequestPaginator(output_type=helpscout.models.Folder): Folders
iterator.
"""
if isinstance(mailbox_or_id, Mailbox):
mailbox_or_id = mailbox_or_id.id
return cls(
'/mailboxes/%d/folders.json' % mailbox_or_id,
session=session,
out_type=Folder,
) | [
"def",
"get_folders",
"(",
"cls",
",",
"session",
",",
"mailbox_or_id",
")",
":",
"if",
"isinstance",
"(",
"mailbox_or_id",
",",
"Mailbox",
")",
":",
"mailbox_or_id",
"=",
"mailbox_or_id",
".",
"id",
"return",
"cls",
"(",
"'/mailboxes/%d/folders.json'",
"%",
"... | List the folders for the mailbox.
Args:
mailbox_or_id (helpscout.models.Mailbox or int): Mailbox or the ID
of the mailbox to get the folders for.
Returns:
RequestPaginator(output_type=helpscout.models.Folder): Folders
iterator. | [
"List",
"the",
"folders",
"for",
"the",
"mailbox",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/apis/mailboxes.py#L45-L62 |
MakersF/LoLScraper | lol_scraper/summoners_api.py | _slice | def _slice(start, stop, step):
"""
Generate pairs so that you can slice from start to stop, step elements at a time
:param start: The start of the generated series
:param stop: The last of the generated series
:param step: The difference between the first element of the returned pair and the second
:return: A pair that you can use to slice
"""
if step == 0:
raise ValueError("slice() arg 3 must not be zero")
if start==stop:
raise StopIteration
previous = start
next = start + step
while next < stop:
yield previous, next
previous += step
next += step
yield previous, stop | python | def _slice(start, stop, step):
"""
Generate pairs so that you can slice from start to stop, step elements at a time
:param start: The start of the generated series
:param stop: The last of the generated series
:param step: The difference between the first element of the returned pair and the second
:return: A pair that you can use to slice
"""
if step == 0:
raise ValueError("slice() arg 3 must not be zero")
if start==stop:
raise StopIteration
previous = start
next = start + step
while next < stop:
yield previous, next
previous += step
next += step
yield previous, stop | [
"def",
"_slice",
"(",
"start",
",",
"stop",
",",
"step",
")",
":",
"if",
"step",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"slice() arg 3 must not be zero\"",
")",
"if",
"start",
"==",
"stop",
":",
"raise",
"StopIteration",
"previous",
"=",
"start",
"n... | Generate pairs so that you can slice from start to stop, step elements at a time
:param start: The start of the generated series
:param stop: The last of the generated series
:param step: The difference between the first element of the returned pair and the second
:return: A pair that you can use to slice | [
"Generate",
"pairs",
"so",
"that",
"you",
"can",
"slice",
"from",
"start",
"to",
"stop",
"step",
"elements",
"at",
"a",
"time",
":",
"param",
"start",
":",
"The",
"start",
"of",
"the",
"generated",
"series",
":",
"param",
"stop",
":",
"The",
"last",
"o... | train | https://github.com/MakersF/LoLScraper/blob/71d9f2ef24159f2ba5d21467aac1ab785c2bb7e6/lol_scraper/summoners_api.py#L8-L27 |
MakersF/LoLScraper | lol_scraper/summoners_api.py | leagues_by_summoner_ids | def leagues_by_summoner_ids(summoner_ids, queue=Queue.RANKED_SOLO_5x5):
"""
Takes in a list of players ids and divide them by league tiers.
:param summoner_ids: a list containing the ids of players
:param queue: the queue to consider
:return: a dictionary tier -> set of ids
"""
summoners_league = defaultdict(set)
for start, end in _slice(0, len(summoner_ids), 10):
for id, leagues in get_league_entries_by_summoner(summoner_ids[start:end]).items():
for league in leagues:
if Queue[league.queue]==queue:
summoners_league[Tier.parse(league.tier)].add(int(id))
return summoners_league | python | def leagues_by_summoner_ids(summoner_ids, queue=Queue.RANKED_SOLO_5x5):
"""
Takes in a list of players ids and divide them by league tiers.
:param summoner_ids: a list containing the ids of players
:param queue: the queue to consider
:return: a dictionary tier -> set of ids
"""
summoners_league = defaultdict(set)
for start, end in _slice(0, len(summoner_ids), 10):
for id, leagues in get_league_entries_by_summoner(summoner_ids[start:end]).items():
for league in leagues:
if Queue[league.queue]==queue:
summoners_league[Tier.parse(league.tier)].add(int(id))
return summoners_league | [
"def",
"leagues_by_summoner_ids",
"(",
"summoner_ids",
",",
"queue",
"=",
"Queue",
".",
"RANKED_SOLO_5x5",
")",
":",
"summoners_league",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"start",
",",
"end",
"in",
"_slice",
"(",
"0",
",",
"len",
"(",
"summoner_ids... | Takes in a list of players ids and divide them by league tiers.
:param summoner_ids: a list containing the ids of players
:param queue: the queue to consider
:return: a dictionary tier -> set of ids | [
"Takes",
"in",
"a",
"list",
"of",
"players",
"ids",
"and",
"divide",
"them",
"by",
"league",
"tiers",
".",
":",
"param",
"summoner_ids",
":",
"a",
"list",
"containing",
"the",
"ids",
"of",
"players",
":",
"param",
"queue",
":",
"the",
"queue",
"to",
"c... | train | https://github.com/MakersF/LoLScraper/blob/71d9f2ef24159f2ba5d21467aac1ab785c2bb7e6/lol_scraper/summoners_api.py#L29-L42 |
MakersF/LoLScraper | lol_scraper/summoners_api.py | get_tier_from_participants | def get_tier_from_participants(participantsIdentities, minimum_tier=Tier.bronze, queue=Queue.RANKED_SOLO_5x5):
"""
Returns the tier of the lowest tier and the participantsIDs divided by tier
player in the match
:param participantsIdentities: the match participants
:param minimum_tier: the minimum tier that a participant must be in order to be added
:param queue: the queue over which the tier of the player is considered
:return: the tier of the lowest tier player in the match
"""
leagues = leagues_by_summoner_ids([p.player.summonerId for p in participantsIdentities], queue)
match_tier = max(leagues.keys(), key=operator.attrgetter('value'))
return match_tier, {league: ids for league, ids in leagues.items() if league.is_better_or_equal(minimum_tier)} | python | def get_tier_from_participants(participantsIdentities, minimum_tier=Tier.bronze, queue=Queue.RANKED_SOLO_5x5):
"""
Returns the tier of the lowest tier and the participantsIDs divided by tier
player in the match
:param participantsIdentities: the match participants
:param minimum_tier: the minimum tier that a participant must be in order to be added
:param queue: the queue over which the tier of the player is considered
:return: the tier of the lowest tier player in the match
"""
leagues = leagues_by_summoner_ids([p.player.summonerId for p in participantsIdentities], queue)
match_tier = max(leagues.keys(), key=operator.attrgetter('value'))
return match_tier, {league: ids for league, ids in leagues.items() if league.is_better_or_equal(minimum_tier)} | [
"def",
"get_tier_from_participants",
"(",
"participantsIdentities",
",",
"minimum_tier",
"=",
"Tier",
".",
"bronze",
",",
"queue",
"=",
"Queue",
".",
"RANKED_SOLO_5x5",
")",
":",
"leagues",
"=",
"leagues_by_summoner_ids",
"(",
"[",
"p",
".",
"player",
".",
"summ... | Returns the tier of the lowest tier and the participantsIDs divided by tier
player in the match
:param participantsIdentities: the match participants
:param minimum_tier: the minimum tier that a participant must be in order to be added
:param queue: the queue over which the tier of the player is considered
:return: the tier of the lowest tier player in the match | [
"Returns",
"the",
"tier",
"of",
"the",
"lowest",
"tier",
"and",
"the",
"participantsIDs",
"divided",
"by",
"tier",
"player",
"in",
"the",
"match",
":",
"param",
"participantsIdentities",
":",
"the",
"match",
"participants",
":",
"param",
"minimum_tier",
":",
"... | train | https://github.com/MakersF/LoLScraper/blob/71d9f2ef24159f2ba5d21467aac1ab785c2bb7e6/lol_scraper/summoners_api.py#L44-L55 |
MakersF/LoLScraper | lol_scraper/summoners_api.py | summoner_names_to_id | def summoner_names_to_id(summoners):
"""
Gets a list of summoners names and return a dictionary mapping the player name to his/her summoner id
:param summoners: a list of player names
:return: a dictionary name -> id
"""
ids = {}
for start, end in _slice(0, len(summoners), 40):
result = get_summoners_by_name(summoners[start:end])
for name, summoner in result.items():
ids[name] = summoner.id
return ids | python | def summoner_names_to_id(summoners):
"""
Gets a list of summoners names and return a dictionary mapping the player name to his/her summoner id
:param summoners: a list of player names
:return: a dictionary name -> id
"""
ids = {}
for start, end in _slice(0, len(summoners), 40):
result = get_summoners_by_name(summoners[start:end])
for name, summoner in result.items():
ids[name] = summoner.id
return ids | [
"def",
"summoner_names_to_id",
"(",
"summoners",
")",
":",
"ids",
"=",
"{",
"}",
"for",
"start",
",",
"end",
"in",
"_slice",
"(",
"0",
",",
"len",
"(",
"summoners",
")",
",",
"40",
")",
":",
"result",
"=",
"get_summoners_by_name",
"(",
"summoners",
"["... | Gets a list of summoners names and return a dictionary mapping the player name to his/her summoner id
:param summoners: a list of player names
:return: a dictionary name -> id | [
"Gets",
"a",
"list",
"of",
"summoners",
"names",
"and",
"return",
"a",
"dictionary",
"mapping",
"the",
"player",
"name",
"to",
"his",
"/",
"her",
"summoner",
"id",
":",
"param",
"summoners",
":",
"a",
"list",
"of",
"player",
"names",
":",
"return",
":",
... | train | https://github.com/MakersF/LoLScraper/blob/71d9f2ef24159f2ba5d21467aac1ab785c2bb7e6/lol_scraper/summoners_api.py#L57-L68 |
Locu/chronology | jia/jia/models.py | Board.json | def json(self):
"""A JSON-encoded description of this board.
Format:
{'id': board_id,
'title': 'The title of the board',
'panels': [{
'title': 'The title of the panel'
'data_source': {
'source_type': PanelSource.TYPE,
'refresh_seconds': 600,
...source_specific_details...
},
'display': {
'display_type': PanelDisplay.TYPE,
...display_specific_details...
}, ...]}
"""
if self.board_data:
board_dict = json.loads(self.board_data)
board_dict['id'] = self.id
del board_dict['__version__']
else:
board_dict = {
'id': self.id,
'title': '',
'panels': []
}
return board_dict
""" pycode = self.pycodes.first() or PyCode()
return {'id': self.id,
'pycode': pycode.json()}
""" | python | def json(self):
"""A JSON-encoded description of this board.
Format:
{'id': board_id,
'title': 'The title of the board',
'panels': [{
'title': 'The title of the panel'
'data_source': {
'source_type': PanelSource.TYPE,
'refresh_seconds': 600,
...source_specific_details...
},
'display': {
'display_type': PanelDisplay.TYPE,
...display_specific_details...
}, ...]}
"""
if self.board_data:
board_dict = json.loads(self.board_data)
board_dict['id'] = self.id
del board_dict['__version__']
else:
board_dict = {
'id': self.id,
'title': '',
'panels': []
}
return board_dict
""" pycode = self.pycodes.first() or PyCode()
return {'id': self.id,
'pycode': pycode.json()}
""" | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"self",
".",
"board_data",
":",
"board_dict",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"board_data",
")",
"board_dict",
"[",
"'id'",
"]",
"=",
"self",
".",
"id",
"del",
"board_dict",
"[",
"'__version__'",... | A JSON-encoded description of this board.
Format:
{'id': board_id,
'title': 'The title of the board',
'panels': [{
'title': 'The title of the panel'
'data_source': {
'source_type': PanelSource.TYPE,
'refresh_seconds': 600,
...source_specific_details...
},
'display': {
'display_type': PanelDisplay.TYPE,
...display_specific_details...
}, ...]} | [
"A",
"JSON",
"-",
"encoded",
"description",
"of",
"this",
"board",
"."
] | train | https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/jia/jia/models.py#L68-L100 |
Knoema/knoema-python-driver | knoema/__init__.py | get | def get(dataset = None, include_metadata = False, mnemonics = None, **dim_values):
"""Use this function to get data from Knoema dataset."""
if not dataset and not mnemonics:
raise ValueError('Dataset id is not specified')
if mnemonics and dim_values:
raise ValueError('The function does not support specifying mnemonics and selection in a single call')
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
ds = client.get_dataset(dataset) if dataset else None
reader = MnemonicsDataReader(client, mnemonics) if mnemonics else StreamingDataReader(client, dim_values) if ds.type == 'Regular' else PivotDataReader(client, dim_values)
reader.include_metadata = include_metadata
reader.dataset = ds
return reader.get_pandasframe() | python | def get(dataset = None, include_metadata = False, mnemonics = None, **dim_values):
"""Use this function to get data from Knoema dataset."""
if not dataset and not mnemonics:
raise ValueError('Dataset id is not specified')
if mnemonics and dim_values:
raise ValueError('The function does not support specifying mnemonics and selection in a single call')
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
ds = client.get_dataset(dataset) if dataset else None
reader = MnemonicsDataReader(client, mnemonics) if mnemonics else StreamingDataReader(client, dim_values) if ds.type == 'Regular' else PivotDataReader(client, dim_values)
reader.include_metadata = include_metadata
reader.dataset = ds
return reader.get_pandasframe() | [
"def",
"get",
"(",
"dataset",
"=",
"None",
",",
"include_metadata",
"=",
"False",
",",
"mnemonics",
"=",
"None",
",",
"*",
"*",
"dim_values",
")",
":",
"if",
"not",
"dataset",
"and",
"not",
"mnemonics",
":",
"raise",
"ValueError",
"(",
"'Dataset id is not ... | Use this function to get data from Knoema dataset. | [
"Use",
"this",
"function",
"to",
"get",
"data",
"from",
"Knoema",
"dataset",
"."
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/__init__.py#L7-L25 |
Knoema/knoema-python-driver | knoema/__init__.py | upload | def upload(file_path, dataset=None, public=False):
"""Use this function to upload data to Knoema dataset."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
return client.upload(file_path, dataset, public) | python | def upload(file_path, dataset=None, public=False):
"""Use this function to upload data to Knoema dataset."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
return client.upload(file_path, dataset, public) | [
"def",
"upload",
"(",
"file_path",
",",
"dataset",
"=",
"None",
",",
"public",
"=",
"False",
")",
":",
"config",
"=",
"ApiConfig",
"(",
")",
"client",
"=",
"ApiClient",
"(",
"config",
".",
"host",
",",
"config",
".",
"app_id",
",",
"config",
".",
"ap... | Use this function to upload data to Knoema dataset. | [
"Use",
"this",
"function",
"to",
"upload",
"data",
"to",
"Knoema",
"dataset",
"."
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/__init__.py#L27-L32 |
Knoema/knoema-python-driver | knoema/__init__.py | delete | def delete(dataset):
"""Use this function to delete dataset by it's id."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.delete(dataset)
return ('Dataset {} has been deleted successfully'.format(dataset)) | python | def delete(dataset):
"""Use this function to delete dataset by it's id."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.delete(dataset)
return ('Dataset {} has been deleted successfully'.format(dataset)) | [
"def",
"delete",
"(",
"dataset",
")",
":",
"config",
"=",
"ApiConfig",
"(",
")",
"client",
"=",
"ApiClient",
"(",
"config",
".",
"host",
",",
"config",
".",
"app_id",
",",
"config",
".",
"app_secret",
")",
"client",
".",
"check_correct_host",
"(",
")",
... | Use this function to delete dataset by it's id. | [
"Use",
"this",
"function",
"to",
"delete",
"dataset",
"by",
"it",
"s",
"id",
"."
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/__init__.py#L34-L41 |
Knoema/knoema-python-driver | knoema/__init__.py | verify | def verify(dataset, publication_date, source, refernce_url):
"""Use this function to verify a dataset."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.verify(dataset, publication_date, source, refernce_url) | python | def verify(dataset, publication_date, source, refernce_url):
"""Use this function to verify a dataset."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.verify(dataset, publication_date, source, refernce_url) | [
"def",
"verify",
"(",
"dataset",
",",
"publication_date",
",",
"source",
",",
"refernce_url",
")",
":",
"config",
"=",
"ApiConfig",
"(",
")",
"client",
"=",
"ApiClient",
"(",
"config",
".",
"host",
",",
"config",
".",
"app_id",
",",
"config",
".",
"app_s... | Use this function to verify a dataset. | [
"Use",
"this",
"function",
"to",
"verify",
"a",
"dataset",
"."
] | train | https://github.com/Knoema/knoema-python-driver/blob/e98b13db3e4df51c208c272e2977bfbe4c6e5532/knoema/__init__.py#L43-L49 |
uberVU/mongo-oplogreplay | oplogreplay/oplogwatcher.py | OplogWatcher.start | def start(self):
""" Starts the OplogWatcher. """
oplog = self.connection.local['oplog.rs']
if self.ts is None:
cursor = oplog.find().sort('$natural', -1)
obj = cursor[0]
if obj:
self.ts = obj['ts']
else:
# In case no oplogs are present.
self.ts = None
if self.ts:
logging.info('Watching oplogs with timestamp > %s' % self.ts)
else:
logging.info('Watching all oplogs')
while self.running:
query = { 'ts': {'$gt': self.ts} }
try:
logging.debug('Tailing over %r...' % query)
cursor = oplog.find(query, tailable=True)
# OplogReplay flag greatly improves scanning for ts performance.
cursor.add_option(pymongo.cursor._QUERY_OPTIONS['oplog_replay'])
while self.running:
for op in cursor:
self.process_op(op['ns'], op)
time.sleep(self.poll_time)
if not cursor.alive:
break
except AutoReconnect, e:
logging.warning(e)
time.sleep(self.poll_time)
except OperationFailure, e:
logging.exception(e)
time.sleep(self.poll_time) | python | def start(self):
""" Starts the OplogWatcher. """
oplog = self.connection.local['oplog.rs']
if self.ts is None:
cursor = oplog.find().sort('$natural', -1)
obj = cursor[0]
if obj:
self.ts = obj['ts']
else:
# In case no oplogs are present.
self.ts = None
if self.ts:
logging.info('Watching oplogs with timestamp > %s' % self.ts)
else:
logging.info('Watching all oplogs')
while self.running:
query = { 'ts': {'$gt': self.ts} }
try:
logging.debug('Tailing over %r...' % query)
cursor = oplog.find(query, tailable=True)
# OplogReplay flag greatly improves scanning for ts performance.
cursor.add_option(pymongo.cursor._QUERY_OPTIONS['oplog_replay'])
while self.running:
for op in cursor:
self.process_op(op['ns'], op)
time.sleep(self.poll_time)
if not cursor.alive:
break
except AutoReconnect, e:
logging.warning(e)
time.sleep(self.poll_time)
except OperationFailure, e:
logging.exception(e)
time.sleep(self.poll_time) | [
"def",
"start",
"(",
"self",
")",
":",
"oplog",
"=",
"self",
".",
"connection",
".",
"local",
"[",
"'oplog.rs'",
"]",
"if",
"self",
".",
"ts",
"is",
"None",
":",
"cursor",
"=",
"oplog",
".",
"find",
"(",
")",
".",
"sort",
"(",
"'$natural'",
",",
... | Starts the OplogWatcher. | [
"Starts",
"the",
"OplogWatcher",
"."
] | train | https://github.com/uberVU/mongo-oplogreplay/blob/c1998663f3ccb93c778a7fe5baaf94884251cdc2/oplogreplay/oplogwatcher.py#L38-L76 |
uberVU/mongo-oplogreplay | oplogreplay/oplogwatcher.py | OplogWatcher.process_op | def process_op(self, ns, raw):
""" Processes a single operation from the oplog.
Performs a switch by raw['op']:
"i" insert
"u" update
"d" delete
"c" db cmd
"db" declares presence of a database
"n" no op
"""
# Compute the document id of the document that will be altered
# (in case of insert, update or delete).
docid = self.__get_id(raw)
op = raw['op']
if op == 'i':
self.insert(ns=ns, docid=docid, raw=raw)
elif op == 'u':
self.update(ns=ns, docid=docid, raw=raw)
elif op == 'd':
self.delete(ns=ns, docid=docid, raw=raw)
elif op == 'c':
self.command(ns=ns, raw=raw)
elif op == 'db':
self.db_declare(ns=ns, raw=raw)
elif op == 'n':
self.noop()
else:
logging.error("Unknown op: %r" % op)
# Save timestamp of last processed oplog.
self.ts = raw['ts'] | python | def process_op(self, ns, raw):
""" Processes a single operation from the oplog.
Performs a switch by raw['op']:
"i" insert
"u" update
"d" delete
"c" db cmd
"db" declares presence of a database
"n" no op
"""
# Compute the document id of the document that will be altered
# (in case of insert, update or delete).
docid = self.__get_id(raw)
op = raw['op']
if op == 'i':
self.insert(ns=ns, docid=docid, raw=raw)
elif op == 'u':
self.update(ns=ns, docid=docid, raw=raw)
elif op == 'd':
self.delete(ns=ns, docid=docid, raw=raw)
elif op == 'c':
self.command(ns=ns, raw=raw)
elif op == 'db':
self.db_declare(ns=ns, raw=raw)
elif op == 'n':
self.noop()
else:
logging.error("Unknown op: %r" % op)
# Save timestamp of last processed oplog.
self.ts = raw['ts'] | [
"def",
"process_op",
"(",
"self",
",",
"ns",
",",
"raw",
")",
":",
"# Compute the document id of the document that will be altered",
"# (in case of insert, update or delete).",
"docid",
"=",
"self",
".",
"__get_id",
"(",
"raw",
")",
"op",
"=",
"raw",
"[",
"'op'",
"]... | Processes a single operation from the oplog.
Performs a switch by raw['op']:
"i" insert
"u" update
"d" delete
"c" db cmd
"db" declares presence of a database
"n" no op | [
"Processes",
"a",
"single",
"operation",
"from",
"the",
"oplog",
"."
] | train | https://github.com/uberVU/mongo-oplogreplay/blob/c1998663f3ccb93c778a7fe5baaf94884251cdc2/oplogreplay/oplogwatcher.py#L81-L113 |
timdiels/pytil | pytil/algorithms.py | multi_way_partitioning | def multi_way_partitioning(items, bin_count): #TODO rename bin_count -> bins
'''
Greedily divide weighted items equally across bins.
This approximately solves a multi-way partition problem, minimising the
difference between the largest and smallest sum of weights in a bin.
Parameters
----------
items : ~typing.Iterable[~typing.Tuple[~typing.Any, float]]
Weighted items as ``(item, weight)`` tuples.
bin_count : int
Number of bins.
Returns
-------
bins : ~collections_extended.frozenbag[~collections_extended.frozenbag[~typing.Any]]
Item bins as a bag of item bags.
Notes
----------
- `A greedy solution <http://stackoverflow.com/a/6855546/1031434>`_
- `Problem definition and solutions <http://ijcai.org/Proceedings/09/Papers/096.pdf>`_
'''
bins = [_Bin() for _ in range(bin_count)]
for item, weight in sorted(items, key=lambda x: x[1], reverse=True):
bin_ = min(bins, key=lambda bin_: bin_.weights_sum)
bin_.add(item, weight)
return frozenbag(frozenbag(bin_.items) for bin_ in bins) | python | def multi_way_partitioning(items, bin_count): #TODO rename bin_count -> bins
'''
Greedily divide weighted items equally across bins.
This approximately solves a multi-way partition problem, minimising the
difference between the largest and smallest sum of weights in a bin.
Parameters
----------
items : ~typing.Iterable[~typing.Tuple[~typing.Any, float]]
Weighted items as ``(item, weight)`` tuples.
bin_count : int
Number of bins.
Returns
-------
bins : ~collections_extended.frozenbag[~collections_extended.frozenbag[~typing.Any]]
Item bins as a bag of item bags.
Notes
----------
- `A greedy solution <http://stackoverflow.com/a/6855546/1031434>`_
- `Problem definition and solutions <http://ijcai.org/Proceedings/09/Papers/096.pdf>`_
'''
bins = [_Bin() for _ in range(bin_count)]
for item, weight in sorted(items, key=lambda x: x[1], reverse=True):
bin_ = min(bins, key=lambda bin_: bin_.weights_sum)
bin_.add(item, weight)
return frozenbag(frozenbag(bin_.items) for bin_ in bins) | [
"def",
"multi_way_partitioning",
"(",
"items",
",",
"bin_count",
")",
":",
"#TODO rename bin_count -> bins",
"bins",
"=",
"[",
"_Bin",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"bin_count",
")",
"]",
"for",
"item",
",",
"weight",
"in",
"sorted",
"(",
"item... | Greedily divide weighted items equally across bins.
This approximately solves a multi-way partition problem, minimising the
difference between the largest and smallest sum of weights in a bin.
Parameters
----------
items : ~typing.Iterable[~typing.Tuple[~typing.Any, float]]
Weighted items as ``(item, weight)`` tuples.
bin_count : int
Number of bins.
Returns
-------
bins : ~collections_extended.frozenbag[~collections_extended.frozenbag[~typing.Any]]
Item bins as a bag of item bags.
Notes
----------
- `A greedy solution <http://stackoverflow.com/a/6855546/1031434>`_
- `Problem definition and solutions <http://ijcai.org/Proceedings/09/Papers/096.pdf>`_ | [
"Greedily",
"divide",
"weighted",
"items",
"equally",
"across",
"bins",
"."
] | train | https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/algorithms.py#L43-L71 |
timdiels/pytil | pytil/algorithms.py | toset_from_tosets | def toset_from_tosets(*tosets): # Note: a setlist is perfect representation of a toset as it's totally ordered and it's a set, i.e. a toset
'''
Create totally ordered set (toset) from tosets.
These tosets, when merged, form a partially ordered set. The linear
extension of this poset, a toset, is returned.
.. warning:: untested
Parameters
----------
tosets : Iterable[~collections_extended.setlist]
Tosets to merge.
Raises
------
ValueError
If the tosets (derived from the lists) contradict each other. E.g.
``[a, b]`` and ``[b, c, a]`` contradict each other.
Returns
-------
toset : ~collectiontions_extended.setlist
Totally ordered set.
'''
# Construct directed graph with: a <-- b iff a < b and adjacent in a list
graph = nx.DiGraph()
for toset in tosets:
graph.add_nodes_from(toset)
graph.add_edges_from(windowed(reversed(toset)))
# No cycles allowed
if not nx.is_directed_acyclic_graph(graph): #TODO could rely on NetworkXUnfeasible https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.dag.topological_sort.html
raise ValueError('Given tosets contradict each other') # each cycle is a contradiction, e.g. a > b > c > a
# Topological sort
return setlist(nx.topological_sort(graph, reverse=True)) | python | def toset_from_tosets(*tosets): # Note: a setlist is perfect representation of a toset as it's totally ordered and it's a set, i.e. a toset
'''
Create totally ordered set (toset) from tosets.
These tosets, when merged, form a partially ordered set. The linear
extension of this poset, a toset, is returned.
.. warning:: untested
Parameters
----------
tosets : Iterable[~collections_extended.setlist]
Tosets to merge.
Raises
------
ValueError
If the tosets (derived from the lists) contradict each other. E.g.
``[a, b]`` and ``[b, c, a]`` contradict each other.
Returns
-------
toset : ~collectiontions_extended.setlist
Totally ordered set.
'''
# Construct directed graph with: a <-- b iff a < b and adjacent in a list
graph = nx.DiGraph()
for toset in tosets:
graph.add_nodes_from(toset)
graph.add_edges_from(windowed(reversed(toset)))
# No cycles allowed
if not nx.is_directed_acyclic_graph(graph): #TODO could rely on NetworkXUnfeasible https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.dag.topological_sort.html
raise ValueError('Given tosets contradict each other') # each cycle is a contradiction, e.g. a > b > c > a
# Topological sort
return setlist(nx.topological_sort(graph, reverse=True)) | [
"def",
"toset_from_tosets",
"(",
"*",
"tosets",
")",
":",
"# Note: a setlist is perfect representation of a toset as it's totally ordered and it's a set, i.e. a toset",
"# Construct directed graph with: a <-- b iff a < b and adjacent in a list",
"graph",
"=",
"nx",
".",
"DiGraph",
"(",
... | Create totally ordered set (toset) from tosets.
These tosets, when merged, form a partially ordered set. The linear
extension of this poset, a toset, is returned.
.. warning:: untested
Parameters
----------
tosets : Iterable[~collections_extended.setlist]
Tosets to merge.
Raises
------
ValueError
If the tosets (derived from the lists) contradict each other. E.g.
``[a, b]`` and ``[b, c, a]`` contradict each other.
Returns
-------
toset : ~collectiontions_extended.setlist
Totally ordered set. | [
"Create",
"totally",
"ordered",
"set",
"(",
"toset",
")",
"from",
"tosets",
"."
] | train | https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/algorithms.py#L75-L111 |
ryanvarley/ExoData | exodata/plots.py | _sortValueIntoGroup | def _sortValueIntoGroup(groupKeys, groupLimits, value):
""" returns the Key of the group a value belongs to
:param groupKeys: a list/tuple of keys ie ['1-3', '3-5', '5-8', '8-10', '10+']
:param groupLimits: a list of the limits for the group [1,3,5,8,10,float('inf')] note the first value is an absolute
minimum and the last an absolute maximum. You can therefore use float('inf')
:param value:
:return:
"""
if not len(groupKeys) == len(groupLimits)-1:
raise ValueError('len(groupKeys) must equal len(grouplimits)-1 got \nkeys:{0} \nlimits:{1}'.format(groupKeys,
groupLimits))
if math.isnan(value):
return 'Uncertain'
# TODO add to other if bad value or outside limits
keyIndex = None
if value == groupLimits[0]: # if value is == minimum skip the comparison
keyIndex = 1
elif value == groupLimits[-1]: # if value is == minimum skip the comparison
keyIndex = len(groupLimits)-1
else:
for i, limit in enumerate(groupLimits):
if value < limit:
keyIndex = i
break
if keyIndex == 0: # below the minimum
raise BelowLimitsError('Value {0} below limit {1}'.format(value, groupLimits[0]))
if keyIndex is None:
raise AboveLimitsError('Value {0} above limit {1}'.format(value, groupLimits[-1]))
return groupKeys[keyIndex-1] | python | def _sortValueIntoGroup(groupKeys, groupLimits, value):
""" returns the Key of the group a value belongs to
:param groupKeys: a list/tuple of keys ie ['1-3', '3-5', '5-8', '8-10', '10+']
:param groupLimits: a list of the limits for the group [1,3,5,8,10,float('inf')] note the first value is an absolute
minimum and the last an absolute maximum. You can therefore use float('inf')
:param value:
:return:
"""
if not len(groupKeys) == len(groupLimits)-1:
raise ValueError('len(groupKeys) must equal len(grouplimits)-1 got \nkeys:{0} \nlimits:{1}'.format(groupKeys,
groupLimits))
if math.isnan(value):
return 'Uncertain'
# TODO add to other if bad value or outside limits
keyIndex = None
if value == groupLimits[0]: # if value is == minimum skip the comparison
keyIndex = 1
elif value == groupLimits[-1]: # if value is == minimum skip the comparison
keyIndex = len(groupLimits)-1
else:
for i, limit in enumerate(groupLimits):
if value < limit:
keyIndex = i
break
if keyIndex == 0: # below the minimum
raise BelowLimitsError('Value {0} below limit {1}'.format(value, groupLimits[0]))
if keyIndex is None:
raise AboveLimitsError('Value {0} above limit {1}'.format(value, groupLimits[-1]))
return groupKeys[keyIndex-1] | [
"def",
"_sortValueIntoGroup",
"(",
"groupKeys",
",",
"groupLimits",
",",
"value",
")",
":",
"if",
"not",
"len",
"(",
"groupKeys",
")",
"==",
"len",
"(",
"groupLimits",
")",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'len(groupKeys) must equal len(grouplimits)-1... | returns the Key of the group a value belongs to
:param groupKeys: a list/tuple of keys ie ['1-3', '3-5', '5-8', '8-10', '10+']
:param groupLimits: a list of the limits for the group [1,3,5,8,10,float('inf')] note the first value is an absolute
minimum and the last an absolute maximum. You can therefore use float('inf')
:param value:
:return: | [
"returns",
"the",
"Key",
"of",
"the",
"group",
"a",
"value",
"belongs",
"to",
":",
"param",
"groupKeys",
":",
"a",
"list",
"/",
"tuple",
"of",
"keys",
"ie",
"[",
"1",
"-",
"3",
"3",
"-",
"5",
"5",
"-",
"8",
"8",
"-",
"10",
"10",
"+",
"]",
":"... | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L693-L728 |
ryanvarley/ExoData | exodata/plots.py | _GlobalFigure.set_size | def set_size(self, size):
""" choose a preset size for the plot
:param size: 'small' for documents or 'large' for presentations
"""
if size == 'small':
self._set_size_small()
elif size == 'large':
self._set_size_large()
else:
raise ValueError('Size must be large or small') | python | def set_size(self, size):
""" choose a preset size for the plot
:param size: 'small' for documents or 'large' for presentations
"""
if size == 'small':
self._set_size_small()
elif size == 'large':
self._set_size_large()
else:
raise ValueError('Size must be large or small') | [
"def",
"set_size",
"(",
"self",
",",
"size",
")",
":",
"if",
"size",
"==",
"'small'",
":",
"self",
".",
"_set_size_small",
"(",
")",
"elif",
"size",
"==",
"'large'",
":",
"self",
".",
"_set_size_large",
"(",
")",
"else",
":",
"raise",
"ValueError",
"("... | choose a preset size for the plot
:param size: 'small' for documents or 'large' for presentations | [
"choose",
"a",
"preset",
"size",
"for",
"the",
"plot",
":",
"param",
"size",
":",
"small",
"for",
"documents",
"or",
"large",
"for",
"presentations"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L30-L39 |
ryanvarley/ExoData | exodata/plots.py | _GlobalFigure.set_foregroundcolor | def set_foregroundcolor(self, color):
'''For the specified axes, sets the color of the frame, major ticks,
tick labels, axis labels, title and legend
'''
ax = self.ax
for tl in ax.get_xticklines() + ax.get_yticklines():
tl.set_color(color)
for spine in ax.spines:
ax.spines[spine].set_edgecolor(color)
for tick in ax.xaxis.get_major_ticks():
tick.label1.set_color(color)
for tick in ax.yaxis.get_major_ticks():
tick.label1.set_color(color)
ax.axes.xaxis.label.set_color(color)
ax.axes.yaxis.label.set_color(color)
ax.axes.xaxis.get_offset_text().set_color(color)
ax.axes.yaxis.get_offset_text().set_color(color)
ax.axes.title.set_color(color)
lh = ax.get_legend()
if lh != None:
lh.get_title().set_color(color)
lh.legendPatch.set_edgecolor('none')
labels = lh.get_texts()
for lab in labels:
lab.set_color(color)
for tl in ax.get_xticklabels():
tl.set_color(color)
for tl in ax.get_yticklabels():
tl.set_color(color)
plt.draw() | python | def set_foregroundcolor(self, color):
'''For the specified axes, sets the color of the frame, major ticks,
tick labels, axis labels, title and legend
'''
ax = self.ax
for tl in ax.get_xticklines() + ax.get_yticklines():
tl.set_color(color)
for spine in ax.spines:
ax.spines[spine].set_edgecolor(color)
for tick in ax.xaxis.get_major_ticks():
tick.label1.set_color(color)
for tick in ax.yaxis.get_major_ticks():
tick.label1.set_color(color)
ax.axes.xaxis.label.set_color(color)
ax.axes.yaxis.label.set_color(color)
ax.axes.xaxis.get_offset_text().set_color(color)
ax.axes.yaxis.get_offset_text().set_color(color)
ax.axes.title.set_color(color)
lh = ax.get_legend()
if lh != None:
lh.get_title().set_color(color)
lh.legendPatch.set_edgecolor('none')
labels = lh.get_texts()
for lab in labels:
lab.set_color(color)
for tl in ax.get_xticklabels():
tl.set_color(color)
for tl in ax.get_yticklabels():
tl.set_color(color)
plt.draw() | [
"def",
"set_foregroundcolor",
"(",
"self",
",",
"color",
")",
":",
"ax",
"=",
"self",
".",
"ax",
"for",
"tl",
"in",
"ax",
".",
"get_xticklines",
"(",
")",
"+",
"ax",
".",
"get_yticklines",
"(",
")",
":",
"tl",
".",
"set_color",
"(",
"color",
")",
"... | For the specified axes, sets the color of the frame, major ticks,
tick labels, axis labels, title and legend | [
"For",
"the",
"specified",
"axes",
"sets",
"the",
"color",
"of",
"the",
"frame",
"major",
"ticks",
"tick",
"labels",
"axis",
"labels",
"title",
"and",
"legend"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L76-L107 |
ryanvarley/ExoData | exodata/plots.py | _GlobalFigure.set_backgroundcolor | def set_backgroundcolor(self, color):
'''Sets the background color of the current axes (and legend).
Use 'None' (with quotes) for transparent. To get transparent
background on saved figures, use:
pp.savefig("fig1.svg", transparent=True)
'''
ax = self.ax
ax.patch.set_facecolor(color)
lh = ax.get_legend()
if lh != None:
lh.legendPatch.set_facecolor(color)
plt.draw() | python | def set_backgroundcolor(self, color):
'''Sets the background color of the current axes (and legend).
Use 'None' (with quotes) for transparent. To get transparent
background on saved figures, use:
pp.savefig("fig1.svg", transparent=True)
'''
ax = self.ax
ax.patch.set_facecolor(color)
lh = ax.get_legend()
if lh != None:
lh.legendPatch.set_facecolor(color)
plt.draw() | [
"def",
"set_backgroundcolor",
"(",
"self",
",",
"color",
")",
":",
"ax",
"=",
"self",
".",
"ax",
"ax",
".",
"patch",
".",
"set_facecolor",
"(",
"color",
")",
"lh",
"=",
"ax",
".",
"get_legend",
"(",
")",
"if",
"lh",
"!=",
"None",
":",
"lh",
".",
... | Sets the background color of the current axes (and legend).
Use 'None' (with quotes) for transparent. To get transparent
background on saved figures, use:
pp.savefig("fig1.svg", transparent=True) | [
"Sets",
"the",
"background",
"color",
"of",
"the",
"current",
"axes",
"(",
"and",
"legend",
")",
".",
"Use",
"None",
"(",
"with",
"quotes",
")",
"for",
"transparent",
".",
"To",
"get",
"transparent",
"background",
"on",
"saved",
"figures",
"use",
":",
"p... | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L109-L121 |
ryanvarley/ExoData | exodata/plots.py | _AstroObjectFigs._getParLabelAndUnit | def _getParLabelAndUnit(self, param):
""" checks param to see if it contains a parent link (ie star.) then returns the correct unit and label for the
job from the parDicts
:return:
"""
firstObject = self.objectList[0]
if isinstance(firstObject, ac.Planet):
if 'star.' in param:
return _starPars[param[5:]] # cut off star. part
else:
return _planetPars[param]
elif isinstance(firstObject, ac.Star):
return _starPars[param]
else:
raise TypeError('Only Planets and Star object are currently supported, you gave {0}'.format(type(firstObject))) | python | def _getParLabelAndUnit(self, param):
""" checks param to see if it contains a parent link (ie star.) then returns the correct unit and label for the
job from the parDicts
:return:
"""
firstObject = self.objectList[0]
if isinstance(firstObject, ac.Planet):
if 'star.' in param:
return _starPars[param[5:]] # cut off star. part
else:
return _planetPars[param]
elif isinstance(firstObject, ac.Star):
return _starPars[param]
else:
raise TypeError('Only Planets and Star object are currently supported, you gave {0}'.format(type(firstObject))) | [
"def",
"_getParLabelAndUnit",
"(",
"self",
",",
"param",
")",
":",
"firstObject",
"=",
"self",
".",
"objectList",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"firstObject",
",",
"ac",
".",
"Planet",
")",
":",
"if",
"'star.'",
"in",
"param",
":",
"return",
... | checks param to see if it contains a parent link (ie star.) then returns the correct unit and label for the
job from the parDicts
:return: | [
"checks",
"param",
"to",
"see",
"if",
"it",
"contains",
"a",
"parent",
"link",
"(",
"ie",
"star",
".",
")",
"then",
"returns",
"the",
"correct",
"unit",
"and",
"label",
"for",
"the",
"job",
"from",
"the",
"parDicts",
":",
"return",
":"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L156-L172 |
ryanvarley/ExoData | exodata/plots.py | _BaseDataPerClass._processResults | def _processResults(self):
""" Checks each result can meet SNR requirments, adds to count
:return:
"""
resultsByClass = self._genEmptyResults()
for astroObject in self.objectList:
sortKey = self._getSortKey(astroObject)
resultsByClass[sortKey] += 1
return resultsByClass | python | def _processResults(self):
""" Checks each result can meet SNR requirments, adds to count
:return:
"""
resultsByClass = self._genEmptyResults()
for astroObject in self.objectList:
sortKey = self._getSortKey(astroObject)
resultsByClass[sortKey] += 1
return resultsByClass | [
"def",
"_processResults",
"(",
"self",
")",
":",
"resultsByClass",
"=",
"self",
".",
"_genEmptyResults",
"(",
")",
"for",
"astroObject",
"in",
"self",
".",
"objectList",
":",
"sortKey",
"=",
"self",
".",
"_getSortKey",
"(",
"astroObject",
")",
"resultsByClass"... | Checks each result can meet SNR requirments, adds to count
:return: | [
"Checks",
"each",
"result",
"can",
"meet",
"SNR",
"requirments",
"adds",
"to",
"count",
":",
"return",
":"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L233-L244 |
ryanvarley/ExoData | exodata/plots.py | _BaseDataPerClass._getPlotData | def _getPlotData(self):
""" Turns the resultsByClass Dict into a list of bin groups skipping the uncertain group if empty
return: (label list, ydata list)
:rtype: tuple(list(str), list(float))
"""
resultsByClass = self.resultsByClass
try:
if resultsByClass['Uncertain'] == 0: # remove uncertain tag if present and = 0
resultsByClass.pop('Uncertain', None)
except KeyError:
pass
plotData = list(zip(*resultsByClass.items())) # (labels, ydata)
return plotData | python | def _getPlotData(self):
""" Turns the resultsByClass Dict into a list of bin groups skipping the uncertain group if empty
return: (label list, ydata list)
:rtype: tuple(list(str), list(float))
"""
resultsByClass = self.resultsByClass
try:
if resultsByClass['Uncertain'] == 0: # remove uncertain tag if present and = 0
resultsByClass.pop('Uncertain', None)
except KeyError:
pass
plotData = list(zip(*resultsByClass.items())) # (labels, ydata)
return plotData | [
"def",
"_getPlotData",
"(",
"self",
")",
":",
"resultsByClass",
"=",
"self",
".",
"resultsByClass",
"try",
":",
"if",
"resultsByClass",
"[",
"'Uncertain'",
"]",
"==",
"0",
":",
"# remove uncertain tag if present and = 0",
"resultsByClass",
".",
"pop",
"(",
"'Uncer... | Turns the resultsByClass Dict into a list of bin groups skipping the uncertain group if empty
return: (label list, ydata list)
:rtype: tuple(list(str), list(float)) | [
"Turns",
"the",
"resultsByClass",
"Dict",
"into",
"a",
"list",
"of",
"bin",
"groups",
"skipping",
"the",
"uncertain",
"group",
"if",
"empty"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L246-L262 |
ryanvarley/ExoData | exodata/plots.py | _BaseDataPerClass._genEmptyResults | def _genEmptyResults(self):
""" Uses allowed keys to generate a empty dict to start counting from
:return:
"""
allowedKeys = self._allowedKeys
keysDict = OrderedDict() # Note: list comprehension take 0 then 2 then 1 then 3 etc for some reason. we want strict order
for k in allowedKeys:
keysDict[k] = 0
resultsByClass = keysDict
return resultsByClass | python | def _genEmptyResults(self):
""" Uses allowed keys to generate a empty dict to start counting from
:return:
"""
allowedKeys = self._allowedKeys
keysDict = OrderedDict() # Note: list comprehension take 0 then 2 then 1 then 3 etc for some reason. we want strict order
for k in allowedKeys:
keysDict[k] = 0
resultsByClass = keysDict
return resultsByClass | [
"def",
"_genEmptyResults",
"(",
"self",
")",
":",
"allowedKeys",
"=",
"self",
".",
"_allowedKeys",
"keysDict",
"=",
"OrderedDict",
"(",
")",
"# Note: list comprehension take 0 then 2 then 1 then 3 etc for some reason. we want strict order",
"for",
"k",
"in",
"allowedKeys",
... | Uses allowed keys to generate a empty dict to start counting from
:return: | [
"Uses",
"allowed",
"keys",
"to",
"generate",
"a",
"empty",
"dict",
"to",
"start",
"counting",
"from",
":",
"return",
":"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L337-L351 |
ryanvarley/ExoData | exodata/plots.py | DataPerParameterBin._getSortKey | def _getSortKey(self, planet):
""" Takes a planet and turns it into a key to be sorted by
:param planet:
:return:
"""
value = eval('planet.'+self._planetProperty)
# TODO some sort of data validation, either before or using try except
if self.unit is not None:
try:
value = value.rescale(self.unit)
except AttributeError: # either nan or unitless
pass
return _sortValueIntoGroup(self._allowedKeys[:-1], self._binlimits, value) | python | def _getSortKey(self, planet):
""" Takes a planet and turns it into a key to be sorted by
:param planet:
:return:
"""
value = eval('planet.'+self._planetProperty)
# TODO some sort of data validation, either before or using try except
if self.unit is not None:
try:
value = value.rescale(self.unit)
except AttributeError: # either nan or unitless
pass
return _sortValueIntoGroup(self._allowedKeys[:-1], self._binlimits, value) | [
"def",
"_getSortKey",
"(",
"self",
",",
"planet",
")",
":",
"value",
"=",
"eval",
"(",
"'planet.'",
"+",
"self",
".",
"_planetProperty",
")",
"# TODO some sort of data validation, either before or using try except",
"if",
"self",
".",
"unit",
"is",
"not",
"None",
... | Takes a planet and turns it into a key to be sorted by
:param planet:
:return: | [
"Takes",
"a",
"planet",
"and",
"turns",
"it",
"into",
"a",
"key",
"to",
"be",
"sorted",
"by",
":",
"param",
"planet",
":",
":",
"return",
":"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L371-L387 |
ryanvarley/ExoData | exodata/plots.py | DataPerParameterBin._genKeysBins | def _genKeysBins(self):
""" Generates keys from bins, sets self._allowedKeys normally set in _classVariables
"""
binlimits = self._binlimits
allowedKeys = []
midbinlimits = binlimits
if binlimits[0] == -float('inf'):
midbinlimits = binlimits[1:] # remove the bottom limit
allowedKeys.append('<{0}'.format(midbinlimits[0]))
if binlimits[-1] == float('inf'):
midbinlimits = midbinlimits[:-1]
lastbin = midbinlimits[0]
for binlimit in midbinlimits[1:]:
if lastbin == binlimit:
allowedKeys.append('{0}'.format(binlimit))
else:
allowedKeys.append('{0} to {1}'.format(lastbin, binlimit))
lastbin = binlimit
if binlimits[-1] == float('inf'):
allowedKeys.append('{0}+'.format(binlimits[-2]))
allowedKeys.append('Uncertain')
self._allowedKeys = allowedKeys | python | def _genKeysBins(self):
""" Generates keys from bins, sets self._allowedKeys normally set in _classVariables
"""
binlimits = self._binlimits
allowedKeys = []
midbinlimits = binlimits
if binlimits[0] == -float('inf'):
midbinlimits = binlimits[1:] # remove the bottom limit
allowedKeys.append('<{0}'.format(midbinlimits[0]))
if binlimits[-1] == float('inf'):
midbinlimits = midbinlimits[:-1]
lastbin = midbinlimits[0]
for binlimit in midbinlimits[1:]:
if lastbin == binlimit:
allowedKeys.append('{0}'.format(binlimit))
else:
allowedKeys.append('{0} to {1}'.format(lastbin, binlimit))
lastbin = binlimit
if binlimits[-1] == float('inf'):
allowedKeys.append('{0}+'.format(binlimits[-2]))
allowedKeys.append('Uncertain')
self._allowedKeys = allowedKeys | [
"def",
"_genKeysBins",
"(",
"self",
")",
":",
"binlimits",
"=",
"self",
".",
"_binlimits",
"allowedKeys",
"=",
"[",
"]",
"midbinlimits",
"=",
"binlimits",
"if",
"binlimits",
"[",
"0",
"]",
"==",
"-",
"float",
"(",
"'inf'",
")",
":",
"midbinlimits",
"=",
... | Generates keys from bins, sets self._allowedKeys normally set in _classVariables | [
"Generates",
"keys",
"from",
"bins",
"sets",
"self",
".",
"_allowedKeys",
"normally",
"set",
"in",
"_classVariables"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L392-L420 |
ryanvarley/ExoData | exodata/plots.py | GeneralPlotter.set_xaxis | def set_xaxis(self, param, unit=None, label=None):
""" Sets the value of use on the x axis
:param param: value to use on the xaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to, None will use the default
:type unit: quantities unit or None
:param label: axis label to use, if None "Parameter (Unit)" is generated here and used
:type label: str
"""
if unit is None:
unit = self._getParLabelAndUnit(param)[1] # use the default unit defined in this class
self._xaxis_unit = unit
self._xaxis = self._set_axis(param, unit)
if label is None:
self.xlabel = self._gen_label(param, unit)
else:
self.xlabel = label | python | def set_xaxis(self, param, unit=None, label=None):
""" Sets the value of use on the x axis
:param param: value to use on the xaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to, None will use the default
:type unit: quantities unit or None
:param label: axis label to use, if None "Parameter (Unit)" is generated here and used
:type label: str
"""
if unit is None:
unit = self._getParLabelAndUnit(param)[1] # use the default unit defined in this class
self._xaxis_unit = unit
self._xaxis = self._set_axis(param, unit)
if label is None:
self.xlabel = self._gen_label(param, unit)
else:
self.xlabel = label | [
"def",
"set_xaxis",
"(",
"self",
",",
"param",
",",
"unit",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"if",
"unit",
"is",
"None",
":",
"unit",
"=",
"self",
".",
"_getParLabelAndUnit",
"(",
"param",
")",
"[",
"1",
"]",
"# use the default unit de... | Sets the value of use on the x axis
:param param: value to use on the xaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to, None will use the default
:type unit: quantities unit or None
:param label: axis label to use, if None "Parameter (Unit)" is generated here and used
:type label: str | [
"Sets",
"the",
"value",
"of",
"use",
"on",
"the",
"x",
"axis",
":",
"param",
"param",
":",
"value",
"to",
"use",
"on",
"the",
"xaxis",
"should",
"be",
"a",
"variable",
"or",
"function",
"of",
"the",
"objects",
"in",
"objectList",
".",
"ie",
"R",
"for... | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L483-L503 |
ryanvarley/ExoData | exodata/plots.py | GeneralPlotter.set_yaxis | def set_yaxis(self, param, unit=None, label=None):
""" Sets the value of use on the yaxis
:param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to
:type unit: quantities unit or None
:param label: axis label to use, if None "Parameter (Unit)" is generated here and used
:type label: str
"""
if unit is None:
unit = self._getParLabelAndUnit(param)[1] # use the default unit defined in this class
self._yaxis_unit = unit
self._yaxis = self._set_axis(param, unit)
if label is None:
self.ylabel = self._gen_label(param, unit)
else:
self.ylabel = label | python | def set_yaxis(self, param, unit=None, label=None):
""" Sets the value of use on the yaxis
:param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to
:type unit: quantities unit or None
:param label: axis label to use, if None "Parameter (Unit)" is generated here and used
:type label: str
"""
if unit is None:
unit = self._getParLabelAndUnit(param)[1] # use the default unit defined in this class
self._yaxis_unit = unit
self._yaxis = self._set_axis(param, unit)
if label is None:
self.ylabel = self._gen_label(param, unit)
else:
self.ylabel = label | [
"def",
"set_yaxis",
"(",
"self",
",",
"param",
",",
"unit",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"if",
"unit",
"is",
"None",
":",
"unit",
"=",
"self",
".",
"_getParLabelAndUnit",
"(",
"param",
")",
"[",
"1",
"]",
"# use the default unit de... | Sets the value of use on the yaxis
:param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to
:type unit: quantities unit or None
:param label: axis label to use, if None "Parameter (Unit)" is generated here and used
:type label: str | [
"Sets",
"the",
"value",
"of",
"use",
"on",
"the",
"yaxis",
":",
"param",
"param",
":",
"value",
"to",
"use",
"on",
"the",
"yaxis",
"should",
"be",
"a",
"variable",
"or",
"function",
"of",
"the",
"objects",
"in",
"objectList",
".",
"ie",
"R",
"for",
"... | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L505-L524 |
ryanvarley/ExoData | exodata/plots.py | GeneralPlotter._set_axis | def _set_axis(self, param, unit):
""" this should take a variable or a function and turn it into a list by evaluating on each planet
"""
axisValues = []
for astroObject in self.objectList:
try:
value = eval('astroObject.{0}'.format(param))
except ac.HierarchyError: # ie trying to call planet.star and one planet is a lone ranger
value = np.nan
if unit is None: # no unit to rescale (a aq.unitless quanitity would otherwise fail with ValueError)
axisValues.append(value)
else:
try:
axisValues.append(value.rescale(unit))
except AttributeError: # either nan or unitless
axisValues.append(value)
return axisValues | python | def _set_axis(self, param, unit):
""" this should take a variable or a function and turn it into a list by evaluating on each planet
"""
axisValues = []
for astroObject in self.objectList:
try:
value = eval('astroObject.{0}'.format(param))
except ac.HierarchyError: # ie trying to call planet.star and one planet is a lone ranger
value = np.nan
if unit is None: # no unit to rescale (a aq.unitless quanitity would otherwise fail with ValueError)
axisValues.append(value)
else:
try:
axisValues.append(value.rescale(unit))
except AttributeError: # either nan or unitless
axisValues.append(value)
return axisValues | [
"def",
"_set_axis",
"(",
"self",
",",
"param",
",",
"unit",
")",
":",
"axisValues",
"=",
"[",
"]",
"for",
"astroObject",
"in",
"self",
".",
"objectList",
":",
"try",
":",
"value",
"=",
"eval",
"(",
"'astroObject.{0}'",
".",
"format",
"(",
"param",
")",... | this should take a variable or a function and turn it into a list by evaluating on each planet | [
"this",
"should",
"take",
"a",
"variable",
"or",
"a",
"function",
"and",
"turn",
"it",
"into",
"a",
"list",
"by",
"evaluating",
"on",
"each",
"planet"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L526-L544 |
ryanvarley/ExoData | exodata/plots.py | GeneralPlotter.set_marker_color | def set_marker_color(self, color='#3ea0e4', edgecolor='k'):
""" set the marker color used in the plot
:param color: matplotlib color (ie 'r', '#000000')
"""
# TODO allow a colour set per another variable
self._marker_color = color
self._edge_color = edgecolor | python | def set_marker_color(self, color='#3ea0e4', edgecolor='k'):
""" set the marker color used in the plot
:param color: matplotlib color (ie 'r', '#000000')
"""
# TODO allow a colour set per another variable
self._marker_color = color
self._edge_color = edgecolor | [
"def",
"set_marker_color",
"(",
"self",
",",
"color",
"=",
"'#3ea0e4'",
",",
"edgecolor",
"=",
"'k'",
")",
":",
"# TODO allow a colour set per another variable",
"self",
".",
"_marker_color",
"=",
"color",
"self",
".",
"_edge_color",
"=",
"edgecolor"
] | set the marker color used in the plot
:param color: matplotlib color (ie 'r', '#000000') | [
"set",
"the",
"marker",
"color",
"used",
"in",
"the",
"plot",
":",
"param",
"color",
":",
"matplotlib",
"color",
"(",
"ie",
"r",
"#000000",
")"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L546-L552 |
ryanvarley/ExoData | exodata/plots.py | DiscoveryMethodByYear.setup_keys | def setup_keys(self):
""" Build the initial data dictionary to store the values
"""
discovery_methods = {}
discovery_years = {}
nan_list = []
# Initial Loop to get keys
for planet in self.planet_list:
if 'Solar System' in planet.params['list'] and self.skip_solar_system_planets:
continue
try:
discovery_methods[planet.discoveryMethod] += 1
except KeyError:
discovery_methods[planet.discoveryMethod] = 1
try:
discovery_years[planet.discoveryYear] += 1
except KeyError:
discovery_years[planet.discoveryYear] = 1
if planet.discoveryMethod is np.nan:
nan_list.append(planet)
self.nan_list = nan_list
return discovery_years | python | def setup_keys(self):
""" Build the initial data dictionary to store the values
"""
discovery_methods = {}
discovery_years = {}
nan_list = []
# Initial Loop to get keys
for planet in self.planet_list:
if 'Solar System' in planet.params['list'] and self.skip_solar_system_planets:
continue
try:
discovery_methods[planet.discoveryMethod] += 1
except KeyError:
discovery_methods[planet.discoveryMethod] = 1
try:
discovery_years[planet.discoveryYear] += 1
except KeyError:
discovery_years[planet.discoveryYear] = 1
if planet.discoveryMethod is np.nan:
nan_list.append(planet)
self.nan_list = nan_list
return discovery_years | [
"def",
"setup_keys",
"(",
"self",
")",
":",
"discovery_methods",
"=",
"{",
"}",
"discovery_years",
"=",
"{",
"}",
"nan_list",
"=",
"[",
"]",
"# Initial Loop to get keys",
"for",
"planet",
"in",
"self",
".",
"planet_list",
":",
"if",
"'Solar System'",
"in",
"... | Build the initial data dictionary to store the values | [
"Build",
"the",
"initial",
"data",
"dictionary",
"to",
"store",
"the",
"values"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L577-L604 |
ryanvarley/ExoData | exodata/plots.py | DiscoveryMethodByYear.plot | def plot(self, method_labels=None, exodata_credit=True):
"""
:param method_labels: list of legend labels for the methods, i.e. give
'Radial Velocity' rather than 'RV'
:return:
"""
if method_labels is None:
method_labels = self.methods_to_plot
plot_matrix, year_list, discovery_years = self.generate_data()
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ind = np.arange(len(year_list))
# output from seaborn.color_palette("Set1", n_colors=8)
colors = [(0.89411765336990356, 0.10196078568696976, 0.10980392247438431),
(0.21602460800432691, 0.49487120380588606, 0.71987698697576341),
(0.30426760128900115, 0.68329106055054012, 0.29293349969620797),
(0.60083047361934883, 0.30814303335021526, 0.63169552298153153),
(1.0, 0.50591311045721465, 0.0031372549487095253),
(0.99315647868549117, 0.9870049982678657, 0.19915417450315812),
(0.65845446095747107, 0.34122261685483596, 0.1707958535236471),
(0.95850826852461868, 0.50846600392285513, 0.74492888871361229)]
width = 0.9
bottom = np.zeros_like(year_list)
for i, method in enumerate(self.methods_to_plot):
bar_data = [plot_matrix[year][method] for year in year_list]
plt.bar(ind, bar_data, width, color=colors[i], bottom=bottom, label=method_labels[i], linewidth=0)
bottom += np.array(bar_data) # plot the next bar stacked
plt.ylabel('Number of planets', fontsize=14)
plt.xlabel('Year', fontsize=14)
plt.xticks(ind+width/2., year_list, rotation=70, fontsize=13)
plt.xlim(0, ind[-1]+1)
plt.legend(loc=2, fontsize=13)
if exodata_credit is True:
ax.text(2, 420, 'Generated by ExoData on {}'.format(time.strftime("%d/%m/%Y")), fontsize=11)
for i, year in enumerate(year_list):
try:
total_planets = discovery_years[year]
except KeyError: # year with no planets discovered
continue # Dont label
y_pos = bottom[i]+10
x_pos = i
ax.text(x_pos, y_pos, '{}'.format(total_planets), fontsize=9)
plt.grid(b=True, which='both', color='0.9', linestyle='-')
return fig | python | def plot(self, method_labels=None, exodata_credit=True):
"""
:param method_labels: list of legend labels for the methods, i.e. give
'Radial Velocity' rather than 'RV'
:return:
"""
if method_labels is None:
method_labels = self.methods_to_plot
plot_matrix, year_list, discovery_years = self.generate_data()
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ind = np.arange(len(year_list))
# output from seaborn.color_palette("Set1", n_colors=8)
colors = [(0.89411765336990356, 0.10196078568696976, 0.10980392247438431),
(0.21602460800432691, 0.49487120380588606, 0.71987698697576341),
(0.30426760128900115, 0.68329106055054012, 0.29293349969620797),
(0.60083047361934883, 0.30814303335021526, 0.63169552298153153),
(1.0, 0.50591311045721465, 0.0031372549487095253),
(0.99315647868549117, 0.9870049982678657, 0.19915417450315812),
(0.65845446095747107, 0.34122261685483596, 0.1707958535236471),
(0.95850826852461868, 0.50846600392285513, 0.74492888871361229)]
width = 0.9
bottom = np.zeros_like(year_list)
for i, method in enumerate(self.methods_to_plot):
bar_data = [plot_matrix[year][method] for year in year_list]
plt.bar(ind, bar_data, width, color=colors[i], bottom=bottom, label=method_labels[i], linewidth=0)
bottom += np.array(bar_data) # plot the next bar stacked
plt.ylabel('Number of planets', fontsize=14)
plt.xlabel('Year', fontsize=14)
plt.xticks(ind+width/2., year_list, rotation=70, fontsize=13)
plt.xlim(0, ind[-1]+1)
plt.legend(loc=2, fontsize=13)
if exodata_credit is True:
ax.text(2, 420, 'Generated by ExoData on {}'.format(time.strftime("%d/%m/%Y")), fontsize=11)
for i, year in enumerate(year_list):
try:
total_planets = discovery_years[year]
except KeyError: # year with no planets discovered
continue # Dont label
y_pos = bottom[i]+10
x_pos = i
ax.text(x_pos, y_pos, '{}'.format(total_planets), fontsize=9)
plt.grid(b=True, which='both', color='0.9', linestyle='-')
return fig | [
"def",
"plot",
"(",
"self",
",",
"method_labels",
"=",
"None",
",",
"exodata_credit",
"=",
"True",
")",
":",
"if",
"method_labels",
"is",
"None",
":",
"method_labels",
"=",
"self",
".",
"methods_to_plot",
"plot_matrix",
",",
"year_list",
",",
"discovery_years"... | :param method_labels: list of legend labels for the methods, i.e. give
'Radial Velocity' rather than 'RV'
:return: | [
":",
"param",
"method_labels",
":",
"list",
"of",
"legend",
"labels",
"for",
"the",
"methods",
"i",
".",
"e",
".",
"give",
"Radial",
"Velocity",
"rather",
"than",
"RV"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/plots.py#L633-L690 |
openmednlp/bedrock | bedrock/viz.py | plot_confusion_matrix | def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label') | python | def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label') | [
"def",
"plot_confusion_matrix",
"(",
"cm",
",",
"classes",
",",
"normalize",
"=",
"False",
",",
"title",
"=",
"'Confusion matrix'",
",",
"cmap",
"=",
"plt",
".",
"cm",
".",
"Blues",
")",
":",
"if",
"normalize",
":",
"cm",
"=",
"cm",
".",
"astype",
"(",... | This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`. | [
"This",
"function",
"prints",
"and",
"plots",
"the",
"confusion",
"matrix",
".",
"Normalization",
"can",
"be",
"applied",
"by",
"setting",
"normalize",
"=",
"True",
"."
] | train | https://github.com/openmednlp/bedrock/blob/15796bd7837ddfe7ad5235fd188e5d7af8c0be49/bedrock/viz.py#L12-L44 |
ask/redish | redish/types.py | is_zsettable | def is_zsettable(s):
"""quick check that all values in a dict are reals"""
return all(map(lambda x: isinstance(x, (int, float, long)), s.values())) | python | def is_zsettable(s):
"""quick check that all values in a dict are reals"""
return all(map(lambda x: isinstance(x, (int, float, long)), s.values())) | [
"def",
"is_zsettable",
"(",
"s",
")",
":",
"return",
"all",
"(",
"map",
"(",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"(",
"int",
",",
"float",
",",
"long",
")",
")",
",",
"s",
".",
"values",
"(",
")",
")",
")"
] | quick check that all values in a dict are reals | [
"quick",
"check",
"that",
"all",
"values",
"in",
"a",
"dict",
"are",
"reals"
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L726-L728 |
ask/redish | redish/types.py | List.trim | def trim(self, start, stop):
"""Trim the list to the specified range of elements."""
return self.client.ltrim(self.name, start, stop - 1) | python | def trim(self, start, stop):
"""Trim the list to the specified range of elements."""
return self.client.ltrim(self.name, start, stop - 1) | [
"def",
"trim",
"(",
"self",
",",
"start",
",",
"stop",
")",
":",
"return",
"self",
".",
"client",
".",
"ltrim",
"(",
"self",
".",
"name",
",",
"start",
",",
"stop",
"-",
"1",
")"
] | Trim the list to the specified range of elements. | [
"Trim",
"the",
"list",
"to",
"the",
"specified",
"range",
"of",
"elements",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L75-L77 |
ask/redish | redish/types.py | List.remove | def remove(self, value, count=1):
"""Remove occurences of ``value`` from the list.
:keyword count: Number of matching values to remove.
Default is to remove a single value.
"""
count = self.client.lrem(self.name, value, num=count)
if not count:
raise ValueError("%s not in list" % value)
return count | python | def remove(self, value, count=1):
"""Remove occurences of ``value`` from the list.
:keyword count: Number of matching values to remove.
Default is to remove a single value.
"""
count = self.client.lrem(self.name, value, num=count)
if not count:
raise ValueError("%s not in list" % value)
return count | [
"def",
"remove",
"(",
"self",
",",
"value",
",",
"count",
"=",
"1",
")",
":",
"count",
"=",
"self",
".",
"client",
".",
"lrem",
"(",
"self",
".",
"name",
",",
"value",
",",
"num",
"=",
"count",
")",
"if",
"not",
"count",
":",
"raise",
"ValueError... | Remove occurences of ``value`` from the list.
:keyword count: Number of matching values to remove.
Default is to remove a single value. | [
"Remove",
"occurences",
"of",
"value",
"from",
"the",
"list",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L87-L97 |
ask/redish | redish/types.py | Set.remove | def remove(self, member):
"""Remove element from set; it must be a member.
:raises KeyError: if the element is not a member.
"""
if not self.client.srem(self.name, member):
raise KeyError(member) | python | def remove(self, member):
"""Remove element from set; it must be a member.
:raises KeyError: if the element is not a member.
"""
if not self.client.srem(self.name, member):
raise KeyError(member) | [
"def",
"remove",
"(",
"self",
",",
"member",
")",
":",
"if",
"not",
"self",
".",
"client",
".",
"srem",
"(",
"self",
".",
"name",
",",
"member",
")",
":",
"raise",
"KeyError",
"(",
"member",
")"
] | Remove element from set; it must be a member.
:raises KeyError: if the element is not a member. | [
"Remove",
"element",
"from",
"set",
";",
"it",
"must",
"be",
"a",
"member",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L147-L154 |
ask/redish | redish/types.py | Set.pop | def pop(self):
"""Remove and return an arbitrary set element.
:raises KeyError: if the set is empty.
"""
member = self.client.spop(self.name)
if member is not None:
return member
raise KeyError() | python | def pop(self):
"""Remove and return an arbitrary set element.
:raises KeyError: if the set is empty.
"""
member = self.client.spop(self.name)
if member is not None:
return member
raise KeyError() | [
"def",
"pop",
"(",
"self",
")",
":",
"member",
"=",
"self",
".",
"client",
".",
"spop",
"(",
"self",
".",
"name",
")",
"if",
"member",
"is",
"not",
"None",
":",
"return",
"member",
"raise",
"KeyError",
"(",
")"
] | Remove and return an arbitrary set element.
:raises KeyError: if the set is empty. | [
"Remove",
"and",
"return",
"an",
"arbitrary",
"set",
"element",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L156-L165 |
ask/redish | redish/types.py | Set.union | def union(self, other):
"""Return the union of sets as a new set.
(i.e. all elements that are in either set.)
Operates on either redish.types.Set or __builtins__.set.
"""
if isinstance(other, self.__class__):
return self.client.sunion([self.name, other.name])
else:
return self._as_set().union(other) | python | def union(self, other):
"""Return the union of sets as a new set.
(i.e. all elements that are in either set.)
Operates on either redish.types.Set or __builtins__.set.
"""
if isinstance(other, self.__class__):
return self.client.sunion([self.name, other.name])
else:
return self._as_set().union(other) | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"self",
".",
"client",
".",
"sunion",
"(",
"[",
"self",
".",
"name",
",",
"other",
".",
"name",
"]",
")",
"e... | Return the union of sets as a new set.
(i.e. all elements that are in either set.)
Operates on either redish.types.Set or __builtins__.set. | [
"Return",
"the",
"union",
"of",
"sets",
"as",
"a",
"new",
"set",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L167-L178 |
ask/redish | redish/types.py | Set.update | def update(self, other):
"""Update this set with the union of itself and others."""
if isinstance(other, self.__class__):
return self.client.sunionstore(self.name, [self.name, other.name])
else:
return map(self.add, other) | python | def update(self, other):
"""Update this set with the union of itself and others."""
if isinstance(other, self.__class__):
return self.client.sunionstore(self.name, [self.name, other.name])
else:
return map(self.add, other) | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"self",
".",
"client",
".",
"sunionstore",
"(",
"self",
".",
"name",
",",
"[",
"self",
".",
"name",
",",
"oth... | Update this set with the union of itself and others. | [
"Update",
"this",
"set",
"with",
"the",
"union",
"of",
"itself",
"and",
"others",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L180-L185 |
ask/redish | redish/types.py | Set.intersection | def intersection(self, other):
"""Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
Operates on either redish.types.Set or __builtins__.set.
"""
if isinstance(other, self.__class__):
return self.client.sinter([self.name, other.name])
else:
return self._as_set().intersection(other) | python | def intersection(self, other):
"""Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
Operates on either redish.types.Set or __builtins__.set.
"""
if isinstance(other, self.__class__):
return self.client.sinter([self.name, other.name])
else:
return self._as_set().intersection(other) | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"self",
".",
"client",
".",
"sinter",
"(",
"[",
"self",
".",
"name",
",",
"other",
".",
"name",
"]",
")... | Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
Operates on either redish.types.Set or __builtins__.set. | [
"Return",
"the",
"intersection",
"of",
"two",
"sets",
"as",
"a",
"new",
"set",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L187-L198 |
ask/redish | redish/types.py | Set.intersection_update | def intersection_update(self, other):
"""Update the set with the intersection of itself and another."""
return self.client.sinterstore(self.name, [self.name, other.name]) | python | def intersection_update(self, other):
"""Update the set with the intersection of itself and another."""
return self.client.sinterstore(self.name, [self.name, other.name]) | [
"def",
"intersection_update",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"client",
".",
"sinterstore",
"(",
"self",
".",
"name",
",",
"[",
"self",
".",
"name",
",",
"other",
".",
"name",
"]",
")"
] | Update the set with the intersection of itself and another. | [
"Update",
"the",
"set",
"with",
"the",
"intersection",
"of",
"itself",
"and",
"another",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L200-L202 |
ask/redish | redish/types.py | Set.difference | def difference(self, *others):
"""Return the difference of two or more sets as a new :class:`set`.
(i.e. all elements that are in this set but not the others.)
Operates on either redish.types.Set or __builtins__.set.
"""
if all([isinstance(a, self.__class__) for a in others]):
return self.client.sdiff([self.name] + [other.name for other in others])
else:
othersets = filter(lambda x: isinstance(x, set), others)
otherTypes = filter(lambda x: isinstance(x, self.__class__), others)
return self.client.sdiff([self.name] + [other.name for other in otherTypes]).difference(*othersets) | python | def difference(self, *others):
"""Return the difference of two or more sets as a new :class:`set`.
(i.e. all elements that are in this set but not the others.)
Operates on either redish.types.Set or __builtins__.set.
"""
if all([isinstance(a, self.__class__) for a in others]):
return self.client.sdiff([self.name] + [other.name for other in others])
else:
othersets = filter(lambda x: isinstance(x, set), others)
otherTypes = filter(lambda x: isinstance(x, self.__class__), others)
return self.client.sdiff([self.name] + [other.name for other in otherTypes]).difference(*othersets) | [
"def",
"difference",
"(",
"self",
",",
"*",
"others",
")",
":",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"a",
",",
"self",
".",
"__class__",
")",
"for",
"a",
"in",
"others",
"]",
")",
":",
"return",
"self",
".",
"client",
".",
"sdiff",
"(",
"[",... | Return the difference of two or more sets as a new :class:`set`.
(i.e. all elements that are in this set but not the others.)
Operates on either redish.types.Set or __builtins__.set. | [
"Return",
"the",
"difference",
"of",
"two",
"or",
"more",
"sets",
"as",
"a",
"new",
":",
"class",
":",
"set",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L204-L217 |
ask/redish | redish/types.py | Set.difference_update | def difference_update(self, other):
"""Remove all elements of another set from this set."""
return self.client.sdiffstore(self.name, [self.name, other.name]) | python | def difference_update(self, other):
"""Remove all elements of another set from this set."""
return self.client.sdiffstore(self.name, [self.name, other.name]) | [
"def",
"difference_update",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"client",
".",
"sdiffstore",
"(",
"self",
".",
"name",
",",
"[",
"self",
".",
"name",
",",
"other",
".",
"name",
"]",
")"
] | Remove all elements of another set from this set. | [
"Remove",
"all",
"elements",
"of",
"another",
"set",
"from",
"this",
"set",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L219-L221 |
ask/redish | redish/types.py | SortedSet.add | def add(self, member, score):
"""Add the specified member to the sorted set, or update the score
if it already exist."""
return self.client.zadd(self.name, member, score) | python | def add(self, member, score):
"""Add the specified member to the sorted set, or update the score
if it already exist."""
return self.client.zadd(self.name, member, score) | [
"def",
"add",
"(",
"self",
",",
"member",
",",
"score",
")",
":",
"return",
"self",
".",
"client",
".",
"zadd",
"(",
"self",
".",
"name",
",",
"member",
",",
"score",
")"
] | Add the specified member to the sorted set, or update the score
if it already exist. | [
"Add",
"the",
"specified",
"member",
"to",
"the",
"sorted",
"set",
"or",
"update",
"the",
"score",
"if",
"it",
"already",
"exist",
"."
] | train | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L288-L291 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.