rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
x, y = map(float, e.split('|')) | x, y = [float(x) for x in e.split('|')] | def map(e, params): x, y = map(float, e.split('|')) return [(mod1.plusceil(x, y) + math.ceil(1.5), '')] |
except (httplib.HTTPException, httplib.socket.error), e: status = httplib.SERVICE_UNAVAILABLE | errmsg = response.reason except httplib.HTTPException, e: status = None errmsg = str(e) or repr(e) except (httplib.socket.error, socket.error), e: status = None errmsg = e if isinstance(e, basestring) else e[1] | def request(method, url, data=None, headers={}, sleep=0): scheme, netloc, path = urlsplit(urlresolve(url)) try: conn = HTTPConnection(str(netloc)) conn.request(method, '/%s' % path, body=data, headers=headers) response = conn.getresponse() status = response.status except (httplib.HTTPException, httplib.socket.error), ... |
if isunavailable(status): | if not status or isunavailable(status): | def request(method, url, data=None, headers={}, sleep=0): scheme, netloc, path = urlsplit(urlresolve(url)) try: conn = HTTPConnection(str(netloc)) conn.request(method, '/%s' % path, body=data, headers=headers) response = conn.getresponse() status = response.status except (httplib.HTTPException, httplib.socket.error), ... |
raise CommError("Service unavailable", url) | raise CommError(errmsg, url, status) | def request(method, url, data=None, headers={}, sleep=0): scheme, netloc, path = urlsplit(urlresolve(url)) try: conn = HTTPConnection(str(netloc)) conn.request(method, '/%s' % path, body=data, headers=headers) response = conn.getresponse() status = response.status except (httplib.HTTPException, httplib.socket.error), ... |
sched = d("scheduler").copy() | sched = jobargs["scheduler"].copy() | def _run(self, **kwargs): jobargs = util.DefaultDict(self.defaults.__getitem__, kwargs) |
sched["max_cores"] = int(kw["nr_maps"]) kw["scheduler"] = sched | sched["max_cores"] = int(jobargs["nr_maps"]) jobargs["scheduler"] = sched | def _run(self, **kwargs): jobargs = util.DefaultDict(self.defaults.__getitem__, kwargs) |
return set(os.getenv('PYTHONPATH', '').split(':') + ['']) | return set([os.path.abspath(path) for path in os.getenv('PYTHONPATH', '').split(':')] + ['']) | def user_paths(): return set(os.getenv('PYTHONPATH', '').split(':') + ['']) |
sys.stderr.write('**<MSG> Singe line message\n') | sys.stderr.write('**<MSG> Single line message\n') | def map(e, params): import sys sys.stderr.write('**<MSG> Singe line message\n') return [] |
sys.stderr.write('**<ERR> Singe line error!\n') | sys.stderr.write('**<ERR> Single line error!\n') | def map(e, params): import sys sys.stderr.write('**<ERR> Singe line error!\n') return [] |
for i, o in enumerate(outputs)]) | for i, output in enumerate(outputs)]) | def _run(self): if len(self.inputs) != 1: TaskFailed("Map takes 1 input, got: %s" % ' '.join(self.inputs)) |
ddfs=self.pop('ddfs', None))] | ddfs=ddfs)] | def __init__(self, *args, **kwargs): super(JobDict, self).__init__(*args, **kwargs) |
return [(e + " | return [(e.strip() + " | def map(e, params): return [(e + "#", '')] |
path, url = Task.reduce_output() | path, url = Task.reduce_output | def reduce_output_stream2(stream, size, url, params): assert stream == 'fd' and url == 'url:%d' % Task.partitions path, url = Task.reduce_output() return disco.fileutils.AtomicFile(path, 'w'), url.replace('disco://', 'foobar://') |
return self._request('/ddfs/tag/%s' % tagname(tag), json.dumps(urls), method='PUT') | from comm_httplib import download status, body = download('%s/ddfs/tag/%s' % (self.master, tagname(tag)), data=json.dumps(urls), method='PUT') return json.loads(body) | def put(self, tag, urls): """Put the list of ``urls`` to the tag ``tag``. |
def __init__(self, format, handle=sys.stdout): | def __init__(self, format, handle=sys.stderr): | def __init__(self, format, handle=sys.stdout): self.handle = handle self.isenabled = True |
from subprocess import check_call, STDOUT from os import uname | def setUp(self): from subprocess import check_call, STDOUT from os import uname if uname()[0] == 'Darwin': self.skipTest('Cannot build static test_external on OS X') else: check_call(['gcc', '-g', '-O3', '-static', '-Wall', '-l', 'Judy', '-I', 'ext/', '-o', 'tests/test_external', 'ext/disco.c', 'tests/test_external.c']... | |
'-I', 'ext/', '-o', 'tests/test_external', 'ext/disco.c', 'tests/test_external.c'], | '-I', path.join(home, 'ext'), '-o', path.join(home, 'tests', 'test_external'), path.join(home, 'ext', 'disco.c'), path.join(home, 'tests', 'test_external.c')], | def setUp(self): from subprocess import check_call, STDOUT from os import uname if uname()[0] == 'Darwin': self.skipTest('Cannot build static test_external on OS X') else: check_call(['gcc', '-g', '-O3', '-static', '-Wall', '-l', 'Judy', '-I', 'ext/', '-o', 'tests/test_external', 'ext/disco.c', 'tests/test_external.c']... |
self.map = external(['tests/test_external']) | self.map = external([path.join(home, 'tests', 'test_external')]) | def setUp(self): from subprocess import check_call, STDOUT from os import uname if uname()[0] == 'Darwin': self.skipTest('Cannot build static test_external on OS X') else: check_call(['gcc', '-g', '-O3', '-static', '-Wall', '-l', 'Judy', '-I', 'ext/', '-o', 'tests/test_external', 'ext/disco.c', 'tests/test_external.c']... |
"""Usage: [-i] [-r] tag ... | """Usage: [-i] [-r] [-p] tag ... | def rm(program, *tags): """Usage: [-i] [-r] tag ... Remove the tag[s]. """ for tag in tags: print program.ddfs.delete(tag) |
for tag in tags: | for tag in program.prefix_mode(*tags): | def rm(program, *tags): """Usage: [-i] [-r] tag ... Remove the tag[s]. """ for tag in tags: print program.ddfs.delete(tag) |
r = self.request('/disco/ctrl/rawevents?name=%s' % name, redir=True, offset=offset) | try: r = self.request("/disco/ctrl/rawevents?name=%s" % name, redir = True, offset = offset) except Exception, x: return [] | def event_iter(events): offs = offset lines = events.splitlines() for i, line in enumerate(lines): if len(line): offs += len(line) + 1 try: event = tuple(json.loads(line)) except ValueError: break # HTTP range request doesn't like empty ranges: # Let's ensure that at least the last newline # is always retrieved. #if i ... |
def check_results(self, name, start_time, timeout): status, results = self.results(name, timeout=timeout) | def check_results(self, name, start_time, timeout, poll_interval): status, results = self.results(name, timeout=poll_interval) | def check_results(self, name, start_time, timeout): status, results = self.results(name, timeout=timeout) if status == 'ready': return results if status != 'active': raise JobError("Job status %s" % status, self.master, name) if timeout and time.time() - start_time > timeout: raise JobError("Timeout", self.master, name... |
return self.check_results(name, start_time, timeout) | return self.check_results(name, start_time, timeout, poll_interval * 1000) | def wait(self, name, poll_interval=2, timeout=2000, clean=False, show=DiscoSettings()['DISCO_EVENTS']): """ Block until the job *name* has finished. Returns a list URLs to the results files which is typically processed with :func:`result_iterator`. |
try: r = op(outstream) outstream.close() return r except Exception, x: raise DataError("Updating file failed: %s" % (x), outfile) | r = op(outstream) outstream.close() return r | def _safe_fileop(op, mode, outfile, timeout): outstream = file(outfile, mode) while timeout > 0: try: fcntl.flock(outstream, fcntl.LOCK_EX | fcntl.LOCK_NB) try: r = op(outstream) outstream.close() return r except Exception, x: # output file is inconsistent state, but might be recoverable raise DataError("Updating file ... |
:param output_stream: :class:`disco.func.InputStream` object that is used | :param output_stream: :class:`disco.func.OutputStream` object that is used | def reduce(input_stream, output_stream, params): """ Takes three parameters, and adds reduced output to an output object. :param input_stream: :class:`disco.func.InputStream` object that is used to iterate through input entries. :param output_stream: :class:`disco.func.InputStream` object that is used to output result... |
for url in util.urllist(i, listdirs=bool(self['map']))] | for url in util.urllist(i, listdirs=bool(self['map']), ddfs=self.pop('ddfs', None))] | def __init__(self, *args, **kwargs): super(JobDict, self).__init__(*args, **kwargs) |
jobpack = JobDict(prefix=self.name, **kwargs).pack() | jobpack = JobDict(prefix=self.name, ddfs=self.master.master, **kwargs).pack() | def run(self, **kwargs): """ Returns the job immediately after the request has been submitted. |
"""Usage: [-i] tag ... | """Usage: [-i] [-p] tag ... | def blobs(program, *tags): """Usage: [-i] tag ... List all blobs reachable from tag[s]. """ ignore_missing = program.options.ignore_missing for tag in tags: for replicas in program.ddfs.blobs(tag, ignore_missing=ignore_missing): print '\t'.join(replicas) |
for tag in tags: | for tag in program.prefix_mode(*tags): | def blobs(program, *tags): """Usage: [-i] tag ... List all blobs reachable from tag[s]. """ ignore_missing = program.options.ignore_missing for tag in tags: for replicas in program.ddfs.blobs(tag, ignore_missing=ignore_missing): print '\t'.join(replicas) |
"""Usage: [-i] tag ... | """Usage: [-i] [-p] tag ... | def cat(program, *tags): """Usage: [-i] tag ... Print all blobs reachable from tag[s] to stdout. """ from subprocess import call from disco.comm import download from disco.util import urlresolve ignore_missing = program.options.ignore_missing def curl(replicas): for replica in replicas: try: return download(replica) e... |
for tag in tags: | for tag in program.prefix_mode(*tags): | def curl(replicas): for replica in replicas: try: return download(replica) except Exception, e: sys.stderr.write("%s\n" % e) raise Exception("Failed downloading all replicas: %s" % replicas) |
"""Usage: tag ... | """Usage: [-p] tag ... | def urls(program, *tags): """Usage: tag ... List the urls pointed to by the tag[s]. """ for tag in tags: print '\n'.join('\t'.join(replicas) for replicas in program.ddfs.get(tag)['urls']) |
for tag in tags: | for tag in program.prefix_mode(*tags): | def urls(program, *tags): """Usage: tag ... List the urls pointed to by the tag[s]. """ for tag in tags: print '\n'.join('\t'.join(replicas) for replicas in program.ddfs.get(tag)['urls']) |
return self._download('%s/%s' % (canonizetag(tag), attr), | return self._download(self._tagattr(tag, attr), | def delattr(self, tag, attr, token=None): """Delete the attribute ``attr` of the tag ``tag``.""" return self._download('%s/%s' % (canonizetag(tag), attr), method='DELETE', token=token) |
return self._download('%s/%s' % (canonizetag(tag), attr), token=token) | return self._download(self._tagattr(tag, attr), token=token) | def getattr(self, tag, attr, token=None): """Return the value of the attribute ``attr` of the tag ``tag``.""" return self._download('%s/%s' % (canonizetag(tag), attr), token=token) |
return self._upload('%s/%s' % (canonizetag(tag), attr), | return self._upload(self._tagattr(tag, attr), | def setattr(self, tag, attr, val, token=None): """Set the value of the attribute ``attr` of the tag ``tag``.""" return self._upload('%s/%s' % (canonizetag(tag), attr), StringIO(json.dumps(val)), token=token) |
if e.http_code == 404: | if e.code == 404: | def oob_get(self, name, key): try: return util.load_oob(self.host, name, key) except CommError, e: if e.http_code == 404: raise DiscoError("Unknown key or job name") raise |
return self.request("/disco/ctrl/rawevents?name=%s" % name, offset=offset) | try: return self.request("/disco/ctrl/rawevents?name=%s" % name, offset=offset) except CommError, e: if e.code == 416: return '' | def rawevents(self, name, offset=0): return self.request("/disco/ctrl/rawevents?name=%s" % name, offset=offset) |
for w, c in iter: d[w] = d.get(w, 1) + 1 for w, c in d.iteritems(): out.add(w, c) This example counts how many teams each key appears. | for k, v in iter: d[k] = d.get(k, 0) + 1 for k, c in d.iteritems(): out.add(k, c) This example counts how many times each key appears. | def fun_reduce(iter, out, params): d = {} for w, c in iter: d[w] = d.get(w, 1) + 1 for w, c in d.iteritems(): out.add(w, c) |
return self.num_workers * 10 | return min(self.num_workers * 10, 300) | def nr_reduces(self): return self.num_workers * 10 |
def check_results(self, name, start_time, timeout): status, results = self.results(name, timeout=timeout) | def check_results(self, name, start_time, timeout, poll_interval): status, results = self.results(name, timeout = poll_interval) | def check_results(self, name, start_time, timeout): status, results = self.results(name, timeout=timeout) if status == 'ready': return results if status != 'active': raise JobError("Job status %s" % status, self.host, name) if timeout and time.time() - start_time > timeout: raise JobError("Timeout", self.host, name) ra... |
return self.check_results(name, start_time, poll_interval * 1000) | return self.check_results(name, start_time, timeout, poll_interval * 1000) | def wait(self, name, show = None, poll_interval = 2, timeout = None, clean = False): event_monitor = EventMonitor(show, disco=self, name=name) start_time = time.time() while True: event_monitor.refresh() try: return self.check_results(name, start_time, poll_interval * 1000) except Continue: continue finally: if clea... |
try: return self.request("/disco/ctrl/rawevents?name=%s" % name, offset=offset) except CommError, e: if e.code == 416: return '' | return self.request("/disco/ctrl/rawevents?name=%s" % name, offset=offset) | def rawevents(self, name, offset=0): try: return self.request("/disco/ctrl/rawevents?name=%s" % name, offset=offset) except CommError, e: if e.code == 416: return '' |
if status_interval and n % status_interval == 0: Message(message_template % n) | if status_interval and (n + 1) % status_interval == 0: Message(message_template % (n + 1)) | def track_status(self, iterator, message_template): status_interval = self.status_interval n = 0 for n, item in enumerate(iterator): if status_interval and n % status_interval == 0: Message(message_template % n) yield item Message("Done: %s" % (message_template % (n + 1))) |
if out.size or out.hunk_size: | if out.hunk_size: | def chunks(self, records): out = self.makeout() for record in records: if out.size > self.chunk_size: yield out.dumps() out = self.makeout() out.append(record) if out.size or out.hunk_size: yield out.dumps() |
def num_cmp(x, y): try: x = (int(x[0]), x[1]) y = (int(y[0]), y[1]) except ValueError: pass return cmp(x, y) | def num_cmp(x, y): try: x = (int(x[0]), x[1]) y = (int(y[0]), y[1]) except ValueError: pass return cmp(x, y) | |
if ' ' in k: TaskFailed("Spaces are not allowed in keys "\ "with external sort.") if '\0' in v: TaskFailed("Zero bytes are not allowed in "\ "values with external sort. "\ "Consider using base64 encoding.") out_fd.write('%s %s\0' % (k, v)) | self.sort_writer(out_fd, k, v) | def download_and_sort(self): dlname = self.task.path('REDUCE_DL', self.task.id) Message("Reduce will be downloaded to %s" % dlname) out_fd = AtomicFile(dlname, 'w') for url in self.inputs: reader, sze, url = self.task.connect_input(url) for k, v in reader: if ' ' in k: TaskFailed("Spaces are not allowed in keys "\ "wit... |
'-z', '-t', ' ', '-o', sortname, dlname] | '-z', '-t', '\xff', '-o', sortname, dlname] | def download_and_sort(self): dlname = self.task.path('REDUCE_DL', self.task.id) Message("Reduce will be downloaded to %s" % dlname) out_fd = AtomicFile(dlname, 'w') for url in self.inputs: reader, sze, url = self.task.connect_input(url) for k, v in reader: if ' ' in k: TaskFailed("Spaces are not allowed in keys "\ "wit... |
def connect(url): fd, sze, url = comm.open_local(url, url) return func.re_reader('(?s)(.*?) (.*?)\000', fd, sze, url) return self.multi_file_iterator(connect, inputs=[sortname]) | return self.multi_file_iterator(self.sort_reader, inputs=[sortname]) | def connect(url): fd, sze, url = comm.open_local(url, url) return func.re_reader('(?s)(.*?) (.*?)\000', fd, sze, url) |
sorted(m, cmp=num_cmp), "%s entries reduced") | sorted(m, cmp=self.num_cmp), "%s entries reduced") | def memory_sort(self): Message("Sorting in memory") m = list(self.multi_file_iterator(self.connect_input, progress=False)) return self.task.track_status( sorted(m, cmp=num_cmp), "%s entries reduced") |
help='balancer to use for indexing') self.add_option('--unique-items', help='balancer to use for indexing') | help='metakeyer to use for indexing') self.add_option('-u', '--unique-items', action='store_true', help='ensure unique items in discodbs') | def __init__(self, **kwargs): OptionParser.__init__(self, **kwargs) self.add_option('-H', '--host', help='host that the client should connect to') self.add_option('-P', '--port', help='port that the client should connect to') self.add_option('-n', '--nr-ichunks', help='the number of ichunks to create') self.add_option(... |
for replicas in blobs: yield replicas | if tags != blobs: for replicas in blobs: yield replicas | def blobs(self, tag, ignore_missing=True): """ Walks the tag graph starting at `tag`. |
(len(k), k, len(v), v)) | (len(k), k, len(v), str(v))) | def encode_netstring_str(d): msg = StringIO.StringIO() for k, v in d: msg.write("%d %s %d %s\n" %\ (len(k), k, len(v), v)) return msg.getvalue() |
lines = events.splitlines() | lines = events.split('\n') | def event_iter(events): offs = offset lines = events.splitlines() for i, line in enumerate(lines): if len(line): offs += len(line) + 1 try: event = tuple(json.loads(line)) except ValueError: break # HTTP range request doesn't like empty ranges: # Let's ensure that at least the last newline # is always retrieved. if i =... |
return os.path.join(self.oobdir, name) | return os.path.join(self.oob_dir, name) | def oob_file(self, name): return os.path.join(self.oobdir, name) |
return msg.encode('utf-8') | return msg.decode('utf-8', 'replace').encode('utf-8') | def __str__(self): tags = ' '.join(tag for tag in self.tags if self.tag_re.match(tag)) msg = '**<%s> %s %s\n%s\n<>**\n' % (self.type, self.timestamp, tags, self.message) try: return msg.encode('utf-8') except UnicodeError: hexmsg = hexlify(self.message) msg = ('**<%s> %s %s\nWarning: non-UTF8 output from worker: %s\n<>... |
return self.headers.get(header, default) | return self.headers.get(header.lower(), default) | def getheader(self, header, default=None): return self.headers.get(header, default) |
t = time.time() | def connected_inputs(self): t = time.time() shuffled = list(self.inputs) random.shuffle(shuffled) inputs = [url for input in shuffled\ for url in util.urllist(input, partid=self.partid)] for input in inputs: yield self.connect_input(input) | |
inputs = [url for input in shuffled\ | inputs = [url for input in shuffled | def connected_inputs(self): t = time.time() shuffled = list(self.inputs) random.shuffle(shuffled) inputs = [url for input in shuffled\ for url in util.urllist(input, partid=self.partid)] for input in inputs: yield self.connect_input(input) |
Returns a triplet (:class:`disco.func.OutputStream`, size, url) that is | Returns a pair (:class:`disco.func.OutputStream`, url) that is | def output_stream(stream, partition, url, params): """ :param stream: :class:`disco.func.OutputStream` object :param partition: partition id :param url: url of the input :param params: the :class:`disco.core.Params` object specified by the *params* parameter in :class:`disco.core.JobDict`. Returns a triplet (:class:`d... |
tags, blobs = partition(urls, tagname) | tags, blobs = partition(urls, istag) | def findtags(self, tags=None, ignore_missing=True): import sys """ Finds the nodes of the tag graph starting at `tags`. |
(tagname(tag), "delayed=1" if delayed else ""), json.dumps(urls)) | (tagname(tag), 'delayed=1' if delayed else ''), json.dumps(urls)) | def tag(self, tag, urls, delayed=False): """Append the list of ``urls`` to the ``tag``.""" return self._download('/ddfs/tag/%s?%s' % (tagname(tag), "delayed=1" if delayed else ""), json.dumps(urls)) |
tags, blobs = partition(urls, tagname) | tags, blobs = partition(urls, istag) | def walk(self, tag, ignore_missing=True, tagpath=()): """ Walks the tag graph starting at `tag`. |
def read_all(self): buf = cStringIO.StringIO() ret = True while ret: ret = self.read(CHUNK_SIZE) buf.write(ret) return buf.getvalue() | def read_all(self): buf = cStringIO.StringIO() ret = True while ret: ret = self.read(CHUNK_SIZE) buf.write(ret) return buf.getvalue() | |
if type(jobspec) == str: | if isinstance(jobspec, basestring): | def results(self, jobspec, timeout=2000): """ Returns a list of results for a single job or for many concurrently running jobs, depending on the type of *jobspec*. |
fn.func_globals.setdefault('Task', self) for module in self.required_modules: mod_name = module[0] if iskv(module) else module mod = __import__(mod_name, fromlist=[mod_name]) fn.func_globals.setdefault(mod_name.split('.')[-1], mod) | if isinstance(fn, FunctionType): fn.func_globals.setdefault('Task', self) for module in self.required_modules: mod_name = module[0] if iskv(module) else module mod = __import__(mod_name, fromlist=[mod_name]) fn.func_globals.setdefault(mod_name.split('.')[-1], mod) | def insert_globals(self, functions): for fn in functions: fn.func_globals.setdefault('Task', self) for module in self.required_modules: mod_name = module[0] if iskv(module) else module mod = __import__(mod_name, fromlist=[mod_name]) fn.func_globals.setdefault(mod_name.split('.')[-1], mod) |
self.insert_globals(self.functions) | self.insert_globals([self.map]) | def _run(self): if len(self.inputs) != 1: TaskFailed("Map can only handle one input. Got: %s" % ' '.join(self.inputs)) |
self.insert_globals(self.functions) | self.insert_globals([self.reduce]) | def _run(self): red_in = iter(ReduceReader(self)) red_out = ReduceOutput(self) params = self.params |
ensure_path(os.path.dirname(fname)) ensure_free_space(fname) | dir = os.path.dirname(fname) ensure_path(dir) ensure_free_space(dir) | def __init__(self, fname, *args, **kw): ensure_path(os.path.dirname(fname)) ensure_free_space(fname) self.fname = fname self.isopen = True super(AtomicFile, self).__init__( fname + ".partial", *args, **kw) |
ensure_free_space(outfile) | ensure_free_space(os.path.dirname(outfile)) | def _safe_fileop(op, mode, outfile, timeout): ensure_free_space(outfile) outstream = file(outfile, mode) while timeout > 0: try: fcntl.flock(outstream, fcntl.LOCK_EX | fcntl.LOCK_NB) r = op(outstream) outstream.close() return r except IOError, x: # Python / BSD doc guides us to check for these errors if x.errno in (err... |
def help(program): print program print """ <indexspec> is the full URI to an index, or the name of an index on --host and --port. [query] is a query in CNF form: ','-separated literals, ' '-separated clauses a,b c == (a or b) and c """ | def help(program, *args): command, leftover = program.search(args) print command if not args: print """ <indexspec> is the full URI to an index, or the name of an index on --host and --port. [query] is a query in CNF form: ','-separated literals, ' '-separated clauses a,b c == (a or b) and c """ | def help(program): print program print """ <indexspec> is the full URI to an index, or the name of an index on --host and --port. [query] is a query in CNF form: ','-separated literals, ' '-separated clauses a,b c == (a or b) and c """ |
def put(program, indexspec, *files): """Usage: <indexspec> file ... Read ichunk urls from file[s], and put them to an index at indexspec. | def put(program, indexspec, *urls): """Usage: [-f] <indexspec> url ... Read ichunk urls from url[s], and put them to an index at indexspec. | def put(program, indexspec, *files): """Usage: <indexspec> file ... Read ichunk urls from file[s], and put them to an index at indexspec. """ from discodex.objects import Index index = Index(urls=[[line.strip()] for line in fileinput.input(files)]) program.client.put(indexspec, index) |
index = Index(urls=[[line.strip()] for line in fileinput.input(files)]) | index = Index(urls=[url.split() for url in program.file_mode(*urls)]) | def put(program, indexspec, *files): """Usage: <indexspec> file ... Read ichunk urls from file[s], and put them to an index at indexspec. """ from discodex.objects import Index index = Index(urls=[[line.strip()] for line in fileinput.input(files)]) program.client.put(indexspec, index) |
def index(program, *files): """Usage: [--parser p] [--demuxer d] [--balancer b] [-n N] [--profile] [file ...] Read input urls from file[s], and index using the specified options. | def index(program, *urls): """Usage: [-f] [--parser p] [--demuxer d] [--balancer b] [-n N] [--profile] [url ...] Read input urls from urls[s], and index using the specified options. | def index(program, *files): """Usage: [--parser p] [--demuxer d] [--balancer b] [-n N] [--profile] [file ...] Read input urls from file[s], and index using the specified options. """ from discodex.objects import DataSet dataset = DataSet(options=program.option_dict, input=[line.strip() for line in fileinput.input(file... |
input=[line.strip() for line in fileinput.input(files)]) | input=[url.split() for url in program.file_mode(*urls)]) | def index(program, *files): """Usage: [--parser p] [--demuxer d] [--balancer b] [-n N] [--profile] [file ...] Read input urls from file[s], and index using the specified options. """ from discodex.objects import DataSet dataset = DataSet(options=program.option_dict, input=[line.strip() for line in fileinput.input(file... |
if not isinstance(key, basestring): | if not isinstance(key, str): | def sort_writer(self, fd, key, value): # key should not contain \xff # value pickled using protocol 0 will always be printable ASCII # (can't contain \0) if not isinstance(key, basestring): TaskFailed("Keys must be strings for external sort") if '\xff' in key or '\x00' in key: TaskFailed("0xFF or 0x00 bytes are not all... |
TaskFailed("Sorting %s to %s failed (%d)" % (dlname, sortname, ret)) | raise DataError("Sorting %s to %s failed (%d)" % (dlname, sortname, ret), dlname) | def download_and_sort(self): dlname = self.task.path('REDUCE_DL', self.task.id) Message("Reduce will be downloaded to %s" % dlname) out_fd = AtomicFile(dlname, 'w') for url in self.inputs: reader, sze, url = self.task.connect_input(url) for k, v in reader: self.sort_writer(out_fd, k, v) out_fd.close() Message("Reduce i... |
def num_cmp(x, y): if x[0].isdigit() and y[0].isdigit(): x = int(x[0]), x[1] y = int(y[0]), y[1] return cmp(x, y) | def num_cmp(x, y): if x[0].isdigit() and y[0].isdigit(): x = int(x[0]), x[1] y = int(y[0]), y[1] return cmp(x, y) | |
return self.task.track_status(sorted(m, cmp=num_cmp), "%s entries reduced") | return self.task.track_status(sorted(m), "%s entries reduced") | def memory_sort(self): Message("Sorting in memory") m = list(self.multi_file_iterator(self.connect_input, progress=False)) return self.task.track_status(sorted(m, cmp=num_cmp), "%s entries reduced") |
if out: | if out.size or out.hunk_size: | def chunks(self, records): out = self.makeout() for record in records: if out.size > self.chunk_size: yield out.dumps() out = self.makeout() out.append(record) if out: yield out.dumps() |
if tags == None: return [tagname(tag) for tag in self.tags()] elif type(tags) == list: return [tagname(tag) for tag in tags] elif type(tags) == str: return [tagname(tags)] | return [tagname(tag) for tag in iterify(tags)] | def canonizetags(tags): if tags == None: return [tagname(tag) for tag in self.tags()] elif type(tags) == list: return [tagname(tag) for tag in tags] elif type(tags) == str: return [tagname(tags)] |
def __init__(self, connection): self.connection = connection | def __init__(self): | def __init__(self, connection): self.connection = connection self.headers = {} self.buffer = StringIO() |
@property def status(self): return self.connection['HTTP_CODE'] | def read(self): return self.buffer.getvalue() | |
self.response = CurlResponse(self) | self.response = CurlResponse() | def __init__(self, netloc): self.handle = pycurl.Curl() for k, v in self.defaults.items(): self[k] = v |
return reduce(__and__, (c.resolve(discodb) for c in self.clauses)) | return reduce(__and__, (c.resolve(discodb) for c in self.clauses), Q([])) | def resolve(self, discodb): return reduce(__and__, (c.resolve(discodb) for c in self.clauses)) |
request['ext_params'] = encode_netstring_fd(e) | request['ext_params'] = encode_netstring_fd(e)\ | def inputlist(input): if hasattr(input, '__iter__'): return ['\n'.join(reversed(list(input)))] return util.urllist(input) |
if self.task.jobdict.input_is_partitioned: | if self.task.ispartitioned or self.task.jobdict.input_is_partitioned: | def partid(self): if self.task.jobdict.input_is_partitioned: if not self.task.jobdict['merge_partitions']: return self.task.id |
qs = urlencode((k, v) for k, v in (('exclude', ','.join(exclude)), ('replicas', replicas)) if v) | qs = urlencode([(k, v) for k, v in (('exclude', ','.join(exclude)), ('replicas', replicas)) if v]) | def _push(self, (source, target), replicas=None, retries=None, exclude=[]): qs = urlencode((k, v) for k, v in (('exclude', ','.join(exclude)), ('replicas', replicas)) if v) dsts = self._request('/ddfs/new_blob/%s?%s' % (target, qs)) try: return [json.loads(url) for url in self._upload(fname, dsts, retries=retries)] exc... |
for url in self._upload(fname, dsts, retries=retries)] | for url in self._upload(source, dsts, retries=retries)] | def _push(self, (source, target), replicas=None, retries=None, exclude=[]): qs = urlencode((k, v) for k, v in (('exclude', ','.join(exclude)), ('replicas', replicas)) if v) dsts = self._request('/ddfs/new_blob/%s?%s' % (target, qs)) try: return [json.loads(url) for url in self._upload(fname, dsts, retries=retries)] exc... |
if i == len(lines) - 1: offs -= 1 | def event_iter(events): offs = offset lines = events.splitlines() for i, line in enumerate(lines): if len(line): offs += len(line) + 1 try: event = tuple(json.loads(line)) except ValueError: break # HTTP range request doesn't like empty ranges: # Let's ensure that at least the last newline # is always retrieved. if i =... | |
r = self.request("/disco/ctrl/rawevents?name=%s" % name, redir = True, offset = offset) | try: r = self.request("/disco/ctrl/rawevents?name=%s" % name, redir = True, offset = offset) except Exception, x: return [] | def event_iter(events): offs = offset lines = events.splitlines() for i, line in enumerate(lines): if len(line): offs += len(line) + 1 try: event = tuple(json.loads(line)) except ValueError: break # HTTP range request doesn't like empty ranges: # Let's ensure that at least the last newline # is always retrieved. if i =... |
if self['required_modules'] is None: functions = util.flatten(util.iterify(self[f]) for f in chain(self.functions, self.stacks)) self['required_modules'] = find_modules([f for f in functions if callable(f)]) if self['required_files']: if not isinstance(self['required_files'], dict): self['required_files'] = util.pack_... | def __init__(self, *args, **kwargs): super(JobDict, self).__init__(*args, **kwargs) | |
jobpack = JobDict(prefix=self.name, ddfs=self.master.master, **kwargs).pack() | jobpack = Job.JobDict(self, prefix=self.name, ddfs=self.master.master, **kwargs).pack() | def run(self, **kwargs): """ Returns the job immediately after the request has been submitted. |
return JobDict.unpack(self.jobpack(name)) | from cStringIO import StringIO return JobDict.unpack(StringIO(self.jobpack(name))) | def jobdict(self, name): return JobDict.unpack(self.jobpack(name)) |
if uri.startswith(baseuri): return uri | def resolveuri(baseuri, uri): if uri.startswith(baseuri): return uri if uri.startswith('/'): scheme, netloc, _path = urlsplit(baseuri) return '%s://%s%s' % (scheme, netloc, uri) return '%s/%s' % (baseuri, uri) | |
resolveuri(url, response.getheader('location')), | loc if loc.startswith('http:') else resolveuri(url, loc), | def request(method, url, data=None, headers={}, sleep=0): scheme, netloc, path = urlsplit(urlresolve(url)) try: conn = HTTPConnection(str(netloc)) conn.request(method, '/%s' % path, body=data, headers=headers) response = conn.getresponse() except (httplib.HTTPException, httplib.socket.error), e: raise CommError("Reque... |
elif scheme == 'tag': from disco.ddfs import DDFS ret = [] for name, tags, blobs in DDFS(ddfs).findtags(url): ret += blobs return ret | def urllist(url, partid=None, listdirs=True, ddfs=None): if isiterable(url): return [list(url)] scheme, netloc, path = urlsplit(url) if scheme == 'dir' and listdirs: return parse_dir(url, partid=partid) elif scheme == 'tag': from disco.ddfs import DDFS ret = [] for name, tags, blobs in DDFS(ddfs).findtags(url): ret += ... | |
print ("Warning: multiple instance of file " + fnamefields[0] + "; Previous version = " + installed_debs[fnamefields[0]]) | print ("Warning: multiple instance of file " + fnamefields[0] + "; Previous version = " + installed_debs[fnamefields[0]][0]) | def changes_files(repo): installed_debs={} # get installed list for root, dirs, files in os.walk(repo+"/installed"): for file in files: for line in open(root+"/"+file): #d_print ( str(len(line)) + line[-5:-1]) if len(line) > 5 and ".deb" == line[-5:-1]: fields=line.split(" ") fname=fields[-1] fnamefields=fname.split("_... |
panel.addfstr(10, 0, "<b>Accounting (<%s>%s</%s>)" % (hibernateColor, status, hibernateColor)) | panel.addfstr(10, 0, "<b>Accounting (<%s>%s</%s>)</b>" % (hibernateColor, status, hibernateColor)) | def draw(self, panel): # if display is narrow, overwrites x-axis labels with avg / total stats if panel.maxX <= COLLAPSE_WIDTH: # clears line panel.addstr(8, 0, " " * 200) graphCol = min((panel.maxX - 10) / 2, graphPanel.MAX_GRAPH_COL) primaryFooter = "%s, %s" % (self._getAvgLabel(True), self._getTotalLabel(True)) sec... |
psCall = sysTools.call("ps -p %s -o %s" % (torPid, "%cpu,rss"), 5, True) | psCall = sysTools.call("ps -p %s -o %s" % (torPid, "%cpu,rss,%mem,etime"), 5, True) | def bandwidth_event(self, event): # doesn't use events but this keeps it in sync with the bandwidth panel # (and so it stops if Tor stops # TODO: ok, screw it - the number of ps calls this makes is ridicuous # compared to how frequently it changes - now caching for five seconds # (note this during the rewrite that its ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.