repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
greyli/flask-avatars | flask_avatars/identicon.py | Identicon._create_matrix | python | def _create_matrix(self, byte_list):
# Number of rows * cols halfed and rounded
# in order to fill opposite side
cells = int(self.rows * self.cols / 2 + self.cols % 2)
matrix = [[False] * self.cols for num in range(self.rows)]
for cell_number in range(cells):
# If... | This matrix decides which blocks should be filled fg/bg colour
True for fg_colour
False for bg_colour
hash_bytes - array of hash bytes values. RGB range values in each slot
Returns:
List representation of the matrix
[[True, True, True, True],
[False,... | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L169-L203 | [
"def _bit_is_one(self, n, hash_bytes):\n \"\"\"\n Check if the n (index) of hash_bytes is 1 or 0.\n \"\"\"\n\n scale = 16 # hexadecimal\n\n if not hash_bytes[int(n / (scale / 2))] >> int(\n (scale / 2) - ((n % (scale / 2)) + 1)) & 1 == 1:\n return False\n return True\n"
] | class Identicon(object):
def __init__(self, rows=None, cols=None, bg_color=None):
"""Generate identicon image.
:param rows: The row of pixels in avatar.
:param columns: The column of pixels in avatar.
:param bg_color: Backgroud color, pass RGB tuple, for example: (125, 125, 125).
... |
greyli/flask-avatars | flask_avatars/identicon.py | Identicon.generate | python | def generate(self, text):
sizes = current_app.config['AVATARS_SIZE_TUPLE']
path = current_app.config['AVATARS_SAVE_PATH']
suffix = {sizes[0]: 's', sizes[1]: 'm', sizes[2]: 'l'}
for size in sizes:
image_byte_array = self.get_image(
string=str(text),
... | Generate and save avatars, return a list of file name: [filename_s, filename_m, filename_l].
:param text: The text used to generate image. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L205-L221 | [
"def get_image(self, string, width, height, pad=0):\n \"\"\"\n Byte representation of a PNG image\n \"\"\"\n hex_digest_byte_list = self._string_to_byte_list(string)\n matrix = self._create_matrix(hex_digest_byte_list)\n return self._create_image(matrix, width, height, pad)\n",
"def save(self,... | class Identicon(object):
def __init__(self, rows=None, cols=None, bg_color=None):
"""Generate identicon image.
:param rows: The row of pixels in avatar.
:param columns: The column of pixels in avatar.
:param bg_color: Backgroud color, pass RGB tuple, for example: (125, 125, 125).
... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.get_field_cache | python | def get_field_cache(self, cache_type='es'):
if cache_type == 'kibana':
try:
search_results = urlopen(self.get_url).read().decode('utf-8')
except HTTPError: # as e:
# self.pr_err("get_field_cache(kibana), HTTPError: %s" % e)
return []
... | Return a list of fields' mappings | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L96-L125 | [
"def iteritems(d):\n if PY3:\n return d.items()\n else:\n return d.iteritems()\n",
"def pr_err(self, msg):\n print('[ERR] Mapping %s' % msg)\n",
"def dedup_field_cache(self, field_cache):\n deduped = []\n fields_found = {}\n for field in field_cache:\n name = field['name']... | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.post_field_cache | python | def post_field_cache(self, field_cache):
index_pattern = self.field_cache_to_index_pattern(field_cache)
# self.pr_dbg("request/post: %s" % index_pattern)
resp = requests.post(self.post_url, data=index_pattern).text
# resp = {"_index":".kibana","_type":"index-pattern","_id":"aaa*","_versi... | Where field_cache is a list of fields' mappings | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L142-L149 | [
"def field_cache_to_index_pattern(self, field_cache):\n \"\"\"Return a .kibana index-pattern doc_type\"\"\"\n mapping_dict = {}\n mapping_dict['customFormats'] = \"{}\"\n mapping_dict['title'] = self.index_pattern\n # now post the data into .kibana\n mapping_dict['fields'] = json.dumps(field_cache... | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.field_cache_to_index_pattern | python | def field_cache_to_index_pattern(self, field_cache):
mapping_dict = {}
mapping_dict['customFormats'] = "{}"
mapping_dict['title'] = self.index_pattern
# now post the data into .kibana
mapping_dict['fields'] = json.dumps(field_cache, separators=(',', ':'))
# in order to po... | Return a .kibana index-pattern doc_type | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L152-L161 | null | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.check_mapping | python | def check_mapping(self, m):
if 'name' not in m:
self.pr_dbg("Missing %s" % "name")
return False
# self.pr_dbg("Checking %s" % m['name'])
for x in ['analyzed', 'indexed', 'type', 'scripted', 'count']:
if x not in m or m[x] == "":
self.pr_dbg("Mi... | Assert minimum set of fields in cache, does not validate contents | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L163-L179 | [
"def pr_dbg(self, msg):\n if self.debug:\n print('[DBG] Mapping %s' % msg)\n"
] | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.get_index_mappings | python | def get_index_mappings(self, index):
fields_arr = []
for (key, val) in iteritems(index):
# self.pr_dbg("\tdoc_type: %s" % key)
doc_mapping = self.get_doc_type_mappings(index[key])
# self.pr_dbg("\tdoc_mapping: %s" % doc_mapping)
if doc_mapping is None:
... | Converts all index's doc_types to .kibana | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L181-L192 | [
"def iteritems(d):\n if PY3:\n return d.items()\n else:\n return d.iteritems()\n",
"def get_doc_type_mappings(self, doc_type):\n \"\"\"Converts all doc_types' fields to .kibana\"\"\"\n doc_fields_arr = []\n found_score = False\n for (key, val) in iteritems(doc_type):\n # sel... | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.get_doc_type_mappings | python | def get_doc_type_mappings(self, doc_type):
doc_fields_arr = []
found_score = False
for (key, val) in iteritems(doc_type):
# self.pr_dbg("\t\tfield: %s" % key)
# self.pr_dbg("\tval: %s" % val)
add_it = False
retdict = {}
# _ are system
... | Converts all doc_types' fields to .kibana | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L194-L254 | [
"def iteritems(d):\n if PY3:\n return d.items()\n else:\n return d.iteritems()\n",
"def pr_err(self, msg):\n print('[ERR] Mapping %s' % msg)\n",
"def check_mapping(self, m):\n \"\"\"Assert minimum set of fields in cache, does not validate contents\"\"\"\n if 'name' not in m:\n ... | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.get_field_mappings | python | def get_field_mappings(self, field):
retdict = {}
retdict['indexed'] = False
retdict['analyzed'] = False
for (key, val) in iteritems(field):
if key in self.mappings:
if (key == 'type' and
(val == "long" or
val == "integ... | Converts ES field mappings to .kibana field mappings | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L256-L278 | [
"def iteritems(d):\n if PY3:\n return d.items()\n else:\n return d.iteritems()\n"
] | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.is_kibana_cache_incomplete | python | def is_kibana_cache_incomplete(self, es_cache, k_cache):
# convert list into dict, with each item's ['name'] as key
k_dict = {}
for field in k_cache:
# self.pr_dbg("field: %s" % field)
k_dict[field['name']] = field
for ign_f in self.mappings_ignore:
... | Test if k_cache is incomplete
Assume k_cache is always correct, but could be missing new
fields that es_cache has | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L310-L339 | null | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.list_to_compare_dict | python | def list_to_compare_dict(self, list_form):
compare_dict = {}
for field in list_form:
if field['name'] in compare_dict:
self.pr_dbg("List has duplicate field %s:\n%s" %
(field['name'], compare_dict[field['name']]))
if compare_dict[fi... | Convert list into a data structure we can query easier | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L341-L354 | [
"def pr_dbg(self, msg):\n if self.debug:\n print('[DBG] Mapping %s' % msg)\n"
] | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/mapping.py | KibanaMapping.compare_field_caches | python | def compare_field_caches(self, replica, original):
if original is None:
original = []
if replica is None:
replica = []
self.pr_dbg("Comparing orig with %s fields to replica with %s fields" %
(len(original), len(replica)))
# convert list into di... | Verify original is subset of replica | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/mapping.py#L356-L400 | [
"def iteritems(d):\n if PY3:\n return d.items()\n else:\n return d.iteritems()\n",
"def pr_dbg(self, msg):\n if self.debug:\n print('[DBG] Mapping %s' % msg)\n",
"def list_to_compare_dict(self, list_form):\n \"\"\"Convert list into a data structure we can query easier\"\"\"\n ... | class KibanaMapping():
def __init__(self, index, index_pattern, host, debug=False):
self.index = index
self._index_pattern = index_pattern
self._host = host
self.update_urls()
# from the js possible mappings are:
# { type, indexed, analyzed, doc_values }
#... |
rfarley3/Kibana | kibana/manager.py | KibanaManager.put_object | python | def put_object(self, obj):
# TODO consider putting into a ES class
self.pr_dbg('put_obj: %s' % self.json_dumps(obj))
if obj['_index'] is None or obj['_index'] == "":
raise Exception("Invalid Object, no index")
if obj['_id'] is None or obj['_id'] == "":
raise Excep... | Wrapper for es.index, determines metadata needed to index from obj.
If you have a raw object json string you can hard code these:
index is .kibana (as of kibana4);
id can be A-Za-z0-9\- and must be unique;
doc_type is either visualization, dashboard, search
or for settings do... | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L105-L134 | [
"def pr_dbg(self, msg):\n if self.debug:\n print('[DBG] Manager %s' % msg)\n",
"def pr_err(self, msg):\n print('[ERR] Manager %s' % msg)\n",
"def connect_es(self):\n if self.es is not None:\n return\n self.es = Elasticsearch(\n [{'host': self._host_ip, 'port': self._host_port}])... | class KibanaManager():
"""Import/Export Kibana objects"""
def __init__(self, index, host, debug=False):
self._host_ip = host[0]
self._host_port = host[1]
self.index = index
self.es = None
self.max_hits = 9999
self.debug = debug
def pr_dbg(self, msg):
... |
rfarley3/Kibana | kibana/manager.py | KibanaManager.del_object | python | def del_object(self, obj):
if obj['_index'] is None or obj['_index'] == "":
raise Exception("Invalid Object")
if obj['_id'] is None or obj['_id'] == "":
raise Exception("Invalid Object")
if obj['_type'] is None or obj['_type'] == "":
raise Exception("Invalid O... | Debug deletes obj of obj[_type] with id of obj['_id'] | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L144-L155 | [
"def connect_es(self):\n if self.es is not None:\n return\n self.es = Elasticsearch(\n [{'host': self._host_ip, 'port': self._host_port}])\n"
] | class KibanaManager():
"""Import/Export Kibana objects"""
def __init__(self, index, host, debug=False):
self._host_ip = host[0]
self._host_port = host[1]
self.index = index
self.es = None
self.max_hits = 9999
self.debug = debug
def pr_dbg(self, msg):
... |
rfarley3/Kibana | kibana/manager.py | KibanaManager.json_dumps | python | def json_dumps(self, obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) | Serializer for consistency | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L161-L163 | null | class KibanaManager():
"""Import/Export Kibana objects"""
def __init__(self, index, host, debug=False):
self._host_ip = host[0]
self._host_port = host[1]
self.index = index
self.es = None
self.max_hits = 9999
self.debug = debug
def pr_dbg(self, msg):
... |
rfarley3/Kibana | kibana/manager.py | KibanaManager.safe_filename | python | def safe_filename(self, otype, oid):
permitted = set(['_', '-', '(', ')'])
oid = ''.join([c for c in oid if c.isalnum() or c in permitted])
while oid.find('--') != -1:
oid = oid.replace('--', '-')
ext = 'json'
ts = datetime.now().strftime("%Y%m%dT%H%M%S")
fnam... | Santize obj name into fname and verify doesn't already exist | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L165-L182 | null | class KibanaManager():
"""Import/Export Kibana objects"""
def __init__(self, index, host, debug=False):
self._host_ip = host[0]
self._host_port = host[1]
self.index = index
self.es = None
self.max_hits = 9999
self.debug = debug
def pr_dbg(self, msg):
... |
rfarley3/Kibana | kibana/manager.py | KibanaManager.write_object_to_file | python | def write_object_to_file(self, obj, path='.', filename=None):
output = self.json_dumps(obj) + '\n'
if filename is None:
filename = self.safe_filename(obj['_type'], obj['_id'])
filename = os.path.join(path, filename)
self.pr_inf("Writing to file: " + filename)
with ope... | Convert obj (dict) to json string and write to file | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L184-L194 | [
"def pr_inf(self, msg):\n print('[INF] Manager %s' % msg)\n",
"def json_dumps(self, obj):\n \"\"\"Serializer for consistency\"\"\"\n return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))\n",
"def safe_filename(self, otype, oid):\n \"\"\"Santize obj name into fname and verify doesn... | class KibanaManager():
"""Import/Export Kibana objects"""
def __init__(self, index, host, debug=False):
self._host_ip = host[0]
self._host_port = host[1]
self.index = index
self.es = None
self.max_hits = 9999
self.debug = debug
def pr_dbg(self, msg):
... |
rfarley3/Kibana | kibana/manager.py | KibanaManager.write_pkg_to_file | python | def write_pkg_to_file(self, name, objects, path='.', filename=None):
# Kibana uses an array of docs, do the same
# as opposed to a dict of docs
pkg_objs = []
for _, obj in iteritems(objects):
pkg_objs.append(obj)
sorted_pkg = sorted(pkg_objs, key=lambda k: k['_id'])
... | Write a list of related objs to file | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L200-L215 | [
"def iteritems(d):\n if PY3:\n return d.items()\n else:\n return d.iteritems()\n",
"def pr_inf(self, msg):\n print('[INF] Manager %s' % msg)\n",
"def json_dumps(self, obj):\n \"\"\"Serializer for consistency\"\"\"\n return json.dumps(obj, sort_keys=True, indent=4, separators=(',', '... | class KibanaManager():
"""Import/Export Kibana objects"""
def __init__(self, index, host, debug=False):
self._host_ip = host[0]
self._host_port = host[1]
self.index = index
self.es = None
self.max_hits = 9999
self.debug = debug
def pr_dbg(self, msg):
... |
rfarley3/Kibana | kibana/manager.py | KibanaManager.get_objects | python | def get_objects(self, search_field, search_val):
query = ("{ size: " + str(self.max_hits) + ", " +
"query: { filtered: { filter: { " +
search_field + ": { value: \"" + search_val + "\"" +
" } } } } } }")
self.connect_es()
res = self.es.search(in... | Return all objects of type (assumes < MAX_HITS) | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L217-L237 | [
"def connect_es(self):\n if self.es is not None:\n return\n self.es = Elasticsearch(\n [{'host': self._host_ip, 'port': self._host_port}])\n"
] | class KibanaManager():
"""Import/Export Kibana objects"""
def __init__(self, index, host, debug=False):
self._host_ip = host[0]
self._host_port = host[1]
self.index = index
self.es = None
self.max_hits = 9999
self.debug = debug
def pr_dbg(self, msg):
... |
rfarley3/Kibana | kibana/manager.py | KibanaManager.get_dashboard_full | python | def get_dashboard_full(self, db_name):
objects = {}
dashboards = self.get_objects("type", "dashboard")
vizs = self.get_objects("type", "visualization")
searches = self.get_objects("type", "search")
if db_name not in dashboards:
return None
self.pr_inf("Found d... | Get DB and all objs needed to duplicate it | train | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L255-L282 | [
"def pr_inf(self, msg):\n print('[INF] Manager %s' % msg)\n",
"def pr_err(self, msg):\n print('[ERR] Manager %s' % msg)\n",
"def get_objects(self, search_field, search_val):\n \"\"\"Return all objects of type (assumes < MAX_HITS)\"\"\"\n query = (\"{ size: \" + str(self.max_hits) + \", \" +\n ... | class KibanaManager():
"""Import/Export Kibana objects"""
def __init__(self, index, host, debug=False):
self._host_ip = host[0]
self._host_port = host[1]
self.index = index
self.es = None
self.max_hits = 9999
self.debug = debug
def pr_dbg(self, msg):
... |
deep-compute/logagg | logagg/util.py | start_daemon_thread | python | def start_daemon_thread(target, args=()):
th = Thread(target=target, args=args)
th.daemon = True
th.start()
return th | starts a deamon thread for a given target function and arguments. | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/util.py#L45-L50 | null | import collections
from deeputil import Dummy
from operator import attrgetter
DUMMY = Dummy()
def memoize(f):
# from: https://goo.gl/aXt4Qy
class memodict(dict):
__slots__ = ()
def __missing__(self, key):
self[key] = ret = f(key)
return ret
return memodict().__ge... |
deep-compute/logagg | logagg/util.py | serialize_dict_keys | python | def serialize_dict_keys(d, prefix=""):
keys = []
for k, v in d.iteritems():
fqk = '%s%s' % (prefix, k)
keys.append(fqk)
if isinstance(v, dict):
keys.extend(serialize_dict_keys(v, prefix="%s." % fqk))
return keys | returns all the keys in a dictionary.
>>> serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } })
['a', 'a.b', 'a.b.c', 'a.b.b'] | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/util.py#L53-L66 | [
"def serialize_dict_keys(d, prefix=\"\"):\n \"\"\"returns all the keys in a dictionary.\n\n >>> serialize_dict_keys({\"a\": {\"b\": {\"c\": 1, \"b\": 2} } })\n ['a', 'a.b', 'a.b.c', 'a.b.b']\n \"\"\"\n keys = []\n for k, v in d.iteritems():\n fqk = '%s%s' % (prefix, k)\n keys.append(... | import collections
from deeputil import Dummy
from operator import attrgetter
DUMMY = Dummy()
def memoize(f):
# from: https://goo.gl/aXt4Qy
class memodict(dict):
__slots__ = ()
def __missing__(self, key):
self[key] = ret = f(key)
return ret
return memodict().__ge... |
deep-compute/logagg | logagg/formatters.py | haproxy | python | def haproxy(line):
#TODO Handle all message formats
'''
>>> import pprint
>>> input_line1 = 'Apr 24 00:00:02 node haproxy[12298]: 1.1.1.1:48660 [24/Apr/2019:00:00:02.358] pre-staging~ pre-staging_doc/pre-staging_active 261/0/2/8/271 200 2406 - - ---- 4/4/0/1/0 0/0 {AAAAAA:AAAAA_AAAAA:AAAAA_AAAAA_AAAAA:3... | >>> import pprint
>>> input_line1 = 'Apr 24 00:00:02 node haproxy[12298]: 1.1.1.1:48660 [24/Apr/2019:00:00:02.358] pre-staging~ pre-staging_doc/pre-staging_active 261/0/2/8/271 200 2406 - - ---- 4/4/0/1/0 0/0 {AAAAAA:AAAAA_AAAAA:AAAAA_AAAAA_AAAAA:300A||| user@mail.net:sdasdasdasdsdasAHDivsjd=|user@mail.net|2018} "G... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L19-L94 | null | import re
import ujson as json
import datetime
class RawLog(dict): pass
#FIXME: cannot do both returns .. should it?
def docker_file_log_driver(line):
log = json.loads(json.loads(line)['msg'])
if 'formatter' in log.get('extra'):
return RawLog(dict(formatter=log.get('extra').get('formatter'),
... |
deep-compute/logagg | logagg/formatters.py | nginx_access | python | def nginx_access(line):
'''
>>> import pprint
>>> input_line1 = '{ \
"remote_addr": "127.0.0.1","remote_user": "-","timestamp": "1515144699.201", \
"request": "GET / HTTP/1.1","status": "200","request_time": "0.000", \
"body_bytes_sent": "396","htt... | >>> import pprint
>>> input_line1 = '{ \
"remote_addr": "127.0.0.1","remote_user": "-","timestamp": "1515144699.201", \
"request": "GET / HTTP/1.1","status": "200","request_time": "0.000", \
"body_bytes_sent": "396","http_referer": "-","http_user_agent": "... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L96-L160 | null | import re
import ujson as json
import datetime
class RawLog(dict): pass
#FIXME: cannot do both returns .. should it?
def docker_file_log_driver(line):
log = json.loads(json.loads(line)['msg'])
if 'formatter' in log.get('extra'):
return RawLog(dict(formatter=log.get('extra').get('formatter'),
... |
deep-compute/logagg | logagg/formatters.py | mongodb | python | def mongodb(line):
'''
>>> import pprint
>>> input_line1 = '2017-08-17T07:56:33.489+0200 I REPL [signalProcessingThread] shutting down replication subsystems'
>>> output_line1 = mongodb(input_line1)
>>> pprint.pprint(output_line1)
{'data': {'component': 'REPL',
'context': '[sig... | >>> import pprint
>>> input_line1 = '2017-08-17T07:56:33.489+0200 I REPL [signalProcessingThread] shutting down replication subsystems'
>>> output_line1 = mongodb(input_line1)
>>> pprint.pprint(output_line1)
{'data': {'component': 'REPL',
'context': '[signalProcessingThread]',
... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L162-L196 | null | import re
import ujson as json
import datetime
class RawLog(dict): pass
#FIXME: cannot do both returns .. should it?
def docker_file_log_driver(line):
log = json.loads(json.loads(line)['msg'])
if 'formatter' in log.get('extra'):
return RawLog(dict(formatter=log.get('extra').get('formatter'),
... |
deep-compute/logagg | logagg/formatters.py | django | python | def django(line):
'''
>>> import pprint
>>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }'
>>> output_line1... | >>> import pprint
>>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }'
>>> output_line1 = django(input_line1)
>>>... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L199-L271 | null | import re
import ujson as json
import datetime
class RawLog(dict): pass
#FIXME: cannot do both returns .. should it?
def docker_file_log_driver(line):
log = json.loads(json.loads(line)['msg'])
if 'formatter' in log.get('extra'):
return RawLog(dict(formatter=log.get('extra').get('formatter'),
... |
deep-compute/logagg | logagg/formatters.py | basescript | python | def basescript(line):
'''
>>> import pprint
>>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local/lib/python2.7/dist-packages/ba... | >>> import pprint
>>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local/lib/python2.7/dist-packages/basescript/basescript.py", "name": "... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L273-L304 | null | import re
import ujson as json
import datetime
class RawLog(dict): pass
#FIXME: cannot do both returns .. should it?
def docker_file_log_driver(line):
log = json.loads(json.loads(line)['msg'])
if 'formatter' in log.get('extra'):
return RawLog(dict(formatter=log.get('extra').get('formatter'),
... |
deep-compute/logagg | logagg/formatters.py | elasticsearch | python | def elasticsearch(line):
'''
>>> import pprint
>>> input_line = '[2017-08-30T06:27:19,158] [WARN ][o.e.m.j.JvmGcMonitorService] [Glsuj_2] [gc][296816] overhead, spent [1.2s] collecting in the last [1.3s]'
>>> output_line = elasticsearch(input_line)
>>> pprint.pprint(output_line)
{'data': {'garba... | >>> import pprint
>>> input_line = '[2017-08-30T06:27:19,158] [WARN ][o.e.m.j.JvmGcMonitorService] [Glsuj_2] [gc][296816] overhead, spent [1.2s] collecting in the last [1.3s]'
>>> output_line = elasticsearch(input_line)
>>> pprint.pprint(output_line)
{'data': {'garbage_collector': 'gc',
'g... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L306-L370 | null | import re
import ujson as json
import datetime
class RawLog(dict): pass
#FIXME: cannot do both returns .. should it?
def docker_file_log_driver(line):
log = json.loads(json.loads(line)['msg'])
if 'formatter' in log.get('extra'):
return RawLog(dict(formatter=log.get('extra').get('formatter'),
... |
deep-compute/logagg | logagg/formatters.py | elasticsearch_ispartial_log | python | def elasticsearch_ispartial_log(line):
'''
>>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], current capacit... | >>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], current capacity [1000]'
>>> line2 = ' org.elasticsearch.Reso... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L374-L391 | null | import re
import ujson as json
import datetime
class RawLog(dict): pass
#FIXME: cannot do both returns .. should it?
def docker_file_log_driver(line):
log = json.loads(json.loads(line)['msg'])
if 'formatter' in log.get('extra'):
return RawLog(dict(formatter=log.get('extra').get('formatter'),
... |
deep-compute/logagg | logagg/collector.py | load_formatter_fn | python | def load_formatter_fn(formatter):
'''
>>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS
<function basescript at 0x...>
'''
obj = util.load_object(formatter)
if not hasattr(obj, 'ispartial'):
obj.ispartial = util.ispartial
return obj | >>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS
<function basescript at 0x...> | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/collector.py#L23-L31 | null | import os
import sys
import time
import ujson as json
import glob
import uuid
import Queue
import socket
import datetime
from operator import attrgetter
import traceback
from deeputil import AttrDict, keeprunning
from pygtail import Pygtail
from logagg import util
from logagg.formatters import RawLog
# TODO
'''
After... |
deep-compute/logagg | logagg/collector.py | LogCollector._remove_redundancy | python | def _remove_redundancy(self, log):
for key in log:
if key in log and key in log['data']:
log[key] = log['data'].pop(key)
return log | Removes duplicate data from 'data' inside log dict and brings it
out.
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> log = {'id' : 46846876, 'type' : 'log',
... 'data' : {'a' : 1, 'b' : 2, 'type' : 'metric'}}
>>> lc._r... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/collector.py#L78-L92 | null | class LogCollector(object):
DESC = 'Collects the log information and sends to NSQTopic'
QUEUE_MAX_SIZE = 2000 # Maximum number of messages in in-mem queue
MAX_NBYTES_TO_SEND = 4.5 * (1024**2) # Number of bytes from in-mem queue minimally required to push
MIN_NBYTES_TO_SEND = 512 * 1024 # Min... |
deep-compute/logagg | logagg/collector.py | LogCollector.validate_log_format | python | def validate_log_format(self, log):
'''
>>> lc = LogCollector('file=/path/to/file.log:formatter=logagg.formatters.basescript', 30)
>>> incomplete_log = {'data' : {'x' : 1, 'y' : 2},
... 'raw' : 'Not all keys present'}
>>> lc.validate_log_format(incomplete_log... | >>> lc = LogCollector('file=/path/to/file.log:formatter=logagg.formatters.basescript', 30)
>>> incomplete_log = {'data' : {'x' : 1, 'y' : 2},
... 'raw' : 'Not all keys present'}
>>> lc.validate_log_format(incomplete_log)
'failed'
>>> redundant_log = {'one_in... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/collector.py#L94-L159 | null | class LogCollector(object):
DESC = 'Collects the log information and sends to NSQTopic'
QUEUE_MAX_SIZE = 2000 # Maximum number of messages in in-mem queue
MAX_NBYTES_TO_SEND = 4.5 * (1024**2) # Number of bytes from in-mem queue minimally required to push
MIN_NBYTES_TO_SEND = 512 * 1024 # Min... |
deep-compute/logagg | logagg/collector.py | LogCollector.assign_default_log_values | python | def assign_default_log_values(self, fpath, line, formatter):
'''
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> from pprint import pprint
>>> formatter = 'logagg.formatters.mongodb'
>>> fpath = '/var/log/mongodb/mongodb.log'
... | >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> from pprint import pprint
>>> formatter = 'logagg.formatters.mongodb'
>>> fpath = '/var/log/mongodb/mongodb.log'
>>> line = 'some log line here'
>>> default_log = lc.assign_defaul... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/collector.py#L184-L221 | null | class LogCollector(object):
DESC = 'Collects the log information and sends to NSQTopic'
QUEUE_MAX_SIZE = 2000 # Maximum number of messages in in-mem queue
MAX_NBYTES_TO_SEND = 4.5 * (1024**2) # Number of bytes from in-mem queue minimally required to push
MIN_NBYTES_TO_SEND = 512 * 1024 # Min... |
deep-compute/logagg | logagg/collector.py | LogCollector._scan_fpatterns | python | def _scan_fpatterns(self, state):
'''
For a list of given fpatterns, this starts a thread
collecting log lines from file
>>> os.path.isfile = lambda path: path == '/path/to/log_file.log'
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 3... | For a list of given fpatterns, this starts a thread
collecting log lines from file
>>> os.path.isfile = lambda path: path == '/path/to/log_file.log'
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> print(lc.fpaths)
file=/path/to... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/collector.py#L356-L412 | null | class LogCollector(object):
DESC = 'Collects the log information and sends to NSQTopic'
QUEUE_MAX_SIZE = 2000 # Maximum number of messages in in-mem queue
MAX_NBYTES_TO_SEND = 4.5 * (1024**2) # Number of bytes from in-mem queue minimally required to push
MIN_NBYTES_TO_SEND = 512 * 1024 # Min... |
deep-compute/logagg | logagg/forwarders.py | MongoDBForwarder._parse_msg_for_mongodb | python | def _parse_msg_for_mongodb(self, msgs):
'''
>>> mdbf = MongoDBForwarder('no_host', '27017', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = [{u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... ... | >>> mdbf = MongoDBForwarder('no_host', '27017', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = [{u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... u'ln': 8,
... u'name... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/forwarders.py#L64-L116 | null | class MongoDBForwarder(BaseForwarder):
SERVER_SELECTION_TIMEOUT = 500 # MongoDB server selection timeout
# FIXME: normalize all var names
def __init__(self,
host, port,
user, password,
db, collection, log=DUMMY):
self.host = host
self.port... |
deep-compute/logagg | logagg/forwarders.py | InfluxDBForwarder._tag_and_field_maker | python | def _tag_and_field_maker(self, event):
'''
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... ... | >>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... u'ln': 8,
... ... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/forwarders.py#L167-L221 | null | class InfluxDBForwarder(BaseForwarder):
EXCLUDE_TAGS = set(["id", "raw", "timestamp", "type", "event", "error"])
def __init__(self,
host, port,
user, password,
db, collection, log=DUMMY):
self.host = host
self.port = port
self.user = us... |
deep-compute/logagg | logagg/forwarders.py | InfluxDBForwarder._parse_msg_for_influxdb | python | def _parse_msg_for_influxdb(self, msgs):
'''
>>> from logagg.forwarders import InfluxDBForwarder
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> valid_log = [{u'data': {u'_force_this_as_field': ... | >>> from logagg.forwarders import InfluxDBForwarder
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> valid_log = [{u'data': {u'_force_this_as_field': 'CXNS CNS nbkbsd',
... u'a': 1,
.... | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/forwarders.py#L223-L290 | null | class InfluxDBForwarder(BaseForwarder):
EXCLUDE_TAGS = set(["id", "raw", "timestamp", "type", "event", "error"])
def __init__(self,
host, port,
user, password,
db, collection, log=DUMMY):
self.host = host
self.port = port
self.user = us... |
deep-compute/logagg | logagg/nsqsender.py | NSQSender._is_ready | python | def _is_ready(self, topic_name):
'''
Is NSQ running and have space to receive messages?
'''
url = 'http://%s/stats?format=json&topic=%s' % (self.nsqd_http_address, topic_name)
#Cheacking for ephmeral channels
if '#' in topic_name:
topic_name, tag =topic_name.s... | Is NSQ running and have space to receive messages? | train | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/nsqsender.py#L39-L74 | null | class NSQSender(object):
NSQ_READY_CHECK_INTERVAL = 1 # Wait time to check nsq readiness (alive and not full)
HEARTBEAT_TOPIC = 'Heartbeat#ephemeral' # Topic name at which heartbeat is to be sent
MPUB_URL = 'http://%s/mpub?topic=%s' # Url to post msgs to NSQ
def __init__(self, http_loc, ... |
chrismattmann/nutch-python | nutch/nutch.py | defaultCrawlId | python | def defaultCrawlId():
timestamp = datetime.now().isoformat().replace(':', '_')
user = getuser()
return '_'.join(('crawl', user, timestamp)) | Provide a reasonable default crawl name using the user name and date | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L91-L98 | null | #!/usr/bin/env python2.7
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Vers... |
chrismattmann/nutch-python | nutch/nutch.py | main | python | def main(argv=None):
global Verbose, Mock
if argv is None:
argv = sys.argv
if len(argv) < 5: die('Bad args')
try:
opts, argv = getopt.getopt(argv[1:], 'hs:p:mv',
['help', 'server=', 'port=', 'mock', 'verbose'])
except getopt.GetoptError as err:
# print help informa... | Run Nutch command using REST API. | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L716-L749 | [
"def echo2(*s):\n sys.stderr.write('nutch.py: ' + ' '.join(map(str, s)) + '\\n')\n",
"def die(*s):\n echo2('Error:', *s)\n echo2(USAGE)\n sys.exit()\n",
"def create(self, command, **args):\n \"\"\"\n Create a job given a command\n :param command: Nutch command, one of nutch.LegalJobs\n ... | #!/usr/bin/env python2.7
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Vers... |
chrismattmann/nutch-python | nutch/nutch.py | Server.call | python | def call(self, verb, servicePath, data=None, headers=None, forceText=False, sendJson=True):
default_data = {} if sendJson else ""
data = data if data else default_data
headers = headers if headers else JsonAcceptHeader.copy()
if not sendJson:
headers.update(TextSendHeader)... | Call the Nutch Server, do some error checking, and return the response.
:param verb: One of nutch.RequestVerbs
:param servicePath: path component of URL to append to endpoint, e.g. '/config'
:param data: Data to attach to this request
:param headers: headers to attach to this request, d... | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L117-L170 | [
"def warn(*s):\n echo2('Warn:', *s)\n",
"def echo2(*s):\n sys.stderr.write('nutch.py: ' + ' '.join(map(str, s)) + '\\n')\n",
"def die(*s):\n echo2('Error:', *s)\n echo2(USAGE)\n sys.exit()\n"
] | class Server:
"""
Implements basic interactions with a Nutch RESTful Server
"""
def __init__(self, serverEndpoint, raiseErrors=True):
"""
Create a Server object for low-level interactions with a Nutch RESTful Server
:param serverEndpoint: URL of the server
:param raiseE... |
chrismattmann/nutch-python | nutch/nutch.py | ConfigClient.create | python | def create(self, cid, configData):
configArgs = {'configId': cid, 'params': configData, 'force': True}
cid = self.server.call('post', "/config/create", configArgs, forceText=True, headers=TextAcceptHeader)
new_config = Config(cid, self.server)
return new_config | Create a new named (cid) configuration from a parameter dictionary (config_data). | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L278-L285 | null | class ConfigClient:
def __init__(self, server):
"""Nutch Config client
List named configurations, create new ones, or delete them with methods to get the list of named
configurations, get parameters for a named configuration, get an individual parameter of a named
configuration, cre... |
chrismattmann/nutch-python | nutch/nutch.py | JobClient.list | python | def list(self, allJobs=False):
jobs = self.server.call('get', '/job')
return [Job(job['id'], self.server) for job in jobs if allJobs or self._job_owned(job)] | Return list of jobs at this endpoint.
Call get(allJobs=True) to see all jobs, not just the ones managed by this Client | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L337-L346 | null | class JobClient:
def __init__(self, server, crawlId, confId, parameters=None):
"""
Nutch Job client with methods to list, create jobs.
When the client is created, a crawlID and confID are associated.
The client will automatically filter out jobs that do not match the associated craw... |
chrismattmann/nutch-python | nutch/nutch.py | JobClient.create | python | def create(self, command, **args):
command = command.upper()
if command not in LegalJobs:
warn('Nutch command must be one of: %s' % ', '.join(LegalJobs))
else:
echo2('Starting %s job with args %s' % (command, str(args)))
parameters = self.parameters.copy()
... | Create a job given a command
:param command: Nutch command, one of nutch.LegalJobs
:param args: Additional arguments to pass to the job
:return: The created Job | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L348-L370 | [
"def warn(*s):\n echo2('Warn:', *s)\n",
"def echo2(*s):\n sys.stderr.write('nutch.py: ' + ' '.join(map(str, s)) + '\\n')\n"
] | class JobClient:
def __init__(self, server, crawlId, confId, parameters=None):
"""
Nutch Job client with methods to list, create jobs.
When the client is created, a crawlID and confID are associated.
The client will automatically filter out jobs that do not match the associated craw... |
chrismattmann/nutch-python | nutch/nutch.py | JobClient.inject | python | def inject(self, seed=None, urlDir=None, **args):
if seed:
if urlDir and urlDir != seed.seedPath:
raise NutchException("Can't specify both seed and urlDir")
urlDir = seed.seedPath
elif urlDir:
pass
else:
raise NutchException("Must ... | :param seed: A Seed object (this or urlDir must be specified)
:param urlDir: The directory on the server containing the seed list (this or urlDir must be specified)
:param args: Extra arguments for the job
:return: a created Job object | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L374-L391 | [
"def create(self, command, **args):\n \"\"\"\n Create a job given a command\n :param command: Nutch command, one of nutch.LegalJobs\n :param args: Additional arguments to pass to the job\n :return: The created Job\n \"\"\"\n\n command = command.upper()\n if command not in LegalJobs:\n ... | class JobClient:
def __init__(self, server, crawlId, confId, parameters=None):
"""
Nutch Job client with methods to list, create jobs.
When the client is created, a crawlID and confID are associated.
The client will automatically filter out jobs that do not match the associated craw... |
chrismattmann/nutch-python | nutch/nutch.py | SeedClient.create | python | def create(self, sid, seedList):
seedUrl = lambda uid, url: {"id": uid, "url": url}
if not isinstance(seedList,tuple):
seedList = (seedList,)
seedListData = {
"id": "12345",
"name": sid,
"seedUrls": [seedUrl(uid, url) for uid, url in enumerate(s... | Create a new named (sid) Seed from a list of seed URLs
:param sid: the name to assign to the new seed list
:param seedList: the list of seeds to use
:return: the created Seed object | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L419-L442 | null | class SeedClient():
def __init__(self, server):
"""Nutch Seed client
Client for uploading seed lists to Nutch
"""
self.server = server
def createFromFile(self, sid, filename):
"""
Create a new named (sid) Seed from a file containing URLs
It's assumed U... |
chrismattmann/nutch-python | nutch/nutch.py | SeedClient.createFromFile | python | def createFromFile(self, sid, filename):
urls = []
with open(filename) as f:
for line in f:
for url in line.split():
urls.append(url)
return self.create(sid, tuple(urls)) | Create a new named (sid) Seed from a file containing URLs
It's assumed URLs are whitespace seperated.
:param sid: the name to assign to the new seed list
:param filename: the name of the file that contains URLs
:return: the created Seed object | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L444-L460 | [
"def create(self, sid, seedList):\n \"\"\"\n Create a new named (sid) Seed from a list of seed URLs\n\n :param sid: the name to assign to the new seed list\n :param seedList: the list of seeds to use\n :return: the created Seed object\n \"\"\"\n\n seedUrl = lambda uid, url: {\"id\": uid, \"url\... | class SeedClient():
def __init__(self, server):
"""Nutch Seed client
Client for uploading seed lists to Nutch
"""
self.server = server
def create(self, sid, seedList):
"""
Create a new named (sid) Seed from a list of seed URLs
:param sid: the name to a... |
chrismattmann/nutch-python | nutch/nutch.py | CrawlClient._nextJob | python | def _nextJob(self, job, nextRound=True):
jobInfo = job.info()
assert jobInfo['state'] == 'FINISHED'
roundEnd = False
if jobInfo['type'] == 'INJECT':
nextCommand = 'GENERATE'
elif jobInfo['type'] == 'GENERATE':
nextCommand = 'FETCH'
elif jobInfo['... | Given a completed job, start the next job in the round, or return None
:param nextRound: whether to start jobs from the next round if the current round is completed.
:return: the newly started Job, or None if no job was started | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L492-L533 | null | class CrawlClient():
def __init__(self, server, seed, jobClient, rounds, index):
"""Nutch Crawl manager
High-level Nutch client for managing crawls.
When this client is initialized, the seedList will automatically be injected.
There are four ways to proceed from here.
prog... |
chrismattmann/nutch-python | nutch/nutch.py | CrawlClient.progress | python | def progress(self, nextRound=True):
currentJob = self.currentJob
if currentJob is None:
return currentJob
jobInfo = currentJob.info()
if jobInfo['state'] == 'RUNNING':
return currentJob
elif jobInfo['state'] == 'FINISHED':
nextJob = self._ne... | Check the status of the current job, activate the next job if it's finished, and return the active job
If the current job has failed, a NutchCrawlException will be raised with no jobs attached.
:param nextRound: whether to start jobs from the next round if the current job/round is completed.
:... | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L535-L560 | [
"def _nextJob(self, job, nextRound=True):\n \"\"\"\n Given a completed job, start the next job in the round, or return None\n\n :param nextRound: whether to start jobs from the next round if the current round is completed.\n :return: the newly started Job, or None if no job was started\n \"\"\"\n\n ... | class CrawlClient():
def __init__(self, server, seed, jobClient, rounds, index):
"""Nutch Crawl manager
High-level Nutch client for managing crawls.
When this client is initialized, the seedList will automatically be injected.
There are four ways to proceed from here.
prog... |
chrismattmann/nutch-python | nutch/nutch.py | CrawlClient.nextRound | python | def nextRound(self):
finishedJobs = []
if self.currentJob is None:
self.currentJob = self.jobClient.create('GENERATE')
activeJob = self.progress(nextRound=False)
while activeJob:
oldJob = activeJob
activeJob = self.progress(nextRound=False) # update... | Execute all jobs in the current round and return when they have finished.
If a job fails, a NutchCrawlException will be raised, with all completed jobs from this round attached
to the exception.
:return: a list of all completed Jobs | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L573-L595 | [
"def progress(self, nextRound=True):\n \"\"\"\n Check the status of the current job, activate the next job if it's finished, and return the active job\n\n If the current job has failed, a NutchCrawlException will be raised with no jobs attached.\n\n :param nextRound: whether to start jobs from the next ... | class CrawlClient():
def __init__(self, server, seed, jobClient, rounds, index):
"""Nutch Crawl manager
High-level Nutch client for managing crawls.
When this client is initialized, the seedList will automatically be injected.
There are four ways to proceed from here.
prog... |
chrismattmann/nutch-python | nutch/nutch.py | CrawlClient.waitAll | python | def waitAll(self):
finishedRounds = [self.nextRound()]
while self.currentRound < self.totalRounds:
finishedRounds.append(self.nextRound())
return finishedRounds | Execute all queued rounds and return when they have finished.
If a job fails, a NutchCrawlException will be raised, with all completed jobs attached
to the exception
:return: a list of jobs completed for each round, organized by round (list-of-lists) | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L597-L612 | [
"def nextRound(self):\n \"\"\"\n Execute all jobs in the current round and return when they have finished.\n\n If a job fails, a NutchCrawlException will be raised, with all completed jobs from this round attached\n to the exception.\n\n :return: a list of all completed Jobs\n \"\"\"\n\n finish... | class CrawlClient():
def __init__(self, server, seed, jobClient, rounds, index):
"""Nutch Crawl manager
High-level Nutch client for managing crawls.
When this client is initialized, the seedList will automatically be injected.
There are four ways to proceed from here.
prog... |
chrismattmann/nutch-python | nutch/nutch.py | Nutch.Jobs | python | def Jobs(self, crawlId=None):
crawlId = crawlId if crawlId else defaultCrawlId()
return JobClient(self.server, crawlId, self.confId) | Create a JobClient for listing and creating jobs.
The JobClient inherits the confId from the Nutch client.
:param crawlId: crawlIds to use for this client. If not provided, will be generated
by nutch.defaultCrawlId()
:return: a JobClient | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L656-L666 | [
"def defaultCrawlId():\n \"\"\"\n Provide a reasonable default crawl name using the user name and date\n \"\"\"\n\n timestamp = datetime.now().isoformat().replace(':', '_')\n user = getuser()\n return '_'.join(('crawl', user, timestamp))\n"
] | class Nutch:
def __init__(self, confId=DefaultConfig, serverEndpoint=DefaultServerEndpoint, raiseErrors=True, **args):
'''
Nutch client for interacting with a Nutch instance over its REST API.
Constructor:
nt = Nutch()
Optional arguments:
confID - The name of the ... |
chrismattmann/nutch-python | nutch/nutch.py | Nutch.Crawl | python | def Crawl(self, seed, seedClient=None, jobClient=None, rounds=1, index=True):
if seedClient is None:
seedClient = self.Seeds()
if jobClient is None:
jobClient = self.Jobs()
if type(seed) != Seed:
seed = seedClient.create(jobClient.crawlId + '_seeds', seed)
... | Launch a crawl using the given seed
:param seed: Type (Seed or SeedList) - used for crawl
:param seedClient: if a SeedList is given, the SeedClient to upload, if None a default will be created
:param jobClient: the JobClient to be used, if None a default will be created
:param rounds: th... | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/nutch.py#L677-L693 | [
"def create(self, sid, seedList):\n \"\"\"\n Create a new named (sid) Seed from a list of seed URLs\n\n :param sid: the name to assign to the new seed list\n :param seedList: the list of seeds to use\n :return: the created Seed object\n \"\"\"\n\n seedUrl = lambda uid, url: {\"id\": uid, \"url\... | class Nutch:
def __init__(self, confId=DefaultConfig, serverEndpoint=DefaultServerEndpoint, raiseErrors=True, **args):
'''
Nutch client for interacting with a Nutch instance over its REST API.
Constructor:
nt = Nutch()
Optional arguments:
confID - The name of the ... |
chrismattmann/nutch-python | nutch/crawl.py | Crawler.crawl_cmd | python | def crawl_cmd(self, seed_list, n):
'''
Runs the crawl job for n rounds
:param seed_list: lines of seed URLs
:param n: number of rounds
:return: number of successful rounds
'''
print("Num Rounds "+str(n))
cc = self.proxy.Crawl(seed=seed_list, rounds=n)
... | Runs the crawl job for n rounds
:param seed_list: lines of seed URLs
:param n: number of rounds
:return: number of successful rounds | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/crawl.py#L38-L51 | [
"def Crawl(self, seed, seedClient=None, jobClient=None, rounds=1, index=True):\n \"\"\"\n Launch a crawl using the given seed\n :param seed: Type (Seed or SeedList) - used for crawl\n :param seedClient: if a SeedList is given, the SeedClient to upload, if None a default will be created\n :param jobCl... | class Crawler(object):
def __init__(self, args):
self.args = args
self.server_url = args['url'] if 'url' in args else nutch.DefaultServerEndpoint
self.conf_id = args['conf_id'] if 'conf_id' in args else nutch.DefaultConfig
self.proxy = nutch.Nutch(self.conf_id, self.server_url)
... |
chrismattmann/nutch-python | nutch/crawl.py | Crawler.load_xml_conf | python | def load_xml_conf(self, xml_file, id):
'''
Creates a new config from xml file.
:param xml_file: path to xml file. Format : nutch-site.xml or nutch-default.xml
:param id:
:return: config object
'''
# converting nutch-site.xml to key:value pairs
import xml.... | Creates a new config from xml file.
:param xml_file: path to xml file. Format : nutch-site.xml or nutch-default.xml
:param id:
:return: config object | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/crawl.py#L53-L67 | null | class Crawler(object):
def __init__(self, args):
self.args = args
self.server_url = args['url'] if 'url' in args else nutch.DefaultServerEndpoint
self.conf_id = args['conf_id'] if 'conf_id' in args else nutch.DefaultConfig
self.proxy = nutch.Nutch(self.conf_id, self.server_url)
... |
chrismattmann/nutch-python | nutch/crawl.py | Crawler.create_cmd | python | def create_cmd(self, args):
'''
'create' sub-command
:param args: cli arguments
:return:
'''
cmd = args.get('cmd_create')
if cmd == 'conf':
conf_file = args['conf_file']
conf_id = args['id']
return self.load_xml_conf(conf_file, ... | 'create' sub-command
:param args: cli arguments
:return: | train | https://github.com/chrismattmann/nutch-python/blob/07ae182e283b2f74ef062ddfa20a690a59ab6f5a/nutch/crawl.py#L70-L82 | [
"def load_xml_conf(self, xml_file, id):\n '''\n Creates a new config from xml file.\n :param xml_file: path to xml file. Format : nutch-site.xml or nutch-default.xml\n :param id:\n :return: config object\n '''\n\n # converting nutch-site.xml to key:value pairs\n import xml.etree.ElementTree ... | class Crawler(object):
def __init__(self, args):
self.args = args
self.server_url = args['url'] if 'url' in args else nutch.DefaultServerEndpoint
self.conf_id = args['conf_id'] if 'conf_id' in args else nutch.DefaultConfig
self.proxy = nutch.Nutch(self.conf_id, self.server_url)
... |
tbielawa/bitmath | bitmath/integrations.py | BitmathType | python | def BitmathType(bmstring):
try:
argvalue = bitmath.parse_string(bmstring)
except ValueError:
raise argparse.ArgumentTypeError("'%s' can not be parsed into a valid bitmath object" %
bmstring)
else:
return argvalue | An 'argument type' for integrations with the argparse module.
For more information, see
https://docs.python.org/2/library/argparse.html#type Of particular
interest to us is this bit:
``type=`` can take any callable that takes a single string
argument and returns the converted value
I.e., ``type`` can be a func... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/integrations.py#L33-L80 | [
"def parse_string(s):\n \"\"\"Parse a string with units and try to make a bitmath object out of\nit.\n\nString inputs may include whitespace characters between the value and\nthe unit.\n \"\"\"\n # Strings only please\n if not isinstance(s, (str, unicode)):\n raise ValueError(\"parse_string only ... | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/integrations.py | BitmathFileTransferSpeed.update | python | def update(self, pbar):
if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6:
scaled = bitmath.Byte()
else:
speed = pbar.currval / pbar.seconds_elapsed
scaled = bitmath.Byte(speed).best_prefix(system=self.system)
return scaled.format(self.format) | Updates the widget with the current NIST/SI speed.
Basically, this calculates the average rate of update and figures out
how to make a "pretty" prefix unit | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/integrations.py#L92-L104 | [
" def format(self, fmt):\n \"\"\"Return a representation of this instance formatted with user\nsupplied syntax\"\"\"\n _fmt_params = {\n 'base': self.base,\n 'bin': self.bin,\n 'binary': self.binary,\n 'bits': self.bits,\n 'bytes': self.bytes,\... | class BitmathFileTransferSpeed(progressbar.widgets.Widget):
"""Widget for showing the transfer speed (useful for file transfers)."""
__slots__ = ('system', 'format')
def __init__(self, system=bitmath.NIST, format="{value:.2f} {unit}/s"):
self.system = system
self.format = format
|
tbielawa/bitmath | bitmath/__init__.py | best_prefix | python | def best_prefix(bytes, system=NIST):
if isinstance(bytes, Bitmath):
value = bytes.bytes
else:
value = bytes
return Byte(value).best_prefix(system=system) | Return a bitmath instance representing the best human-readable
representation of the number of bytes given by ``bytes``. In addition
to a numeric type, the ``bytes`` parameter may also be a bitmath type.
Optionally select a preferred unit system by specifying the ``system``
keyword. Choices for ``system`` are ``bitmat... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1174-L1198 | [
" def best_prefix(self, system=None):\n \"\"\"Optional parameter, `system`, allows you to prefer NIST or SI in\nthe results. By default, the current system is used (Bit/Byte default\nto NIST).\n\nLogic discussion/notes:\n\nBase-case, does it need converting?\n\nIf the instance is less than one Byte, retur... | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/__init__.py | query_device_capacity | python | def query_device_capacity(device_fd):
if os_name() != 'posix':
raise NotImplementedError("'bitmath.query_device_capacity' is not supported on this platform: %s" % os_name())
s = os.stat(device_fd.name).st_mode
if not stat.S_ISBLK(s):
raise ValueError("The file descriptor provided is not of ... | Create bitmath instances of the capacity of a system block device
Make one or more ioctl request to query the capacity of a block
device. Perform any processing required to compute the final capacity
value. Return the device capacity in bytes as a :class:`bitmath.Byte`
instance.
Thanks to the following resources for ... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1201-L1331 | [
"def os_name():\n # makes unittesting platform specific code easier\n return os.name\n"
] | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/__init__.py | getsize | python | def getsize(path, bestprefix=True, system=NIST):
_path = os.path.realpath(path)
size_bytes = os.path.getsize(_path)
if bestprefix:
return Byte(size_bytes).best_prefix(system=system)
else:
return Byte(size_bytes) | Return a bitmath instance in the best human-readable representation
of the file size at `path`. Optionally, provide a preferred unit
system by setting `system` to either `bitmath.NIST` (default) or
`bitmath.SI`.
Optionally, set ``bestprefix`` to ``False`` to get ``bitmath.Byte``
instances back. | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1334-L1348 | [
" def best_prefix(self, system=None):\n \"\"\"Optional parameter, `system`, allows you to prefer NIST or SI in\nthe results. By default, the current system is used (Bit/Byte default\nto NIST).\n\nLogic discussion/notes:\n\nBase-case, does it need converting?\n\nIf the instance is less than one Byte, retur... | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/__init__.py | listdir | python | def listdir(search_base, followlinks=False, filter='*',
relpath=False, bestprefix=False, system=NIST):
for root, dirs, files in os.walk(search_base, followlinks=followlinks):
for name in fnmatch.filter(files, filter):
_path = os.path.join(root, name)
if relpath:
... | This is a generator which recurses the directory tree
`search_base`, yielding 2-tuples of:
* The absolute/relative path to a discovered file
* A bitmath instance representing the "apparent size" of the file.
- `search_base` - The directory to begin walking down.
- `followlinks` - Whether or not to follow symb... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1351-L1391 | [
"def getsize(path, bestprefix=True, system=NIST):\n \"\"\"Return a bitmath instance in the best human-readable representation\nof the file size at `path`. Optionally, provide a preferred unit\nsystem by setting `system` to either `bitmath.NIST` (default) or\n`bitmath.SI`.\n\nOptionally, set ``bestprefix`` to ``F... | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/__init__.py | parse_string | python | def parse_string(s):
# Strings only please
if not isinstance(s, (str, unicode)):
raise ValueError("parse_string only accepts string inputs but a %s was given" %
type(s))
# get the index of the first alphabetic character
try:
index = list([i.isalpha() for i in s]... | Parse a string with units and try to make a bitmath object out of
it.
String inputs may include whitespace characters between the value and
the unit. | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1394-L1434 | null | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/__init__.py | parse_string_unsafe | python | def parse_string_unsafe(s, system=SI):
if not isinstance(s, (str, unicode)) and \
not isinstance(s, numbers.Number):
raise ValueError("parse_string_unsafe only accepts string/number inputs but a %s was given" %
type(s))
###################################################... | Attempt to parse a string with ambiguous units and try to make a
bitmath object out of it.
This may produce inaccurate results if parsing shell output. For
example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB
~= 2.666 KiB. See the documentation for all of the important details.
Note the following ca... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1437-L1559 | [
"def capitalize_first(s):\n \"\"\"Capitalize ONLY the first letter of the input `s`\n\n* returns a copy of input `s` with the first letter capitalized\n \"\"\"\n pfx = s[0].upper()\n _s = s[1:]\n return pfx + _s\n"
] | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/__init__.py | format | python | def format(fmt_str=None, plural=False, bestprefix=False):
if 'bitmath' not in globals():
import bitmath
if plural:
orig_fmt_plural = bitmath.format_plural
bitmath.format_plural = True
if fmt_str:
orig_fmt_str = bitmath.format_string
bitmath.format_string = fmt_str
... | Context manager for printing bitmath instances.
``fmt_str`` - a formatting mini-language compat formatting string. See
the @properties (above) for a list of available items.
``plural`` - True enables printing instances with 's's if they're
plural. False (default) prints them as singular (no trailing 's').
``bestpref... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1565-L1595 | null | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/__init__.py | cli_script_main | python | def cli_script_main(cli_args):
choices = ALL_UNIT_TYPES
parser = argparse.ArgumentParser(
description='Converts from one type of size to another.')
parser.add_argument('--from-stdin', default=False, action='store_true',
help='Reads number from stdin rather than the cli')
... | A command line interface to basic bitmath operations. | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1598-L1643 | null | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright © 2014-2016 Tim Bielawa <timbielawa@gmail.com>
# See GitHub Contributors Graph for more information
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to ... |
tbielawa/bitmath | bitmath/__init__.py | Bitmath._do_setup | python | def _do_setup(self):
(self._base, self._power, self._name_singular, self._name_plural) = self._setup()
self._unit_value = self._base ** self._power | Setup basic parameters for this class.
`base` is the numeric base which when raised to `power` is equivalent
to 1 unit of the corresponding prefix. I.e., base=2, power=10
represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte.
Likewise, for the SI prefix classes `base` will be 10, and the `power`
for the Kil... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L239-L250 | [
"def _setup(self):\n raise NotImplementedError(\"The base 'bitmath.Bitmath' class can not be used directly\")\n"
] | class Bitmath(object):
"""The base class for all the other prefix classes"""
# All the allowed input types
valid_types = (int, float, long)
def __init__(self, value=0, bytes=None, bits=None):
"""Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
... |
tbielawa/bitmath | bitmath/__init__.py | Bitmath._norm | python | def _norm(self, value):
if isinstance(value, self.valid_types):
self._byte_value = value * self._unit_value
self._bit_value = self._byte_value * 8.0
else:
raise ValueError("Initialization value '%s' is of an invalid type: %s. "
"Must be on... | Normalize the input value into the fundamental unit for this prefix
type.
:param number value: The input value to be normalized
:raises ValueError: if the input value is not a type of real number | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L252-L267 | null | class Bitmath(object):
"""The base class for all the other prefix classes"""
# All the allowed input types
valid_types = (int, float, long)
def __init__(self, value=0, bytes=None, bits=None):
"""Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
... |
tbielawa/bitmath | bitmath/__init__.py | Bitmath.system | python | def system(self):
if self._base == 2:
return "NIST"
elif self._base == 10:
return "SI"
else:
# I don't expect to ever encounter this logic branch, but
# hey, it's better to have extra test coverage than
# insufficient test coverage.
... | The system of units used to measure an instance | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L299-L310 | null | class Bitmath(object):
"""The base class for all the other prefix classes"""
# All the allowed input types
valid_types = (int, float, long)
def __init__(self, value=0, bytes=None, bits=None):
"""Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
... |
tbielawa/bitmath | bitmath/__init__.py | Bitmath.unit | python | def unit(self):
global format_plural
if self.prefix_value == 1:
# If it's a '1', return it singular, no matter what
return self._name_singular
elif format_plural:
# Pluralization requested
return self._name_plural
else:
# Plura... | The string that is this instances prefix unit name in agreement
with this instance value (singular or plural). Following the
convention that only 1 is singular. This will always be the singular
form when :attr:`bitmath.format_plural` is ``False`` (default value).
For example:
>>> KiB(1).unit == 'KiB'
>>> Byte(0... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L313-L338 | null | class Bitmath(object):
"""The base class for all the other prefix classes"""
# All the allowed input types
valid_types = (int, float, long)
def __init__(self, value=0, bytes=None, bits=None):
"""Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
... |
tbielawa/bitmath | bitmath/__init__.py | Bitmath.from_other | python | def from_other(cls, item):
if isinstance(item, Bitmath):
return cls(bits=item.bits)
else:
raise ValueError("The provided items must be a valid bitmath class: %s" %
str(item.__class__)) | Factory function to return instances of `item` converted into a new
instance of ``cls``. Because this is a class method, it may be called
from any bitmath class object without the need to explicitly
instantiate the class ahead of time.
*Implicit Parameter:*
* ``cls`` A bitmath class, implicitly set to the class of th... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L371-L398 | null | class Bitmath(object):
"""The base class for all the other prefix classes"""
# All the allowed input types
valid_types = (int, float, long)
def __init__(self, value=0, bytes=None, bits=None):
"""Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
... |
tbielawa/bitmath | bitmath/__init__.py | Bitmath.format | python | def format(self, fmt):
_fmt_params = {
'base': self.base,
'bin': self.bin,
'binary': self.binary,
'bits': self.bits,
'bytes': self.bytes,
'power': self.power,
'system': self.system,
'unit': self.unit,
'un... | Return a representation of this instance formatted with user
supplied syntax | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L416-L433 | null | class Bitmath(object):
"""The base class for all the other prefix classes"""
# All the allowed input types
valid_types = (int, float, long)
def __init__(self, value=0, bytes=None, bits=None):
"""Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
... |
tbielawa/bitmath | bitmath/__init__.py | Bitmath.best_prefix | python | def best_prefix(self, system=None):
# Use absolute value so we don't return Bit's for *everything*
# less than Byte(1). From github issue #55
if abs(self) < Byte(1):
return Bit.from_other(self)
else:
if type(self) is Byte: # pylint: disable=unidiomatic-typecheck... | Optional parameter, `system`, allows you to prefer NIST or SI in
the results. By default, the current system is used (Bit/Byte default
to NIST).
Logic discussion/notes:
Base-case, does it need converting?
If the instance is less than one Byte, return the instance as a Bit
instance.
Else, begin by recording the unit... | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L439-L528 | [
" def from_other(cls, item):\n \"\"\"Factory function to return instances of `item` converted into a new\ninstance of ``cls``. Because this is a class method, it may be called\nfrom any bitmath class object without the need to explicitly\ninstantiate the class ahead of time.\n\n*Implicit Parameter:*\n\n* ... | class Bitmath(object):
"""The base class for all the other prefix classes"""
# All the allowed input types
valid_types = (int, float, long)
def __init__(self, value=0, bytes=None, bits=None):
"""Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
... |
tbielawa/bitmath | bitmath/__init__.py | Bit._norm | python | def _norm(self, value):
self._bit_value = value * self._unit_value
self._byte_value = self._bit_value / 8.0 | Normalize the input value into the fundamental unit for this prefix
type | train | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1091-L1095 | null | class Bit(Bitmath):
"""Bit based types fundamentally operate on self._bit_value"""
def _set_prefix_value(self):
self.prefix_value = self._to_prefix_value(self._bit_value)
def _setup(self):
return (2, 0, 'Bit', 'Bits')
|
disqus/nydus | nydus/db/routers/keyvalue.py | ConsistentHashingRouter._route | python | def _route(self, attr, args, kwargs, **fkwargs):
key = get_key(args, kwargs)
found = self._hash.get_node(key)
if not found and len(self._down_connections) > 0:
raise self.HostListExhausted()
return [i for i, h in self.cluster.hosts.iteritems()
if h.identif... | The first argument is assumed to be the ``key`` for routing. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/keyvalue.py#L66-L79 | null | class ConsistentHashingRouter(RoundRobinRouter):
"""
Router that returns host number based on a consistent hashing algorithm.
The consistent hashing algorithm only works if a key argument is provided.
If a key is not provided, then all hosts are returned.
The first argument is assumed to be the ``... |
disqus/nydus | nydus/db/routers/keyvalue.py | PartitionRouter._route | python | def _route(self, attr, args, kwargs, **fkwargs):
key = get_key(args, kwargs)
return [crc32(str(key)) % len(self.cluster)] | The first argument is assumed to be the ``key`` for routing. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/keyvalue.py#L84-L90 | null | class PartitionRouter(BaseRouter):
@routing_params
|
disqus/nydus | nydus/db/promise.py | promise_method | python | def promise_method(func):
name = func.__name__
@wraps(func)
def wrapped(self, *args, **kwargs):
cls_name = type(self).__name__
if getattr(self, '_%s__resolved' % (cls_name,)):
return getattr(getattr(self, '_%s__wrapped' % (cls_name,)), name)(*args, **kwargs)
return func(... | A decorator which ensures that once a method has been marked as resolved
(via Class.__resolved)) will then propagate the attribute (function) call
upstream. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/promise.py#L13-L27 | null | """
nydus.db.promise
~~~~~~~~~~~~~~~~
:copyright: (c) 2011 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from nydus.db.exceptions import CommandError
from functools import wraps
def change_resolution(command, value):
"""
Public API to change the resolution of an already resolved E... |
disqus/nydus | nydus/db/base.py | BaseCluster.get_conn | python | def get_conn(self, *args, **kwargs):
connections = self.__connections_for('get_conn', args=args, kwargs=kwargs)
if len(connections) is 1:
return connections[0]
else:
return connections | Returns a connection object from the router given ``args``.
Useful in cases where a connection cannot be automatically determined
during all steps of the process. An example of this would be
Redis pipelines. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/base.py#L100-L113 | null | class BaseCluster(object):
"""
Holds a cluster of connections.
"""
class MaxRetriesExceededError(Exception):
pass
def __init__(self, hosts, backend, router=BaseRouter, max_connection_retries=20, defaults=None):
self.hosts = dict(
(conn_number, create_connection(backend, ... |
disqus/nydus | nydus/db/routers/base.py | BaseRouter.get_dbs | python | def get_dbs(self, attr, args, kwargs, **fkwargs):
if not self._ready:
if not self.setup_router(args=args, kwargs=kwargs, **fkwargs):
raise self.UnableToSetupRouter()
retval = self._pre_routing(attr=attr, args=args, kwargs=kwargs, **fkwargs)
if retval is not None:
... | Returns a list of db keys to route the given call to.
:param attr: Name of attribute being called on the connection.
:param args: List of arguments being passed to ``attr``.
:param kwargs: Dictionary of keyword arguments being passed to ``attr``.
>>> redis = Cluster(router=BaseRouter)
... | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/base.py#L50-L81 | [
"def _handle_exception(self, e):\n \"\"\"\n Handle/transform exceptions and return it\n \"\"\"\n raise e\n"
] | class BaseRouter(object):
"""
Handles routing requests to a specific connection in a single cluster.
For the most part, all public functions will receive arguments as ``key=value``
pairs and should expect as much. Functions which receive ``args`` and ``kwargs``
from the calling function will receiv... |
disqus/nydus | nydus/db/routers/base.py | BaseRouter.setup_router | python | def setup_router(self, args, kwargs, **fkwargs):
self._ready = self._setup_router(args=args, kwargs=kwargs, **fkwargs)
return self._ready | Call method to perform any setup | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/base.py#L87-L93 | null | class BaseRouter(object):
"""
Handles routing requests to a specific connection in a single cluster.
For the most part, all public functions will receive arguments as ``key=value``
pairs and should expect as much. Functions which receive ``args`` and ``kwargs``
from the calling function will receiv... |
disqus/nydus | nydus/db/routers/base.py | BaseRouter._route | python | def _route(self, attr, args, kwargs, **fkwargs):
return self.cluster.hosts.keys() | Perform routing and return db_nums | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/base.py#L111-L115 | null | class BaseRouter(object):
"""
Handles routing requests to a specific connection in a single cluster.
For the most part, all public functions will receive arguments as ``key=value``
pairs and should expect as much. Functions which receive ``args`` and ``kwargs``
from the calling function will receiv... |
disqus/nydus | nydus/db/routers/base.py | RoundRobinRouter.check_down_connections | python | def check_down_connections(self):
now = time.time()
for db_num, marked_down_at in self._down_connections.items():
if marked_down_at + self.retry_timeout <= now:
self.mark_connection_up(db_num) | Iterates through all connections which were previously listed as unavailable
and marks any that have expired their retry_timeout as being up. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/base.py#L175-L184 | null | class RoundRobinRouter(BaseRouter):
"""
Basic retry router that performs round robin
"""
# Raised if all hosts in the hash have been marked as down
class HostListExhausted(Exception):
pass
class InvalidDBNum(Exception):
pass
# If this router can be retried on if a particul... |
disqus/nydus | nydus/db/routers/base.py | RoundRobinRouter.flush_down_connections | python | def flush_down_connections(self):
self._get_db_attempts = 0
for db_num in self._down_connections.keys():
self.mark_connection_up(db_num) | Marks all connections which were previously listed as unavailable as being up. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/base.py#L186-L192 | [
"def mark_connection_up(self, db_num):\n db_num = self.ensure_db_num(db_num)\n self._down_connections.pop(db_num, None)\n"
] | class RoundRobinRouter(BaseRouter):
"""
Basic retry router that performs round robin
"""
# Raised if all hosts in the hash have been marked as down
class HostListExhausted(Exception):
pass
class InvalidDBNum(Exception):
pass
# If this router can be retried on if a particul... |
disqus/nydus | nydus/contrib/ketama.py | Ketama._build_circle | python | def _build_circle(self):
total_weight = 0
for node in self._nodes:
total_weight += self._weights.get(node, 1)
for node in self._nodes:
weight = self._weights.get(node, 1)
ks = math.floor((40 * len(self._nodes) * weight) / total_weight)
for i in ... | Creates hash ring. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/contrib/ketama.py#L35-L60 | [
"def _md5_digest(self, key):\n return map(ord, hashlib.md5(key).digest())\n"
] | class Ketama(object):
def __init__(self, nodes=None, weights=None):
"""
nodes - List of nodes(strings)
weights - Dictionary of node wheights where keys are nodes names.
if not set, all nodes will be equal.
"""
self._hashring = dict()
s... |
disqus/nydus | nydus/contrib/ketama.py | Ketama._get_node_pos | python | def _get_node_pos(self, key):
if not self._hashring:
return None
key = self._gen_key(key)
nodes = self._sorted_keys
pos = bisect(nodes, key)
if pos == len(nodes):
return 0
return pos | Return node position(integer) for a given key. Else return None | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/contrib/ketama.py#L62-L76 | [
"def _gen_key(self, key):\n \"\"\"\n Return long integer for a given key, that represent it place on\n the hash ring.\n \"\"\"\n b_key = self._md5_digest(key)\n return self._hashi(b_key, lambda x: x)\n"
] | class Ketama(object):
def __init__(self, nodes=None, weights=None):
"""
nodes - List of nodes(strings)
weights - Dictionary of node wheights where keys are nodes names.
if not set, all nodes will be equal.
"""
self._hashring = dict()
s... |
disqus/nydus | nydus/contrib/ketama.py | Ketama._gen_key | python | def _gen_key(self, key):
b_key = self._md5_digest(key)
return self._hashi(b_key, lambda x: x) | Return long integer for a given key, that represent it place on
the hash ring. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/contrib/ketama.py#L78-L84 | [
"def _hashi(self, b_key, fn):\n return ((b_key[fn(3)] << 24)\n | (b_key[fn(2)] << 16)\n | (b_key[fn(1)] << 8)\n | b_key[fn(0)])\n",
"def _md5_digest(self, key):\n return map(ord, hashlib.md5(key).digest())\n"
] | class Ketama(object):
def __init__(self, nodes=None, weights=None):
"""
nodes - List of nodes(strings)
weights - Dictionary of node wheights where keys are nodes names.
if not set, all nodes will be equal.
"""
self._hashring = dict()
s... |
disqus/nydus | nydus/contrib/ketama.py | Ketama.remove_node | python | def remove_node(self, node):
try:
self._nodes.remove(node)
del self._weights[node]
except (KeyError, ValueError):
pass
self._hashring = dict()
self._sorted_keys = []
self._build_circle() | Removes node from circle and rebuild it. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/contrib/ketama.py#L95-L107 | [
"def _build_circle(self):\n \"\"\"\n Creates hash ring.\n \"\"\"\n total_weight = 0\n for node in self._nodes:\n total_weight += self._weights.get(node, 1)\n\n for node in self._nodes:\n weight = self._weights.get(node, 1)\n\n ks = math.floor((40 * len(self._nodes) * weigh... | class Ketama(object):
def __init__(self, nodes=None, weights=None):
"""
nodes - List of nodes(strings)
weights - Dictionary of node wheights where keys are nodes names.
if not set, all nodes will be equal.
"""
self._hashring = dict()
s... |
disqus/nydus | nydus/contrib/ketama.py | Ketama.add_node | python | def add_node(self, node, weight=1):
self._nodes.add(node)
self._weights[node] = weight
self._hashring = dict()
self._sorted_keys = []
self._build_circle() | Adds node to circle and rebuild it. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/contrib/ketama.py#L109-L118 | [
"def _build_circle(self):\n \"\"\"\n Creates hash ring.\n \"\"\"\n total_weight = 0\n for node in self._nodes:\n total_weight += self._weights.get(node, 1)\n\n for node in self._nodes:\n weight = self._weights.get(node, 1)\n\n ks = math.floor((40 * len(self._nodes) * weigh... | class Ketama(object):
def __init__(self, nodes=None, weights=None):
"""
nodes - List of nodes(strings)
weights - Dictionary of node wheights where keys are nodes names.
if not set, all nodes will be equal.
"""
self._hashring = dict()
s... |
disqus/nydus | nydus/db/__init__.py | create_cluster | python | def create_cluster(settings):
# Pull in our client
settings = copy.deepcopy(settings)
backend = settings.pop('engine', settings.pop('backend', None))
if isinstance(backend, basestring):
Conn = import_string(backend)
elif backend:
Conn = backend
else:
raise KeyError('backe... | Creates a new Nydus cluster from the given settings.
:param settings: Dictionary of the cluster settings.
:returns: Configured instance of ``nydus.db.base.Cluster``.
>>> redis = create_cluster({
>>> 'backend': 'nydus.db.backends.redis.Redis',
>>> 'router': 'nydus.db.routers.redis.Partition... | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/__init__.py#L28-L82 | [
"def import_string(import_name, silent=False):\n \"\"\"Imports an object based on a string. If *silent* is True the return\n value will be None if the import fails.\n\n Simplified version of the function with same name from `Werkzeug`_.\n\n :param import_name:\n The dotted name for the object to ... | """
nydus.db
~~~~~~~~
Disqus generic connections wrappers.
>>> from nydus.db import create_cluster
>>> redis = create_cluster({
>>> 'backend': 'nydus.db.backends.redis.Redis',
>>> })
>>> res = conn.incr('foo')
>>> assert res == 1
:copyright: (c) 2011-2012 DISQUS.
:license: Apache License 2.0, see LICENSE for mor... |
disqus/nydus | nydus/db/backends/memcache.py | grouped_command | python | def grouped_command(commands):
base = commands[0]
name = base.get_name()
multi_command = EventualCommand('%s_multi' % name)
if name in ('get', 'delete'):
args = [c.get_args()[0] for c in commands]
elif base.get_name() == 'set':
args = dict(c.get_args()[0:2] for c in commands)
els... | Given a list of commands (which are assumed groupable), return
a new command which is a batch (multi) command.
For ``set`` commands the outcome will be::
set_multi({key: value}, **kwargs)
For ``get`` and ``delete`` commands, the outcome will be::
get_multi(list_of_keys, **kwargs)
(O... | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/backends/memcache.py#L67-L94 | [
"def grouped_args_for_command(command):\n \"\"\"\n Returns a list of arguments that are shared for this command.\n\n When comparing similar commands, these arguments represent the\n groupable signature for said commands.\n \"\"\"\n if command.get_name() == 'set':\n return command.get_args()... | """
nydus.db.backends.memcache
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from __future__ import absolute_import
import pylibmc
from itertools import izip
from nydus.db.backends import BaseConnection, BasePipeline
from nydus.db.promise imp... |
disqus/nydus | nydus/db/backends/memcache.py | can_group_commands | python | def can_group_commands(command, next_command):
multi_capable_commands = ('get', 'set', 'delete')
if next_command is None:
return False
name = command.get_name()
# TODO: support multi commands
if name not in multi_capable_commands:
return False
if name != next_command.get_name... | Returns a boolean representing whether these commands can be
grouped together or not.
A few things are taken into account for this decision:
For ``set`` commands:
- Are all arguments other than the key/value the same?
For ``delete`` and ``get`` commands:
- Are all arguments other than the k... | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/backends/memcache.py#L97-L135 | [
"def grouped_args_for_command(command):\n \"\"\"\n Returns a list of arguments that are shared for this command.\n\n When comparing similar commands, these arguments represent the\n groupable signature for said commands.\n \"\"\"\n if command.get_name() == 'set':\n return command.get_args()... | """
nydus.db.backends.memcache
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from __future__ import absolute_import
import pylibmc
from itertools import izip
from nydus.db.backends import BaseConnection, BasePipeline
from nydus.db.promise imp... |
disqus/nydus | nydus/db/backends/memcache.py | regroup_commands | python | def regroup_commands(commands):
grouped = []
pending = []
def group_pending():
if not pending:
return
new_command = grouped_command(pending)
result = []
while pending:
result.append(pending.pop(0))
grouped.append((new_command, result))
f... | Returns a list of tuples:
[(command_to_run, [list, of, commands])]
If the list of commands has a single item, the command was not grouped. | train | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/backends/memcache.py#L138-L182 | [
"def peek(value):\n generator = iter(value)\n prev = generator.next()\n for item in generator:\n yield prev, item\n prev = item\n yield prev, None\n",
"def can_group_commands(command, next_command):\n \"\"\"\n Returns a boolean representing whether these commands can be\n groupe... | """
nydus.db.backends.memcache
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from __future__ import absolute_import
import pylibmc
from itertools import izip
from nydus.db.backends import BaseConnection, BasePipeline
from nydus.db.promise imp... |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | connector.getConnectorVersion | python | def getConnectorVersion(self):
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result | GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult | train | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L72-L87 | [
"def fill(self, data):\n\tif type(data) == r.models.Response:\n\t\ttry:\n\t\t\tself.result = json.loads(data.content)\n\t\texcept:\n\t\t\tself.result = []\n\t\t\tif isinstance(data.content,str): # string handler\n\t\t\t\tself.result = data.content\n\t\t\telif isinstance(data.content,int): # int handler\n\t\t\t\ts... | class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
# Return API version of connector
def getA... |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | connector.getEndpoints | python | def getEndpoints(self,typeOfEndpoint=""):
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = respo... | Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult | train | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L126-L146 | [
"def fill(self, data):\n\tif type(data) == r.models.Response:\n\t\ttry:\n\t\t\tself.result = json.loads(data.content)\n\t\texcept:\n\t\t\tself.result = []\n\t\t\tif isinstance(data.content,str): # string handler\n\t\t\t\tself.result = data.content\n\t\t\telif isinstance(data.content,int): # int handler\n\t\t\t\ts... | class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET th... |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | connector.getResources | python | def getResources(self,ep,noResp=False,cacheOnly=False):
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make quer... | Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult | train | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L149-L178 | [
"def fill(self, data):\n\tif type(data) == r.models.Response:\n\t\ttry:\n\t\t\tself.result = json.loads(data.content)\n\t\texcept:\n\t\t\tself.result = []\n\t\t\tif isinstance(data.content,str): # string handler\n\t\t\t\tself.result = data.content\n\t\t\telif isinstance(data.content,int): # int handler\n\t\t\t\ts... | class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET th... |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | connector.getResourceValue | python | def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if c... | Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - g... | train | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L182-L217 | [
"def fill(self, data):\n\tif type(data) == r.models.Response:\n\t\ttry:\n\t\t\tself.result = json.loads(data.content)\n\t\texcept:\n\t\t\tself.result = []\n\t\t\tif isinstance(data.content,str): # string handler\n\t\t\t\tself.result = data.content\n\t\t\telif isinstance(data.content,int): # int handler\n\t\t\t\ts... | class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET th... |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | connector.putResourceValue | python | def putResourceValue(self,ep,res,data,cbfn=""):
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
... | Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rty... | train | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L220-L245 | [
"def _putURL(self, url,payload=None,versioned=True):\n\tif self._isJSON(payload):\n\t\tself.log.debug(\"PUT payload is json\")\n\t\tif versioned:\n\t\t\treturn r.put(self.address+self.apiVersion+url,json=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\t\telse:\n\t\t\treturn r.put(self.address+url,jso... | class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET th... |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | connector.deleteEndpoint | python | def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = as... | Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | train | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L276-L298 | [
"def _deleteURL(self, url,versioned=True):\n\tif versioned:\n\t\treturn r.delete(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\telse:\n\t\treturn r.delete(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer})\n"
] | class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET th... |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | connector.deleteEndpointSubscriptions | python | def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("... | Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | train | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L329-L348 | [
"def _deleteURL(self, url,versioned=True):\n\tif versioned:\n\t\treturn r.delete(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\telse:\n\t\treturn r.delete(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer})\n"
] | class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET th... |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | connector.deleteAllSubscriptions | python | def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #i... | Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult | train | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L373-L390 | [
"def _deleteURL(self, url,versioned=True):\n\tif versioned:\n\t\treturn r.delete(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\telse:\n\t\treturn r.delete(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer})\n"
] | class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.