docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Build an HTML tag from the given name and attributes. Arguments: name -- the name of the tag (p, div, etc.) attrs -- a dict of attributes to apply to the tag start_end -- whether this tag should be self-closing
def make_tag(name, attrs, start_end=False): text = '<' + name if isinstance(attrs, dict): attr_list = attrs.items() elif isinstance(attrs, list): attr_list = attrs elif attrs is not None: raise TypeError("Unhandled attrs type " + str(type(attrs))) for key, val in attr...
627,554
Given a file path and an acceptable list of templates, return the best-matching template's path relative to the configured template directory. Arguments: category -- The path to map template_list -- A template to look up (as a string), or a list of templates.
def map_template(category, template_list): if isinstance(template_list, str): template_list = [template_list] for template in template_list: path = os.path.normpath(category) while path is not None: for extension in ['', '.html', '.htm', '.xml', '.json']: ...
627,604
Render an error page. Arguments: category -- The category of the request error_message -- The message to provide to the error template error_codes -- The applicable HTTP error code(s). Will usually be an integer or a list of integers; the HTTP error response will always be the first er...
def render_error(category, error_message, error_codes, exception=None): if isinstance(error_codes, int): error_codes = [error_codes] error_code = error_codes[0] template_list = [str(code) for code in error_codes] template_list.append(str(int(error_code / 100) * 100)) template_list.app...
627,608
Render a category page. Arguments: category -- The category to render template -- The template to render it with
def render_category(category='', template=None): # pylint:disable=too-many-return-statements # See if this is an aliased path redir = get_redirect() if redir: return redir # Forbidden template types if template and template.startswith('_'): raise http_error.Forbidden("Temp...
627,611
Render an entry page. Arguments: entry_id -- The numeric ID of the entry to render slug_text -- The expected URL slug text category -- The expected category
def render_entry(entry_id, slug_text='', category=''): # pylint: disable=too-many-return-statements # check if it's a valid entry record = model.Entry.get(id=entry_id) if not record: # It's not a valid entry, so see if it's a redirection path_redirect = get_redirect() if p...
627,612
Set a path alias. Arguments: alias -- The alias specification entry -- The entry to alias it to category -- The category to alias it to url -- The external URL to alias it to
def set_alias(alias, **kwargs): spec = alias.split() path = spec[0] values = {**kwargs, 'path': path} if len(spec) > 1: values['template'] = spec[1] record = model.PathAlias.get(path=path) if record: record.set(**values) else: record = model.PathAlias(**value...
627,637
Remove a path alias. Arguments: path -- the path to remove the alias of
def remove_alias(path): orm.delete(p for p in model.PathAlias if p.path == path) orm.commit()
627,638
Get a redirect from a path or list of paths Arguments: paths -- either a single path string, or a list of paths to check Returns: a flask.redirect() result
def get_redirect(paths): if isinstance(paths, str): paths = [paths] for path in paths: url, permanent = get_alias(path) if url: return redirect(url, 301 if permanent else 302) url, permanent = current_app.get_path_regex(path) if url: return...
627,641
Generate a where clause for currently-visible entries Arguments: date -- The date to generate it relative to (defaults to right now)
def where_entry_visible(query, date=None): return orm.select( e for e in query if e.status == model.PublishStatus.PUBLISHED.value or (e.status == model.PublishStatus.SCHEDULED.value and (e.utc_date <= (date or arrow.utcnow().datetime)) ) )
627,710
Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): encoding type (only for binary access) Returns: io.BytesIO OR io.TextIOWrapper: buffer accessing the file as bytes or characters
def open(self, mode='r', encoding=None): access_type = self._get_access_type(mode) if encoding is None: encoding = self.encoding # here, we face the task of returning the correct data type if access_type == 'b': if not self._isbytes: con...
627,774
Write the file to the given path Args: filename (str): path to write this file to encoding (str): file encoding (default: system default) Returns: LocalFile: reference to the copy of the file stored at ``filename``
def put(self, filename, encoding=None): from . import LocalFile if os.path.isdir(filename) and self.source is None: raise ValueError("Cannot write this object to " "directory %s without an explicit filename." % filename) target = get_target_pat...
627,777
Store any methods or variables bound from the function's closure Args: func (function): function to inspect Returns: dict: mapping of variable names to globally bound VARIABLES
def get_global_vars(func): closure = getclosurevars(func) if closure['nonlocal']: raise TypeError("Can't launch a job with closure variables: %s" % closure['nonlocals'].keys()) globalvars = dict(modules={}, functions={}, vars={...
627,778
Return the source code for a class or function. Notes: Returned source will not include any decorators for the object. This will only return the explicit declaration of the object, not any dependencies Args: classorfunc (type or function): the object to get the source code for Ret...
def getsource(classorfunc): if _isbuiltin(classorfunc): return '' try: source = inspect.getsource(classorfunc) except TypeError: # raised if defined in __main__ - use fallback to get the source instead source = getsourcefallback(classorfunc) declaration = [] lines = ...
627,779
Initialization: Args: client (docker.Client): a docker-py client. If not passed, we will try to create the client from the job's environmental varaibles workingdir (str): default working directory to create in the containers
def __init__(self, client=None, workingdir='/workingdir'): self.client = self.connect_to_docker(client) self.default_wdir = workingdir self.hostname = self.client.base_url
627,782
Return a Job object for the requested job id. The returned object will be suitable for retrieving output, but depending on the engine, may not populate all fields used at launch time (such as `job.inputs`, `job.commands`, etc.) Args: jobid (str): container id Returns: ...
def get_job(self, jobid): import shlex from pyccc.job import Job job = Job(engine=self) job.jobid = job.rundata.containerid = jobid try: jobdata = self.client.inspect_container(job.jobid) except docker.errors.NotFound: raise exceptions.Jo...
627,784
Submit job to the engine Args: job (pyccc.job.Job): Job to submit
def submit(self, job): self._check_job(job) if job.workingdir is None: job.workingdir = self.default_wdir job.imageid = du.create_provisioned_image(self.client, job.image, job.workingdir, job.inputs) container_args ...
627,785
Write a tar stream of the build context to the provided buffer Args: build_context (Mapping[str, pyccc.FileReferenceBase]): dict mapping filenames to file references buffer (io.BytesIO): writable binary mode buffer
def make_tar_stream(build_context, buffer): tf = tarfile.TarFile(fileobj=buffer, mode='w') for context_path, fileobj in build_context.items(): if getattr(fileobj, 'localpath', None) is not None: tf.add(fileobj.localpath, arcname=context_path) else: tar_add_bytes(tf, ...
627,805
Add a file to a tar archive Args: tf (tarfile.TarFile): tarfile to add the file to filename (str): path within the tar file bytestring (bytes or str): file contents. Must be :class:`bytes` or ascii-encodable :class:`str`
def tar_add_bytes(tf, filename, bytestring): if not isinstance(bytestring, bytes): # it hasn't been encoded yet bytestring = bytestring.encode('ascii') buff = io.BytesIO(bytestring) tarinfo = tarfile.TarInfo(filename) tarinfo.size = len(bytestring) tf.addfile(tarinfo, buff)
627,806
Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect Args: b (bytes): byte string Returns: str: decoded text string
def autodecode(b): import warnings import chardet try: return b.decode() except UnicodeError: result = chardet.detect(b) if result['confidence'] < 0.95: warnings.warn('autodecode failed with utf-8; guessing %s' % result['encoding']) return result.decode(...
627,819
Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename``
def put(self, filename, encoding=None): from . import LocalFile if os.path.isdir(filename) and self.source is None: raise ValueError("Cannot write this object to " "directory %s without an explicit filename." % filename) target = get_target_pat...
627,846
Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): text decoding method for text access (default: system default) Returns: io.BytesIO OR io.TextIOWrapper: buffer accessing the file as bytes or characters
def open(self, mode='r', encoding=None): access_type = self._get_access_type(mode) if access_type == 't' and encoding is not None and encoding != self.encoded_with: warnings.warn('Attempting to decode %s as "%s", but encoding is declared as "%s"' % (self, ...
627,847
Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename``
def put(self, filename): from . import LocalFile target = get_target_path(filename, self.source) with self.open('rb') as infile, open(target, 'wb') as outfile: shutil.copyfileobj(infile, outfile) return LocalFile(target)
627,860
Copy the referenced directory to this path The semantics of this command are similar to unix ``cp``: if ``destination`` already exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If it does not already exist, the directory will be renamed to this path (the ...
def put(self, destination): target = get_target_path(destination, self.localpath) shutil.copytree(self.localpath, target)
627,864
Copy the referenced directory to this path Note: This ignores anything not in the desired directory, given by ``self.dirname``. Args: destination (str): path to put this directory (which must NOT already exist) References: https://stackoverflow.com/a/826108...
def put(self, destination): target = get_target_path(destination, self.dirname) valid_paths = (self.dirname, './%s' % self.dirname) with tarfile.open(self.archive_path, 'r:*') as tf: members = [] for tarinfo in tf: # Get only files under the dire...
627,866
Copy the referenced directory to this path Args: destination (str): path to put this directory (which must NOT already exist)
def put(self, destination): if not self._fetched: self._fetch() DirectoryArchive.put(self, destination)
627,868
Create a job on this engine Args: image (str): name of the docker image to launch command (str): shell command to run
def launch(self, image, command, **kwargs): if isinstance(command, PythonCall): return PythonJob(self, image, command, **kwargs) else: return Job(self, image, command, **kwargs)
627,871
Recursively remove duplucates from all lists. Args: obj: collection to deduplicate exclude_keys (Container[str]): key names to ignore for deduplication
def dedupe_all_lists(obj, exclude_keys=()): squared_dedupe_len = 10 if isinstance(obj, dict): new_obj = {} for key, value in obj.items(): if key in exclude_keys: new_obj[key] = value else: new_obj[key] = dedupe_all_lists(value) ...
628,238
Convert a MARCXML string to a JSON record. Tries to guess which set of rules to use by inspecting the contents of the ``980__a`` MARC field, but falls back to HEP in case nothing matches, because records belonging to special collections logically belong to the Literature collection but don't have ``980...
def marcxml2record(marcxml): marcjson = create_record(marcxml, keep_singletons=False) collections = _get_collections(marcjson) if 'conferences' in collections: return conferences.do(marcjson) elif 'data' in collections: return data.do(marcjson) elif 'experiment' in collections:...
628,318
Convert a JSON record to a MARCXML string. Deduces which set of rules to use by parsing the ``$schema`` key, as it unequivocally determines which kind of record we have. Args: record(dict): a JSON record. Returns: str: a MARCXML string converted from the record.
def record2marcxml(record): schema_name = _get_schema_name(record) if schema_name == 'hep': marcjson = hep2marc.do(record) elif schema_name == 'authors': marcjson = hepnames2marc.do(record) else: raise NotImplementedError(u'JSON -> MARC rules missing for "{}"'.format(schema...
628,319
Passes the coefficients to the Malin and Barraclough routine (function pmag.magsyn) to calculate the field from the coefficients. Parameters: ----------- lon = east longitude in degrees (0 to 360 or -180 to 180) lat = latitude in degrees (-90 to 90) alt = height above mean sea level in km ...
def docustom(lon, lat, alt, gh): model, date, itype = 0, 0, 1 sv = np.zeros(len(gh)) colat = 90. - lat x, y, z, f = magsyn(gh, sv, model, date, itype, alt, colat, lon) return x, y, z, f
629,118
Make a time scale plot between specified ages. Parameters: ------------ ax : figure object agemin : Minimum age for timescale agemax : Maximum age for timescale timescale : Time Scale [ default is Gradstein et al., (2012)] for other options see pmag.get_ts() ylabel : if set, plot as ...
def plot_ts(ax, agemin, agemax, timescale='gts12', ylabel="Age (Ma)"): ax.set_title(timescale.upper()) ax.axis([-.25, 1.5, agemax, agemin]) ax.axes.get_xaxis().set_visible(False) # get dates and chron names for timescale TS, Chrons = pmag.get_ts(timescale) X, Y, Y2 = [0, 1], [], [] cnt ...
630,118
Add new item to the list. If needed, append will first flush existing items and clear existing items. Args: item: an item to add to the list.
def append(self, item): if self.should_flush(): self.flush() self.items.append(item)
631,497
Constructor. Args: max_entity_count: maximum number of entities before flushing it to db. mapreduce_spec: An optional instance of MapperSpec.
def __init__(self, max_entity_count=MAX_ENTITY_COUNT, mapreduce_spec=None): self.max_entity_count = max_entity_count params = mapreduce_spec.params if mapreduce_spec is not None else {} self.force_writes = bool(params.get("force_ops_writes", False)) self.puts = _ItemLi...
631,500
Registers entity to put to datastore. Args: entity: an entity or model instance to put.
def put(self, entity): actual_entity = _normalize_entity(entity) if actual_entity is None: return self.ndb_put(entity) self.puts.append(actual_entity)
631,501
Registers entity to delete from datastore. Args: entity: an entity, model instance, or key to delete.
def delete(self, entity): key = _normalize_key(entity) if key is None: return self.ndb_delete(entity) self.deletes.append(key)
631,503
Increment counter value. Args: counter_name: name of the counter as string. delta: increment delta as int.
def increment(self, counter_name, delta=1): self._shard_state.counters_map.increment(counter_name, delta)
631,511
Constructor. Args: mapreduce_spec: mapreduce specification as model.MapreduceSpec. shard_state: an instance of model.ShardState. This has to be the same instance as the one MapperWorkerHandler mutates. All mutations are flushed to datastore in the end of the slice. task_retry_coun...
def __init__(self, mapreduce_spec, shard_state, task_retry_count=0): self._shard_state = shard_state self.mapreduce_spec = mapreduce_spec # TODO(user): Create a hierarchy of Context classes. Certain fields # like task_retry_count only makes sense in TaskAttemptContext. self.task_retry_count = t...
631,512
Init. Args: p_range: a property_range.PropertyRange object that defines the conditions entities should safisfy. ns_range: a namesrange.NamespaceRange object that defines the namespaces to examine. query_spec: a model.QuerySpec object that defines how to retrieve entities f...
def __init__(self, p_range, ns_range, query_spec): self._property_range = p_range self._ns_range = ns_range self._query_spec = query_spec self._cursor = None self._query = None
631,513
Init. Args: k_ranges: a key_ranges._KeyRanges object. query_spec: a model.query_spec object that defines how to retrieve entities from datastore. key_range_iter_cls: the class that iterates over a single key range. The value yielded by this class is yielded.
def __init__(self, k_ranges, query_spec, key_range_iter_cls): self._key_ranges = k_ranges self._query_spec = query_spec self._key_range_iter_cls = key_range_iter_cls self._current_iter = None self._current_key_range = None
631,519
Init. Args: k_range: a key_range.KeyRange object that defines the entity keys to operate on. KeyRange object already contains a namespace. query_spec: a model.query_spec object that defines how to retrieve entities from datastore.
def __init__(self, k_range, query_spec): self._key_range = k_range self._query_spec = query_spec self._cursor = None self._query = None
631,523
Traverse directory trees to find mapreduce.yaml file. Begins with the location of status.py and then moves on to check the working directory. Args: status_file: location of status.py, overridable for testing purposes. Returns: the path of mapreduce.yaml file or None if not found.
def find_mapreduce_yaml(status_file=__file__): checked = set() yaml = _find_mapreduce_yaml(os.path.dirname(status_file), checked) if not yaml: yaml = _find_mapreduce_yaml(os.getcwd(), checked) return yaml
631,530
Traverse the directory tree identified by start until a directory already in checked is encountered or the path of mapreduce.yaml is found. Checked is present both to make loop termination easy to reason about and so that the same directories do not get rechecked. Args: start: the path to start in and wor...
def _find_mapreduce_yaml(start, checked): dir = start while dir not in checked: checked.add(dir) for mr_yaml_name in MR_YAML_NAMES: yaml_path = os.path.join(dir, mr_yaml_name) if os.path.exists(yaml_path): return yaml_path dir = os.path.dirname(dir) return None
631,531
Parses mapreduce.yaml file contents. Args: contents: mapreduce.yaml file contents. Returns: MapReduceYaml object with all the data from original file. Raises: errors.BadYamlError: when contents is not a valid mapreduce.yaml file.
def parse_mapreduce_yaml(contents): try: builder = yaml_object.ObjectBuilder(MapReduceYaml) handler = yaml_builder.BuilderHandler(builder) listener = yaml_listener.EventListener(handler) listener.Parse(contents) mr_info = handler.GetResults() except (ValueError, yaml_errors.EventError), e: ...
631,532
Locates mapreduce.yaml, loads and parses its info. Args: parse: Used for testing. Returns: MapReduceYaml object. Raises: errors.BadYamlError: when contents is not a valid mapreduce.yaml file or the file is missing.
def get_mapreduce_yaml(parse=parse_mapreduce_yaml): mr_yaml_path = find_mapreduce_yaml() if not mr_yaml_path: raise errors.MissingYamlError() mr_yaml_file = open(mr_yaml_path) try: return parse(mr_yaml_file.read()) finally: mr_yaml_file.close()
631,533
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...
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["ma...
631,534
Validates relevant parameters. This method can validate fields which it deems relevant. Args: job_config: an instance of map_job.JobConfig. Raises: errors.BadReaderParamsError: required parameters are missing or invalid.
def validate(cls, job_config): if job_config.input_reader_cls != cls: raise errors.BadReaderParamsError( "Expect input reader class %r, got %r." % (cls, job_config.input_reader_cls))
631,538
Map function sorting records. Converts records to KeyValue protos, sorts them by key and writes them into new GCS file. Creates _OutputFile entity to record resulting file name. Args: records: list of records which are serialized KeyValue protos.
def _sort_records_map(records): ctx = context.get() l = len(records) key_records = [None] * l logging.debug("Parsing") for i in range(l): proto = kv_pb.KeyValue() proto.ParseFromString(records[i]) key_records[i] = (proto.key(), records[i]) logging.debug("Sorting") key_records.sort(cmp=_co...
631,539
A map function used in merge phase. Stores (key, values) into KeyValues proto and yields its serialization. Args: key: values key. values: values themselves. partial: True if more values for this key will follow. False otherwise. Yields: The proto.
def _merge_map(key, values, partial): proto = kv_pb.KeyValues() proto.set_key(key) proto.value_list().extend(values) yield proto.Encode()
631,540
A map function used in hash phase. Reads KeyValue from binary record. Args: binary_record: The binary record. Yields: The (key, value).
def _hashing_map(binary_record): proto = kv_pb.KeyValue() proto.ParseFromString(binary_record) yield (proto.key(), proto.value())
631,541
Constructor. Args: offsets: offsets for each input file to start from as list of ints. max_values_count: maximum number of values to yield for a single value at a time. Ignored if -1. max_values_size: maximum total size of yielded values. Ignored if -1
def __init__(self, offsets, max_values_count, max_values_size): self._offsets = offsets self._max_values_count = max_values_count self._max_values_size = max_values_size
631,546
Constructor. Args: filehandles: list of file handles that this writer outputs to.
def __init__(self, filehandles): self._filehandles = filehandles self._pools = [None] * len(filehandles)
631,550
Validates mapper specification. Args: mapper_spec: an instance of model.MapperSpec to validate. Raises: BadWriterParamsError: when Output writer class mismatch.
def validate(cls, mapper_spec): if mapper_spec.output_writer_class() != cls: raise errors.BadWriterParamsError("Output writer class mismatch") params = output_writers._get_params(mapper_spec) # Bucket Name is required if cls.BUCKET_NAME_PARAM not in params: raise errors.BadWriterParamsE...
631,551
Write data. Args: data: actual data yielded from handler. Type is writer-specific.
def write(self, data): ctx = context.get() if len(data) != 2: logging.error("Got bad tuple of length %d (2-tuple expected): %s", len(data), data) try: key = str(data[0]) value = str(data[1]) except TypeError: logging.error("Expecting a tuple, but got %s:...
631,556
Converts model.MapreduceSpec back to JobConfig. This method allows our internal methods to use JobConfig directly. This method also allows us to expose JobConfig as an API during execution, despite that it is not saved into datastore. Args: mr_spec: model.MapreduceSpec. queue_name: queue n...
def _to_map_job_config(cls, mr_spec, # TODO(user): Remove this parameter after it can be # read from mr_spec. queue_name): mapper_spec = mr_spec.mapper # 0 means all the old APIs before api_version is introd...
631,570
Write single record. Args: data: record data to write as string, byte array or byte sequence.
def write(self, data): block_remaining = _BLOCK_SIZE - self.__position % _BLOCK_SIZE if block_remaining < _HEADER_LENGTH: # Header won't fit into remainder self.__writer.write('\x00' * block_remaining) self.__position += block_remaining block_remaining = _BLOCK_SIZE if block_r...
631,590
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
631,598
Execute operation. Args: context: mapreduce context as context.Context.
def __call__(self, context): context._counters.increment(self.counter_name, self.delta)
631,599
Creates a _Config class and modifies its class dict. Args: classname: name of the class. bases: a list of base classes. class_dict: original class dict. Returns: A new _Config class. The modified class will have two fields. _options field is a dict from option name to _Option obj...
def __new__(mcs, classname, bases, class_dict): options = {} required = set() for name, option in class_dict.iteritems(): if isinstance(option, _Option): options[name] = option if option.required: required.add(name) for name in options: class_dict.pop(name) ...
631,600
Init. Args: kind: type of the option. required: whether user is required to supply a value. default_factory: a factory, when called, returns the default value. can_be_none: whether value can be None. Raises: ValueError: if arguments aren't compatible.
def __init__(self, kind, required=False, default_factory=None, can_be_none=False): if required and default_factory is not None: raise ValueError("No default_factory value when option is required.") self.kind = kind self.required = required self.default_factory = default_factory...
631,601
Init. Args: _lenient: When true, no option is required. **kwds: keyword arguments for options and their values.
def __init__(self, _lenient=False, **kwds): self._verify_keys(kwds, _lenient) self._set_values(kwds, _lenient)
631,602
Init the job instance representing the job with id job_id. Do not directly call this method. Use class methods to construct new instances. Args: state: model.MapreduceState.
def __init__(self, state=None): self._state = state self.job_config = map_job_config.JobConfig._to_map_job_config( state.mapreduce_spec, queue_name=state.mapreduce_spec.params.get("queue_name"))
631,605
Get the value of the named counter from this job. When a job is running, counter values won't be very accurate. Args: counter_name: name of the counter in string. default: default value if the counter doesn't exist. Returns: Value in int of the named counter.
def get_counter(self, counter_name, default=0): self.__update_state() return self._state.counters_map.get(counter_name, default)
631,607
Get job state by id. Args: job_id: job id. Returns: model.MapreduceState for the job. Raises: ValueError: if the job state is missing.
def __get_state_by_id(cls, job_id): state = model.MapreduceState.get_by_job_id(job_id) if state is None: raise ValueError("Job state for job %s is missing." % job_id) return state
631,611
Save map job state to datastore. Save state to datastore so that UI can see it immediately. Args: job_config: map_job.JobConfig. mapreduce_spec: model.MapreduceSpec. Returns: model.MapreduceState for this job.
def __create_and_save_state(cls, job_config, mapreduce_spec): state = model.MapreduceState.create_new(job_config.job_id) state.mapreduce_spec = mapreduce_spec state.active = True state.active_shards = 0 state.app_id = job_config._app config = datastore_rpc.Configuration(force_writes=job_con...
631,613
Add kickoff task to taskqueue. Args: job_config: map_job.JobConfig. mapreduce_spec: model.MapreduceSpec,
def __add_kickoff_task(cls, job_config, mapreduce_spec): params = {"mapreduce_id": job_config.job_id} # Task is not named so that it can be added within a transaction. kickoff_task = taskqueue.Task( # TODO(user): Perhaps make this url a computed field of job_config. url=job_config._base...
631,614
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.
def from_json_str(cls, json_str): return cls.from_json(json.loads(json_str, cls=JsonDecoder))
631,616
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
631,617
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 data...
631,618
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 = json.loads(value, cls=JsonDecoder) if self.data_type == dict: return _json return self.data_type.from_json(_json)
631,619
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)
631,620
Init. Args: url: task url in str. params: a dict from str to str. name: task name. eta: task eta. countdown: task countdown. parent: parent entity of huge task's payload. headers: a dict of headers for the task. Raises: ValueError: when payload is too big even f...
def __init__(self, url, params, name=None, eta=None, countdown=None, parent=None, headers=None): self.url = url self.name = name self.eta = eta self.countdown = countdown self._headers = { ...
631,621
Decode task payload. HugeTask controls its own payload entirely including urlencoding. It doesn't depend on any particular web framework. Args: request: a webapp Request instance. Returns: A dict of str to str. The same as the params argument to __init__. Raises: DeprecationWar...
def decode_payload(cls, request): # TODO(user): Pass mr_id into headers. Otherwise when payload decoding # failed, we can't abort a mr. if request.headers.get(cls.PAYLOAD_VERSION_HEADER) != cls.PAYLOAD_VERSION: raise DeprecationWarning( "Task is generated by an older incompatible versio...
631,624
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
631,626
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])
631,627
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])
631,628
Create new MapreduceSpec from the json, encoded by to_json. Args: json: json representation of MapreduceSpec. Returns: an instance of MapreduceSpec with all data deserialized from json.
def from_json(cls, json): mapreduce_spec = cls(json["name"], json["mapreduce_id"], json["mapper_spec"], json.get("params"), json.get("hooks_class_name")) return mapreduce_spec
631,636
Retrieves the Key for a Job. Args: mapreduce_id: The job to retrieve. Returns: Datastore Key that can be used to fetch the MapreduceState.
def get_key_by_job_id(cls, mapreduce_id): return db.Key.from_path(cls.kind(), str(mapreduce_id))
631,638
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, shards_status): chart = google_chart_api.BarChart() def filter_status(status_to_filter): return [count if status == status_to_filter else 0 for count, status in zip(shards_processed, shards_status)] if shards_status: # Each in...
631,639
Create a new MapreduceState. Args: mapreduce_id: Mapreduce id as string. gettime: Used for testing.
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...
631,640
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 = self.mapreduce_spec.mapper.handler
631,643
Advance relavent states for next slice. Args: recovery_slice: True if this slice is running recovery logic. See handlers.MapperWorkerCallbackHandler._attempt_slice_recovery for more info.
def advance_for_next_slice(self, recovery_slice=False): if recovery_slice: self.slice_id += 2 # Restore input reader to the beginning of the slice. self.input_reader = self.input_reader.from_json(self._input_reader_json) else: self.slice_id += 1
631,644
Advance self for next slice. Args: recovery_slice: True if this slice is running recovery logic. See handlers.MapperWorkerCallbackHandler._attempt_slice_recovery for more info.
def advance_for_next_slice(self, recovery_slice=False): self.slice_start_time = None self.slice_request_id = None self.slice_retries = 0 self.acquired_once = False if recovery_slice: self.slice_id += 2 else: self.slice_id += 1
631,649
Find all shard states for given mapreduce. Args: mapreduce_state: MapreduceState instance Yields: shard states sorted by shard id.
def find_all_by_mapreduce_state(cls, mapreduce_state): keys = cls.calculate_keys_by_mapreduce_state(mapreduce_state) i = 0 while i < len(keys): @db.non_transactional def no_tx_get(i): return db.get(keys[i:i+cls._MAX_STATES_IN_MEMORY]) # We need a separate function to so that w...
631,652
Calculate all shard states keys for given mapreduce. Args: mapreduce_state: MapreduceState instance Returns: A list of keys for shard states, sorted by shard id. The corresponding shard states may not exist.
def calculate_keys_by_mapreduce_state(cls, mapreduce_state): if mapreduce_state is None: return [] keys = [] for i in range(mapreduce_state.mapreduce_spec.mapper.shard_count): shard_id = cls.shard_id_from_number(mapreduce_state.key().name(), i) keys.append(cls.get_key_by_shard_id(sha...
631,653
Create new shard state. Args: mapreduce_id: unique mapreduce id as string. shard_number: shard number for which to create shard state. Returns: new instance of ShardState ready to put into datastore.
def create_new(cls, mapreduce_id, shard_number): shard_id = cls.shard_id_from_number(mapreduce_id, shard_number) state = cls(key_name=shard_id, mapreduce_id=mapreduce_id) return state
631,654
Retrieves the Key for a mapreduce ID. Args: mapreduce_id: The job to fetch. Returns: Datastore Key for the command for the given job ID.
def get_key_by_job_id(cls, mapreduce_id): return db.Key.from_path(cls.kind(), "%s:%s" % (mapreduce_id, cls._KEY_NAME))
631,655
Causes a job to abort. Args: mapreduce_id: The job to abort. Not verified as a valid job.
def abort(cls, mapreduce_id, **kwargs): cls(key_name="%s:%s" % (mapreduce_id, cls._KEY_NAME), command=cls.ABORT).put(**kwargs)
631,656
Initialize. 1. call webapp init. 2. check request is indeed from taskqueue. 3. check the task has not been retried too many times. 4. run handler specific processing logic. 5. run error handling logic if precessing failed. Args: request: a webapp.Request instance. response: a webap...
def initialize(self, request, response): super(TaskQueueHandler, self).initialize(request, response) # Check request is from taskqueue. if "X-AppEngine-QueueName" not in self.request.headers: logging.error(self.request.headers) logging.error("Task queue handler received non-task queue requ...
631,661
Init. Instances are pickle safe. Args: seg_prefix: filename prefix for all segs. It is expected seg_prefix + index = seg filename. last_seg_index: the last index of all segs. int.
def __init__(self, seg_prefix, last_seg_index): self._EOF = False self._offset = 0 # fields related to seg. self._seg_prefix = seg_prefix self._last_seg_index = last_seg_index self._seg_index = -1 self._seg_valid_length = None self._seg = None self._next_seg()
631,667
Read data from file segs. Args: n: max bytes to read. Must be positive. Returns: some bytes. May be smaller than n bytes. "" when no more data is left.
def read(self, n): if self._EOF: return "" while self._seg_index <= self._last_seg_index: result = self._read_from_seg(n) if result != "": return result else: self._next_seg() self._EOF = True return ""
631,668
Read from current seg. Args: n: max number of bytes to read. Returns: valid bytes from the current seg. "" if no more is left.
def _read_from_seg(self, n): result = self._seg.read(size=n) if result == "": return result offset = self._seg.tell() if offset > self._seg_valid_length: extra = offset - self._seg_valid_length result = result[:-1*extra] self._offset += len(result) return result
631,670
Returns a key name lexically ordered by time descending. This lets us have a key name for use with Datastore entities which returns rows in time descending order when it is scanned in lexically ascending order, allowing us to bypass index building for descending indexes. Args: gettime: Used for testing. ...
def _get_descending_key(gettime=time.time): now_descending = int((_FUTURE_TIME - gettime()) * 100) request_id_hash = os.environ.get("REQUEST_ID_HASH") if not request_id_hash: request_id_hash = str(random.getrandbits(32)) return "%d%s" % (now_descending, request_id_hash)
631,671
convert a timedelta to seconds. This is patterned after timedelta.total_seconds, which is only available in python 27. Args: td: a timedelta object. Returns: total seconds within a timedelta. Rounded up to seconds.
def total_seconds(td): secs = td.seconds + td.days * 24 * 3600 if td.microseconds: secs += 1 return secs
631,674
Resolves and instantiates handler by fully qualified name. First resolves the name using for_name call. Then if it resolves to a class, instantiates a class, if it resolves to a method - instantiates the class and binds method to the instance. Args: fq_name: fully qualified name of something to find. R...
def handler_for_name(fq_name): resolved_name = for_name(fq_name) if isinstance(resolved_name, (type, types.ClassType)): # create new instance if this is type return resolved_name() elif isinstance(resolved_name, types.MethodType): # bind the method return getattr(resolved_name.im_class(), resol...
631,675
Try to serialize map/reduce handler. Args: handler: handler function/instance. Handler can be a function or an instance of a callable class. In the latter case, the handler will be serialized across slices to allow users to save states. Returns: serialized handler string or None.
def try_serialize_handler(handler): if (isinstance(handler, types.InstanceType) or # old style class (isinstance(handler, object) and # new style class not inspect.isfunction(handler) and not inspect.ismethod(handler)) and hasattr(handler, "__call__")): return pickle.dumps(handler) ...
631,676
Return true if the object is generator or generator function. Generator function objects provides same attributes as functions. See isfunction.__doc__ for attributes listing. Adapted from Python 2.6. Args: obj: an object to test. Returns: true if the object is generator function.
def is_generator(obj): if isinstance(obj, types.GeneratorType): return True CO_GENERATOR = 0x20 return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and obj.func_code.co_flags & CO_GENERATOR))
631,677
Creates datastore config to use in write operations. Args: mapreduce_spec: current mapreduce specification as MapreduceSpec. Returns: an instance of datastore_rpc.Configuration to use for all write operations in the mapreduce.
def create_datastore_write_config(mapreduce_spec): force_writes = parse_bool(mapreduce_spec.params.get("force_writes", "false")) if force_writes: return datastore_rpc.Configuration(force_writes=force_writes) else: # dev server doesn't support force_writes. return datastore_rpc.Configuration()
631,679
Returns the fully qualified path to the object. Args: obj: obj must be a new style top level class, or a top level function. No inner function or static method. Returns: Fully qualified path to the object. Raises: TypeError: when argument obj has unsupported type. ValueError: when obj can...
def _obj_to_path(obj): if obj is None: return obj if inspect.isclass(obj) or inspect.isfunction(obj): fetched = getattr(sys.modules[obj.__module__], obj.__name__, None) if fetched is None: raise ValueError( "Object %r must be defined on the top level of a module." % obj) return "...
631,681
Strips out the prefix from each of the items if it is present. Args: prefix: the string for that you wish to strip from the beginning of each of the items. items: a list of strings that may or may not contain the prefix you want to strip out. Returns: items_no_prefix: a copy of the list of...
def strip_prefix_from_items(prefix, items): items_no_prefix = [] for item in items: if item.startswith(prefix): items_no_prefix.append(item[len(prefix):]) else: items_no_prefix.append(item) return items_no_prefix
631,682
Invokes hooks.method(task, queue_name). Args: hooks: A hooks.Hooks instance or None. method: The name of the method to invoke on the hooks class e.g. "enqueue_kickoff_task". task: The taskqueue.Task to pass to the hook method. queue_name: The name of the queue to pass to the hook method. R...
def _run_task_hook(hooks, method, task, queue_name): if hooks is not None: try: getattr(hooks, method)(task, queue_name) except NotImplementedError: # Use the default task addition implementation. return False return True return False
631,683