desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Iterate over records in file.
Yields records as strings.'
| def __iter__(self):
| ctx = context.get()
while self._reader:
try:
start_time = time.time()
record = self._reader.read()
if ctx:
operation.counters.Increment(COUNTER_IO_READ_MSEC, int(((time.time() - start_time) * 1000)))(ctx)
operation.counters.Increment(CO... |
'Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json.'
| @classmethod
def from_json(cls, json):
| return cls(json['filenames'], json['position'])
|
'Returns an input shard state for the remaining inputs.
Returns:
A json-izable version of the remaining InputReader.'
| def to_json(self):
| result = {'filenames': self._filenames, 'position': 0}
if self._reader:
result['position'] = self._reader.tell()
return result
|
'Returns a list of input readers for the input spec.
Args:
mapper_spec: The MapperSpec for this InputReader.
Returns:
A list of InputReaders.'
| @classmethod
def split_input(cls, mapper_spec):
| params = _get_params(mapper_spec)
shard_count = mapper_spec.shard_count
if (cls.FILES_PARAM in params):
filenames = params[cls.FILES_PARAM]
if isinstance(filenames, basestring):
filenames = filenames.split(',')
else:
filenames = [params[cls.FILE_PARAM]]
batch_list... |
'Validates mapper spec and all mapper parameters.
Args:
mapper_spec: The MapperSpec for this InputReader.
Raises:
BadReaderParamsError: required parameters are missing or invalid.'
| @classmethod
def validate(cls, mapper_spec):
| if (mapper_spec.input_reader_class() != cls):
raise errors.BadReaderParamsError('Input reader class mismatch')
params = _get_params(mapper_spec)
if ((cls.FILES_PARAM not in params) and (cls.FILE_PARAM not in params)):
raise BadReaderParamsError(("Must specify '%s' or '%s... |
'Constructor.
Args:
start_time: The earliest request completion or last-update time of logs
that should be mapped over, in seconds since the Unix epoch.
end_time: The latest request completion or last-update time that logs
should be mapped over, in seconds since the Unix epoch.
minimum_log_level: An application log lev... | def __init__(self, start_time=None, end_time=None, minimum_log_level=None, include_incomplete=False, include_app_logs=False, version_ids=None, **kwargs):
| InputReader.__init__(self)
self.__params = dict(kwargs)
if (start_time is not None):
self.__params[self.START_TIME_PARAM] = start_time
if (end_time is not None):
self.__params[self.END_TIME_PARAM] = end_time
if (minimum_log_level is not None):
self.__params[self.MINIMUM_LOG_L... |
'Iterates over logs in a given range of time.
Yields:
A RequestLog containing all the information for a single request.'
| def __iter__(self):
| for log in logservice.fetch(**self.__params):
self.__params[self._OFFSET_PARAM] = log.offset
(yield log)
|
'Creates an instance of the InputReader for the given input shard\'s state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the given JSON parameters.'
| @classmethod
def from_json(cls, json):
| params = dict(((str(k), v) for (k, v) in json.iteritems() if (k in cls._PARAMS)))
if (cls._OFFSET_PARAM in params):
params[cls._OFFSET_PARAM] = base64.b64decode(params[cls._OFFSET_PARAM])
return cls(**params)
|
'Returns an input shard state for the remaining inputs.
Returns:
A JSON serializable version of the remaining input to read.'
| def to_json(self):
| params = dict(self.__params)
if (self._PROTOTYPE_REQUEST_PARAM in params):
prototype_request = params[self._PROTOTYPE_REQUEST_PARAM]
params[self._PROTOTYPE_REQUEST_PARAM] = prototype_request.Encode()
if (self._OFFSET_PARAM in params):
params[self._OFFSET_PARAM] = base64.b64encode(par... |
'Returns a list of input readers for the given input specification.
Args:
mapper_spec: The MapperSpec for this InputReader.
Returns:
A list of InputReaders.'
| @classmethod
def split_input(cls, mapper_spec):
| params = _get_params(mapper_spec)
shard_count = mapper_spec.shard_count
start_time = params[cls.START_TIME_PARAM]
end_time = params[cls.END_TIME_PARAM]
seconds_per_shard = ((end_time - start_time) / shard_count)
shards = []
for _ in xrange((shard_count - 1)):
params[cls.END_TIME_PARA... |
'Validates the mapper\'s specification and all necessary parameters.
Args:
mapper_spec: The MapperSpec to be used with this InputReader.
Raises:
BadReaderParamsError: If the user fails to specify both a starting time
and an ending time, or if the starting time is later than the ending
time.'
| @classmethod
def validate(cls, mapper_spec):
| if (mapper_spec.input_reader_class() != cls):
raise errors.BadReaderParamsError('Input reader class mismatch')
params = _get_params(mapper_spec, allowed_keys=cls._PARAMS)
if (cls.VERSION_IDS_PARAM not in params):
raise errors.BadReaderParamsError('Must specify a list of ... |
'Returns the string representation of this LogInputReader.'
| def __str__(self):
| params = []
for key in sorted(self.__params.keys()):
value = self.__params[key]
if (key is self._PROTOTYPE_REQUEST_PARAM):
params.append(("%s='%s'" % (key, value)))
elif (key is self._OFFSET_PARAM):
params.append(("%s='%s'" % (key, value)))
else:
... |
'Returns entity kind.'
| @classmethod
def kind(cls):
| return '_GAE_MR_TaskPayload'
|
'Add task to the queue.'
| def add(self, queue_name, transactional=False, parent=None):
| if (self.compressed_payload is None):
task = self.to_task()
task.add(queue_name, transactional)
return
if (len(self.compressed_payload) < self.MAX_TASK_PAYLOAD):
task = taskqueue.Task(url=self.url, params={self.PAYLOAD_PARAM: self.compressed_payload}, name=self.name, eta=self.eta... |
'Convert to a taskqueue task without doing any kind of encoding.'
| def to_task(self):
| return taskqueue.Task(url=self.url, params=self.params, name=self.name, eta=self.eta, countdown=self.countdown)
|
'Initialize.
Args:
tokenizer: an instance of _Tokenizer.
Raises:
ValueError: when parser couldn\'t consume all format_string.'
| def __init__(self, tokenizer):
| self.formats = []
self._tokenizer = tokenizer
self._parse_format_string()
if tokenizer.remainder():
raise ValueError(('Extra chars after index -%d' % tokenizer.remainder()))
|
'Add a format to result list.
The format name will be resolved to its corresponding _FileFormat class.
kwargs will be passed to the class\'s __init___.
Args:
format_name: name of the parsed format in str.
kwargs: a dict containing key word arguments for the format.
Raises:
ValueError: when format_name is not supported ... | def _add_format(self, format_name, kwargs):
| if (format_name not in file_formats.FORMATS):
raise ValueError(('Invalid format %s.' % format_name))
format_cls = file_formats.FORMATS[format_name]
for k in kwargs:
if (k not in format_cls.ARGUMENTS):
raise ValueError(('Invalid argument %s for format %s' % (k... |
'Parses format_string.'
| def _parse_format_string(self):
| self._parse_parameterized_format()
if self._tokenizer.consume_if('['):
self._parse_format_string()
self._tokenizer.consume(']')
|
'Validates a string is composed of valid characters.
Args:
text: any str to validate.
Raises:
ValueError: when text contains illegal characters.'
| def _validate_string(self, text):
| if (not re.match(tokenize.Name, text)):
raise ValueError(('%s should only contain ascii letters or digits.' % text))
|
'Parses parameterized_format.'
| def _parse_parameterized_format(self):
| format_name = self._tokenizer.next()
self._validate_string(format_name)
arguments = {}
if self._tokenizer.consume_if('('):
arguments = self._parse_format_parameters()
self._tokenizer.consume(')')
self._add_format(format_name, arguments)
|
'Parses format_parameters.
Returns:
a dict of parameter names to their values for this format.
Raises:
ValueError: when the format_parameters have illegal syntax or semantics.'
| def _parse_format_parameters(self):
| arguments = {}
comma_exist = True
while (self._tokenizer.peek() not in ')]'):
if (not comma_exist):
raise ValueError(('Arguments should be separated by comma at index %d.' % self._tokenizer.index))
key = self._tokenizer.next()
self._validate_string... |
'Initialize.
Args:
format_string: user supplied format string for MapReduce InputReader.'
| def __init__(self, format_string):
| self.index = 0
self._format_string = format_string
|
'Returns the next token with surrounding white spaces stripped.
This method does not advance underlying buffer.
Returns:
the next token with surrounding whitespaces stripped.'
| def peek(self):
| return self.next(advance=False)
|
'Returns the next token with surrounding white spaces stripped.
Args:
advance: boolean. True if underlying buffer should be advanced.
Returns:
the next token with surrounding whitespaces stripped.'
| def next(self, advance=True):
| escaped = False
token = ''
previous_index = self.index
while self.remainder():
char = self._format_string[self.index]
if (char == self.ESCAPE_CHAR):
if escaped:
token += char
self.index += 1
escaped = False
else:
... |
'Consumes the next token which must match expectation.
Args:
expected_token: the expected value of the next token.
Raises:
ValueError: raised when the next token doesn\'t match expected_token.'
| def consume(self, expected_token):
| token = self.next()
if (token != expected_token):
raise ValueError(('Expect "%s" but got "%s" at offset %d' % (expected_token, token, self.index)))
|
'Consumes the next token when it matches expectation.
Args:
token: the expected next token.
Returns:
True when next token matches the argument and is consumed.
False otherwise.'
| def consume_if(self, token):
| if (self.peek() == token):
self.consume(token)
return True
return False
|
'Returns the number of bytes left to be processed.'
| def remainder(self):
| return (len(self._format_string) - self.index)
|
'Constructor.
Args:
counter_name: name of the counter as string
delta: increment delta as int.'
| def __init__(self, counter_name, delta=1):
| self.counter_name = counter_name
self.delta = delta
|
'Execute operation.
Args:
context: mapreduce context as context.Context.'
| def __call__(self, context):
| context.counters.increment(self.counter_name, self.delta)
|
'Constructor.
Args:
entity: an entity to put.'
| def __init__(self, entity):
| self.entity = entity
|
'Perform operation.
Args:
context: mapreduce context as context.Context.'
| def __call__(self, context):
| context.mutation_pool.put(self.entity)
|
'Constructor.
Args:
entity: a key or model instance to delete.'
| def __init__(self, entity):
| self.entity = entity
|
'Perform operation.
Args:
context: mapreduce context as context.Context.'
| def __call__(self, context):
| context.mutation_pool.delete(self.entity)
|
'Create a KeyRanges object.
Args:
list_of_key_ranges: a list of key_range.KeyRange object.
Returns:
A _KeyRanges object.'
| @classmethod
def create_from_list(cls, list_of_key_ranges):
| return _KeyRangesFromList(list_of_key_ranges)
|
'Create a KeyRanges object.
Args:
ns_range: a namespace_range.NameSpace Range object.
Returns:
A _KeyRanges object.'
| @classmethod
def create_from_ns_range(cls, ns_range):
| return _KeyRangesFromNSRange(ns_range)
|
'Deserialize from json.
Args:
json: a dict of json compatible fields.
Returns:
a KeyRanges object.
Raises:
ValueError: if the json is invalid.'
| @classmethod
def from_json(cls, json):
| if (json['name'] in _KEYRANGES_CLASSES):
return _KEYRANGES_CLASSES[json['name']].from_json(json)
raise ValueError('Invalid json %s', json)
|
'Iterator iteraface.'
| def next(self):
| raise NotImplementedError()
|
'Init.'
| def __init__(self, ns_range):
| self._ns_range = ns_range
if (self._ns_range is not None):
self._iter = iter(self._ns_range)
self._last_ns = None
|
'Initializes a Hooks class.
Args:
mapreduce_spec: The mapreduce.model.MapreduceSpec for the current
mapreduce.'
| def __init__(self, mapreduce_spec):
| self.mapreduce_spec = mapreduce_spec
|
'Enqueues a worker task that is used to run the mapper.
Args:
task: A taskqueue.Task that must be queued in order for the mapreduce
mappers to be run.
queue_name: The queue where the task should be run e.g. "default".
Raises:
NotImplementedError: to indicate that the default worker queueing strategy
should be used.'
| def enqueue_worker_task(self, task, queue_name):
| raise NotImplementedError()
|
'Enqueues a task that is used to start the mapreduce.
Args:
task: A taskqueue.Task that must be queued in order for the mapreduce
to start.
queue_name: The queue where the task should be run e.g. "default".
Raises:
NotImplementedError: to indicate that the default mapreduce start strategy
should be used.'
| def enqueue_kickoff_task(self, task, queue_name):
| raise NotImplementedError()
|
'Enqueues a task that is triggered when the mapreduce completes.
Args:
task: A taskqueue.Task that must be queued in order for the client to be
notified when the mapreduce is complete.
queue_name: The queue where the task should be run e.g. "default".
Raises:
NotImplementedError: to indicate that the default mapreduce ... | def enqueue_done_task(self, task, queue_name):
| raise NotImplementedError()
|
'Enqueues a task that is used to monitor the mapreduce process.
Args:
task: A taskqueue.Task that must be queued in order for updates to the
mapreduce process to be properly tracked.
queue_name: The queue where the task should be run e.g. "default".
Raises:
NotImplementedError: to indicate that the default mapreduce tr... | def enqueue_controller_task(self, task, queue_name):
| raise NotImplementedError()
|
'Converts a MapReduceYaml file into a JSON-encodable dictionary.
For use in user-visible UI and internal methods for interfacing with
user code (like param validation). as a list
Args:
mapreduce_yaml: The Pyton representation of the mapreduce.yaml document.
Returns:
A list of configuration dictionaries.'
| @staticmethod
def to_dict(mapreduce_yaml):
| all_configs = []
for config in mapreduce_yaml.mapreduce:
out = {'name': config.name, 'mapper_input_reader': config.mapper.input_reader, 'mapper_handler': config.mapper.handler}
if config.mapper.params_validator:
out['mapper_params_validator'] = config.mapper.params_validator
... |
'Encodes the given data, which may have include raw bytes.
Works around limitations in JSON encoding, which cannot handle raw bytes.'
| @staticmethod
def encode_data(data):
| return base64.b64encode(pickle.dumps(data))
|
'Decodes data encoded with the encode_data function.'
| @staticmethod
def decode_data(data):
| return pickle.loads(base64.b64decode(data))
|
'Returns an input shard state for the remaining inputs.
Returns:
A json-izable version of the remaining InputReader.'
| def to_json(self):
| result = super(_ReducerReader, self).to_json()
result['current_key'] = _ReducerReader.encode_data(self.current_key)
result['current_values'] = _ReducerReader.encode_data(self.current_values)
return result
|
'Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json.'
| @classmethod
def from_json(cls, json):
| result = super(_ReducerReader, cls).from_json(json)
result.current_key = _ReducerReader.decode_data(json['current_key'])
result.current_values = _ReducerReader.decode_data(json['current_values'])
return result
|
'Inherit docs.'
| def default(self, o):
| if (type(o) in JSON_DEFAULTS):
encoder = JSON_DEFAULTS[type(o)][0]
json_struct = encoder(o)
json_struct[self.TYPE_ID] = type(o).__name__
return json_struct
return super(JsonEncoder, self).default(o)
|
'Converts a dictionary of json object to a Python object.'
| def _dict_to_obj(self, d):
| if (JsonEncoder.TYPE_ID not in d):
return d
obj_type = d.pop(JsonEncoder.TYPE_ID)
if (obj_type in _TYPE_IDS):
decoder = JSON_DEFAULTS[_TYPE_IDS[obj_type]][1]
return decoder(d)
else:
raise TypeError('Invalid type %s.', obj_type)
|
'Convert data to json string representation.
Returns:
json representation as string.'
| def to_json_str(self):
| json_dic = self.to_json()
try:
return json.dumps(json_dic, sort_keys=True, cls=JsonEncoder)
except:
logging.exception('Could not serialize JSON: %r', json_dic)
raise
|
'Convert json string representation into class instance.
Args:
json_str: json representation as string.
Returns:
New instance of the class with data loaded from json string.'
| @classmethod
def from_json_str(cls, json_str):
| return cls.from_json(json.loads(json_str, cls=JsonDecoder))
|
'Constructor.
Args:
data_type: underlying data type as class.
default: default value for the property. The value is deep copied
fore each model instance.
kwargs: remaining arguments.'
| def __init__(self, data_type, default=None, **kwargs):
| kwargs['default'] = default
super(JsonProperty, self).__init__(**kwargs)
self.data_type = data_type
|
'Gets value for datastore.
Args:
model_instance: instance of the model class.
Returns:
datastore-compatible value.'
| def get_value_for_datastore(self, model_instance):
| value = super(JsonProperty, self).get_value_for_datastore(model_instance)
if (not value):
return None
json_value = value
if (not isinstance(value, dict)):
json_value = value.to_json()
if (not json_value):
return None
return datastore_types.Text(json.dumps(json_value, sort... |
'Convert value from datastore representation.
Args:
value: datastore value.
Returns:
value to store in the model.'
| def make_value_from_datastore(self, value):
| if (value is None):
return None
json_out = json.loads(value, cls=JsonDecoder)
if (self.data_type == dict):
return json_out
return self.data_type.from_json(json_out)
|
'Validate value.
Args:
value: model value.
Returns:
Whether the specified value is valid data type value.
Raises:
BadValueError: when value is not of self.data_type type.'
| def validate(self, value):
| if ((value is not None) and (not isinstance(value, self.data_type))):
raise datastore_errors.BadValueError(('Property %s must be convertible to a %s instance (%s)' % (self.name, self.data_type, value)))
return super(JsonProperty, self).validate(value)
|
'Checks if value is empty.
Args:
value: model value.
Returns:
True passed value is empty.'
| def empty(self, value):
| return (not value)
|
'Create default model value.
If default option was specified, then it will be deeply copied.
None otherwise.
Returns:
default model value.'
| def default_value(self):
| if self.default:
return copy.deepcopy(self.default)
else:
return None
|
'Constructor.
Args:
initial_map: initial counter values map from counter name (string) to
counter value (int).'
| def __init__(self, initial_map=None):
| if initial_map:
self.counters = initial_map
else:
self.counters = {}
|
'Compute string representation.'
| def __repr__(self):
| return ('mapreduce.model.CountersMap(%r)' % self.counters)
|
'Get current counter value.
Args:
counter_name: counter name as string.
Returns:
current counter value as int. 0 if counter was not set.'
| def get(self, counter_name):
| return self.counters.get(counter_name, 0)
|
'Increment counter value.
Args:
counter_name: counter name as String.
delta: increment delta as Integer.
Returns:
new counter value.'
| def increment(self, counter_name, delta):
| current_value = self.counters.get(counter_name, 0)
new_value = (current_value + delta)
self.counters[counter_name] = new_value
return new_value
|
'Add all counters from the map.
For each counter in the passed map, adds its value to the counter in this
map.
Args:
counters_map: CounterMap instance to add.'
| def add_map(self, counters_map):
| for counter_name in counters_map.counters:
self.increment(counter_name, counters_map.counters[counter_name])
|
'Subtracts all counters from the map.
For each counter in the passed map, subtracts its value to the counter in
this map.
Args:
counters_map: CounterMap instance to subtract.'
| def sub_map(self, counters_map):
| for counter_name in counters_map.counters:
self.increment(counter_name, (- counters_map.counters[counter_name]))
|
'Clear all values.'
| def clear(self):
| self.counters = {}
|
'Serializes all the data in this map into json form.
Returns:
json-compatible data representation.'
| def to_json(self):
| return {'counters': self.counters}
|
'Create new CountersMap from the json data structure, encoded by to_json.
Args:
json: json representation of CountersMap .
Returns:
an instance of CountersMap with all data deserialized from json.'
| @classmethod
def from_json(cls, json_in):
| counters_map = cls()
counters_map.counters = json_in['counters']
return counters_map
|
'Convert to dictionary.
Returns:
a dictionary with counter name as key and counter values as value.'
| def to_dict(self):
| return self.counters
|
'Creates a new MapperSpec.
Args:
handler_spec: handler specification as string (see class doc for
details).
input_reader_spec: The class name of the input reader to use.
params: Dictionary of additional parameters for the mapper.
shard_count: number of shards to process in parallel.
Properties:
handler_spec: name of ha... | def __init__(self, handler_spec, input_reader_spec, params, shard_count, output_writer_spec=None):
| self.handler_spec = handler_spec
self.input_reader_spec = input_reader_spec
self.output_writer_spec = output_writer_spec
self.shard_count = shard_count
self.params = params
|
'Get mapper handler instance.
Returns:
handler instance as callable.'
| def get_handler(self):
| return util.handler_for_name(self.handler_spec)
|
'Get input reader class.
Returns:
input reader class object.'
| def input_reader_class(self):
| return util.for_name(self.input_reader_spec)
|
'Get output writer class.
Returns:
output writer class object.'
| def output_writer_class(self):
| return (self.output_writer_spec and util.for_name(self.output_writer_spec))
|
'Serializes this MapperSpec into a json-izable object.'
| def to_json(self):
| result = {'mapper_handler_spec': self.handler_spec, 'mapper_input_reader': self.input_reader_spec, 'mapper_params': self.params, 'mapper_shard_count': self.shard_count}
if self.output_writer_spec:
result['mapper_output_writer'] = self.output_writer_spec
return result
|
'Creates MapperSpec from a dict-like object.'
| @classmethod
def from_json(cls, json_in):
| return cls(json_in['mapper_handler_spec'], json_in['mapper_input_reader'], json_in['mapper_params'], json_in['mapper_shard_count'], json_in.get('mapper_output_writer'))
|
'Create new MapreduceSpec.
Args:
name: The name of this mapreduce job type.
mapreduce_id: ID of the mapreduce.
mapper_spec: JSON-encoded string containing a MapperSpec.
params: dictionary of additional mapreduce parameters.
hooks_class_name: The fully qualified name of the hooks class to use.
Properties:
name: The name... | def __init__(self, name, mapreduce_id, mapper_spec, params={}, hooks_class_name=None):
| self.name = name
self.mapreduce_id = mapreduce_id
self.mapper = MapperSpec.from_json(mapper_spec)
self.params = params
self.hooks_class_name = hooks_class_name
self.__hooks = None
self.get_hooks()
|
'Returns a hooks.Hooks class or None if no hooks class has been set.'
| def get_hooks(self):
| if ((self.__hooks is None) and (self.hooks_class_name is not None)):
hooks_class = util.for_name(self.hooks_class_name)
if (not isinstance(hooks_class, type)):
raise ValueError(('hooks_class_name must refer to a class, got %s' % type(hooks_class).__name__))
i... |
'Serializes all data in this mapreduce spec into json form.
Returns:
data in json format.'
| def to_json(self):
| mapper_spec = self.mapper.to_json()
return {'name': self.name, 'mapreduce_id': self.mapreduce_id, 'mapper_spec': mapper_spec, 'params': self.params, 'hooks_class_name': self.hooks_class_name}
|
'Create new MapreduceSpec from the json, encoded by to_json.
Args:
json_in: json representation of MapreduceSpec.
Returns:
an instance of MapreduceSpec with all data deserialized from json.'
| @classmethod
def from_json(cls, json_in):
| mapreduce_spec = cls(json_in['name'], json_in['mapreduce_id'], json_in['mapper_spec'], json_in.get('params'), json_in.get('hooks_class_name'))
return mapreduce_spec
|
'Returns entity kind.'
| @classmethod
def kind(cls):
| return '_GAE_MR_MapreduceState'
|
'Retrieves the Key for a Job.
Args:
mapreduce_id: The job to retrieve.
Returns:
Datastore Key that can be used to fetch the MapreduceState.'
| @classmethod
def get_key_by_job_id(cls, mapreduce_id):
| return db.Key.from_path(cls.kind(), str(mapreduce_id))
|
'Retrieves the instance of state for a Job.
Args:
mapreduce_id: The mapreduce job to retrieve.
Returns:
instance of MapreduceState for passed id.'
| @classmethod
def get_by_job_id(cls, mapreduce_id):
| return db.get(cls.get_key_by_job_id(mapreduce_id))
|
'Updates a chart url to display processed count for each shard.
Args:
shards_processed: list of integers with number of processed entities in
each shard'
| def set_processed_counts(self, shards_processed):
| chart = google_chart_api.BarChart(shards_processed)
shard_count = len(shards_processed)
if shards_processed:
stride_length = max(1, (shard_count / 16))
chart.bottom.labels = []
for x in xrange(shard_count):
if (((x % stride_length) == 0) or (x == (shard_count - 1))):
... |
'Number of processed entities.
Returns:
The total number of processed entities as int.'
| def get_processed(self):
| return self.counters_map.get(context.COUNTER_MAPPER_CALLS)
|
'Create a new MapreduceState.
Args:
mapreduce_id: Mapreduce id as string.
gettime: Used for testing.'
| @staticmethod
def create_new(mapreduce_id=None, gettime=datetime.datetime.now):
| if (not mapreduce_id):
mapreduce_id = MapreduceState.new_mapreduce_id()
state = MapreduceState(key_name=mapreduce_id, last_poll_time=gettime())
state.set_processed_counts([])
return state
|
'Generate new mapreduce id.'
| @staticmethod
def new_mapreduce_id():
| return _get_descending_key()
|
'Init.
Args:
base_path: base path of this mapreduce job.
mapreduce_spec: an instance of MapReduceSpec.
shard_id: shard id.
slice_id: slice id. When enqueuing task for the next slice, this number
is incremented by 1.
input_reader: input reader instance for this shard.
initial_input_reader: the input reader instance befo... | def __init__(self, base_path, mapreduce_spec, shard_id, slice_id, input_reader, initial_input_reader, output_writer=None, retries=0, handler=None):
| self.base_path = base_path
self.mapreduce_spec = mapreduce_spec
self.shard_id = shard_id
self.slice_id = slice_id
self.input_reader = input_reader
self.initial_input_reader = initial_input_reader
self.output_writer = output_writer
self.retries = retries
self.handler = handler
|
'Reset self for shard retry.
Args:
output_writer: new output writer that contains new output files.'
| def reset_for_retry(self, output_writer):
| self.input_reader = self.initial_input_reader
self.slice_id = 0
self.retries += 1
self.output_writer = output_writer
self.handler = None
|
'Advance relavent states for next slice.'
| def advance_for_next_slice(self):
| self.slice_id += 1
|
'Convert state to dictionary to save in task payload.'
| def to_dict(self):
| result = {'mapreduce_spec': self.mapreduce_spec.to_json_str(), 'shard_id': self.shard_id, 'slice_id': str(self.slice_id), 'input_reader_state': self.input_reader.to_json_str(), 'initial_input_reader_state': self.initial_input_reader.to_json_str(), 'retries': str(self.retries)}
if self.output_writer:
res... |
'Create new TransientShardState from webapp request.'
| @classmethod
def from_request(cls, request):
| mapreduce_spec = MapreduceSpec.from_json_str(request.get('mapreduce_spec'))
mapper_spec = mapreduce_spec.mapper
input_reader_spec_dict = json.loads(request.get('input_reader_state'), cls=JsonDecoder)
input_reader = mapper_spec.input_reader_class().from_json(input_reader_spec_dict)
initial_input_read... |
'Reset self for shard retry.'
| def reset_for_retry(self):
| self.retries += 1
self.last_work_item = ''
self.active = True
self.result_status = None
self.counters_map = CountersMap()
self.slice_id = 0
self.slice_start_time = None
self.slice_request_id = None
self.slice_retries = 0
|
'Advance self for next slice.'
| def advance_for_next_slice(self):
| self.slice_id += 1
self.slice_start_time = None
self.slice_request_id = None
self.slice_retries = 0
|
'Copy data from another shard state entity to self.'
| def copy_from(self, other_state):
| for prop in self.properties().values():
setattr(self, prop.name, getattr(other_state, prop.name))
|
'Gets the shard number from the key name.'
| def get_shard_number(self):
| return int(self.key().name().split('-')[(-1)])
|
'Returns the shard ID.'
| def get_shard_id(self):
| return self.key().name()
|
'Returns entity kind.'
| @classmethod
def kind(cls):
| return '_GAE_MR_ShardState'
|
'Get shard id by mapreduce id and shard number.
Args:
mapreduce_id: mapreduce id as string.
shard_number: shard number to compute id for as int.
Returns:
shard id as string.'
| @classmethod
def shard_id_from_number(cls, mapreduce_id, shard_number):
| return ('%s-%d' % (mapreduce_id, shard_number))
|
'Retrieves the Key for this ShardState.
Args:
shard_id: The shard ID to fetch.
Returns:
The Datatore key to use to retrieve this ShardState.'
| @classmethod
def get_key_by_shard_id(cls, shard_id):
| return db.Key.from_path(cls.kind(), shard_id)
|
'Get shard state from datastore by shard_id.
Args:
shard_id: shard id as string.
Returns:
ShardState for given shard id or None if it\'s not found.'
| @classmethod
def get_by_shard_id(cls, shard_id):
| return cls.get_by_key_name(shard_id)
|
'Find all shard states for given mapreduce.
Args:
mapreduce_state: MapreduceState instance
Returns:
iterable of all ShardState for given mapreduce.'
| @classmethod
def find_by_mapreduce_state(cls, mapreduce_state):
| keys = cls.calculate_keys_by_mapreduce_state(mapreduce_state)
return [state for state in db.get(keys) if state]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.