repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/input_readers.py
_GoogleCloudStorageInputReader.next
def next(self): """Returns the next input from this input reader, a block of bytes. Non existent files will be logged and skipped. The file might have been removed after input splitting. Returns: The next input from this input reader in the form of a cloudstorage ReadBuffer that supports a...
python
def next(self): """Returns the next input from this input reader, a block of bytes. Non existent files will be logged and skipped. The file might have been removed after input splitting. Returns: The next input from this input reader in the form of a cloudstorage ReadBuffer that supports a...
[ "def", "next", "(", "self", ")", ":", "options", "=", "{", "}", "if", "self", ".", "_buffer_size", ":", "options", "[", "\"read_buffer_size\"", "]", "=", "self", ".", "_buffer_size", "if", "self", ".", "_account_id", ":", "options", "[", "\"_account_id\"",...
Returns the next input from this input reader, a block of bytes. Non existent files will be logged and skipped. The file might have been removed after input splitting. Returns: The next input from this input reader in the form of a cloudstorage ReadBuffer that supports a File-like interface (r...
[ "Returns", "the", "next", "input", "from", "this", "input", "reader", "a", "block", "of", "bytes", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L2478-L2518
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/input_readers.py
_GoogleCloudStorageRecordInputReader.next
def next(self): """Returns the next input from this input reader, a record. Returns: The next input from this input reader in the form of a record read from an LevelDB file. Raises: StopIteration: The ordered set records has been exhausted. """ while True: if not hasattr(se...
python
def next(self): """Returns the next input from this input reader, a record. Returns: The next input from this input reader in the form of a record read from an LevelDB file. Raises: StopIteration: The ordered set records has been exhausted. """ while True: if not hasattr(se...
[ "def", "next", "(", "self", ")", ":", "while", "True", ":", "if", "not", "hasattr", "(", "self", ",", "\"_cur_handle\"", ")", "or", "self", ".", "_cur_handle", "is", "None", ":", "# If there are no more files, StopIteration is raised here", "self", ".", "_cur_ha...
Returns the next input from this input reader, a record. Returns: The next input from this input reader in the form of a record read from an LevelDB file. Raises: StopIteration: The ordered set records has been exhausted.
[ "Returns", "the", "next", "input", "from", "this", "input", "reader", "a", "record", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L2559-L2590
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/input_readers.py
_ReducerReader.to_json
def to_json(self): """Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader. """ result = super(_ReducerReader, self).to_json() result["current_key"] = self.encode_data(self.current_key) result["current_values"] = self.encode_da...
python
def to_json(self): """Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader. """ result = super(_ReducerReader, self).to_json() result["current_key"] = self.encode_data(self.current_key) result["current_values"] = self.encode_da...
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "_ReducerReader", ",", "self", ")", ".", "to_json", "(", ")", "result", "[", "\"current_key\"", "]", "=", "self", ".", "encode_data", "(", "self", ".", "current_key", ")", "result", ...
Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader.
[ "Returns", "an", "input", "shard", "state", "for", "the", "remaining", "inputs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L2693-L2702
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/input_readers.py
_ReducerReader.from_json
def from_json(cls, json): """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. """ result = super(_ReducerReader, cls).from_json(j...
python
def from_json(cls, json): """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. """ result = super(_ReducerReader, cls).from_json(j...
[ "def", "from_json", "(", "cls", ",", "json", ")", ":", "result", "=", "super", "(", "_ReducerReader", ",", "cls", ")", ".", "from_json", "(", "json", ")", "result", ".", "current_key", "=", "_ReducerReader", ".", "decode_data", "(", "json", "[", "\"curre...
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.
[ "Creates", "an", "instance", "of", "the", "InputReader", "for", "the", "given", "input", "shard", "state", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L2705-L2717
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/map_job_context.py
ShardContext.incr
def incr(self, counter_name, delta=1): """Changes counter by delta. Args: counter_name: the name of the counter to change. str. delta: int. """ self._state.counters_map.increment(counter_name, delta)
python
def incr(self, counter_name, delta=1): """Changes counter by delta. Args: counter_name: the name of the counter to change. str. delta: int. """ self._state.counters_map.increment(counter_name, delta)
[ "def", "incr", "(", "self", ",", "counter_name", ",", "delta", "=", "1", ")", ":", "self", ".", "_state", ".", "counters_map", ".", "increment", "(", "counter_name", ",", "delta", ")" ]
Changes counter by delta. Args: counter_name: the name of the counter to change. str. delta: int.
[ "Changes", "counter", "by", "delta", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/map_job_context.py#L63-L70
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/map_job_context.py
ShardContext.counter
def counter(self, counter_name, default=0): """Get the current counter value. Args: counter_name: name of the counter in string. default: default value in int if one doesn't exist. Returns: Current value of the counter. """ return self._state.counters_map.get(counter_name, defaul...
python
def counter(self, counter_name, default=0): """Get the current counter value. Args: counter_name: name of the counter in string. default: default value in int if one doesn't exist. Returns: Current value of the counter. """ return self._state.counters_map.get(counter_name, defaul...
[ "def", "counter", "(", "self", ",", "counter_name", ",", "default", "=", "0", ")", ":", "return", "self", ".", "_state", ".", "counters_map", ".", "get", "(", "counter_name", ",", "default", ")" ]
Get the current counter value. Args: counter_name: name of the counter in string. default: default value in int if one doesn't exist. Returns: Current value of the counter.
[ "Get", "the", "current", "counter", "value", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/map_job_context.py#L72-L82
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/map_job_context.py
SliceContext.emit
def emit(self, value): """Emits a value to output writer. Args: value: a value of type expected by the output writer. """ if not self._tstate.output_writer: logging.error("emit is called, but no output writer is set.") return self._tstate.output_writer.write(value)
python
def emit(self, value): """Emits a value to output writer. Args: value: a value of type expected by the output writer. """ if not self._tstate.output_writer: logging.error("emit is called, but no output writer is set.") return self._tstate.output_writer.write(value)
[ "def", "emit", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "_tstate", ".", "output_writer", ":", "logging", ".", "error", "(", "\"emit is called, but no output writer is set.\"", ")", "return", "self", ".", "_tstate", ".", "output_writer", "...
Emits a value to output writer. Args: value: a value of type expected by the output writer.
[ "Emits", "a", "value", "to", "output", "writer", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/map_job_context.py#L119-L128
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/lib/input_reader/_gcs.py
GCSInputReader.validate
def validate(cls, job_config): """Validate mapper specification. Args: job_config: map_job.JobConfig. Raises: BadReaderParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name. """ reader_params = job_config...
python
def validate(cls, job_config): """Validate mapper specification. Args: job_config: map_job.JobConfig. Raises: BadReaderParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name. """ reader_params = job_config...
[ "def", "validate", "(", "cls", ",", "job_config", ")", ":", "reader_params", "=", "job_config", ".", "input_reader_params", "# Bucket Name is required", "if", "cls", ".", "BUCKET_NAME_PARAM", "not", "in", "reader_params", ":", "raise", "errors", ".", "BadReaderParam...
Validate mapper specification. Args: job_config: map_job.JobConfig. Raises: BadReaderParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name.
[ "Validate", "mapper", "specification", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/lib/input_reader/_gcs.py#L164-L225
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/lib/input_reader/_gcs.py
GCSInputReader.split_input
def split_input(cls, job_config): """Returns a list of input readers. An equal number of input files are assigned to each shard (+/- 1). If there are fewer files than shards, fewer than the requested number of shards will be used. Input files are currently never split (although for some formats cou...
python
def split_input(cls, job_config): """Returns a list of input readers. An equal number of input files are assigned to each shard (+/- 1). If there are fewer files than shards, fewer than the requested number of shards will be used. Input files are currently never split (although for some formats cou...
[ "def", "split_input", "(", "cls", ",", "job_config", ")", ":", "reader_params", "=", "job_config", ".", "input_reader_params", "bucket", "=", "reader_params", "[", "cls", ".", "BUCKET_NAME_PARAM", "]", "filenames", "=", "reader_params", "[", "cls", ".", "OBJECT_...
Returns a list of input readers. An equal number of input files are assigned to each shard (+/- 1). If there are fewer files than shards, fewer than the requested number of shards will be used. Input files are currently never split (although for some formats could be and may be split in a future implem...
[ "Returns", "a", "list", "of", "input", "readers", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/lib/input_reader/_gcs.py#L228-L269
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/lib/input_reader/_gcs.py
GCSInputReader.next
def next(self): """Returns a handler to the next file. Non existent files will be logged and skipped. The file might have been removed after input splitting. Returns: The next input from this input reader in the form of a cloudstorage ReadBuffer that supports a File-like interface (read, r...
python
def next(self): """Returns a handler to the next file. Non existent files will be logged and skipped. The file might have been removed after input splitting. Returns: The next input from this input reader in the form of a cloudstorage ReadBuffer that supports a File-like interface (read, r...
[ "def", "next", "(", "self", ")", ":", "options", "=", "{", "}", "if", "self", ".", "_buffer_size", ":", "options", "[", "\"read_buffer_size\"", "]", "=", "self", ".", "_buffer_size", "if", "self", ".", "_account_id", ":", "options", "[", "\"_account_id\"",...
Returns a handler to the next file. Non existent files will be logged and skipped. The file might have been removed after input splitting. Returns: The next input from this input reader in the form of a cloudstorage ReadBuffer that supports a File-like interface (read, readline, seek, te...
[ "Returns", "a", "handler", "to", "the", "next", "file", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/lib/input_reader/_gcs.py#L289-L325
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/lib/input_reader/_gcs.py
GCSInputReader.params_to_json
def params_to_json(cls, params): """Inherit docs.""" params_cp = dict(params) if cls.PATH_FILTER_PARAM in params_cp: path_filter = params_cp[cls.PATH_FILTER_PARAM] params_cp[cls.PATH_FILTER_PARAM] = pickle.dumps(path_filter) return params_cp
python
def params_to_json(cls, params): """Inherit docs.""" params_cp = dict(params) if cls.PATH_FILTER_PARAM in params_cp: path_filter = params_cp[cls.PATH_FILTER_PARAM] params_cp[cls.PATH_FILTER_PARAM] = pickle.dumps(path_filter) return params_cp
[ "def", "params_to_json", "(", "cls", ",", "params", ")", ":", "params_cp", "=", "dict", "(", "params", ")", "if", "cls", ".", "PATH_FILTER_PARAM", "in", "params_cp", ":", "path_filter", "=", "params_cp", "[", "cls", ".", "PATH_FILTER_PARAM", "]", "params_cp"...
Inherit docs.
[ "Inherit", "docs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/lib/input_reader/_gcs.py#L348-L354
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/lib/input_reader/_gcs.py
GCSRecordInputReader.next
def next(self): """Returns the next input from this input reader, a record. Returns: The next input from this input reader in the form of a record read from an LevelDB file. Raises: StopIteration: The ordered set records has been exhausted. """ while True: if not hasattr(se...
python
def next(self): """Returns the next input from this input reader, a record. Returns: The next input from this input reader in the form of a record read from an LevelDB file. Raises: StopIteration: The ordered set records has been exhausted. """ while True: if not hasattr(se...
[ "def", "next", "(", "self", ")", ":", "while", "True", ":", "if", "not", "hasattr", "(", "self", ",", "\"_cur_handle\"", ")", "or", "self", ".", "_cur_handle", "is", "None", ":", "# If there are no more files, StopIteration is raised here", "self", ".", "_cur_ha...
Returns the next input from this input reader, a record. Returns: The next input from this input reader in the form of a record read from an LevelDB file. Raises: StopIteration: The ordered set records has been exhausted.
[ "Returns", "the", "next", "input", "from", "this", "input", "reader", "a", "record", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/lib/input_reader/_gcs.py#L379-L405
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py
AbstractDatastoreInputReader._get_query_spec
def _get_query_spec(cls, params): """Construct a model.QuerySpec from model.MapperSpec.""" entity_kind = params[cls.ENTITY_KIND_PARAM] filters = params.get(cls.FILTERS_PARAM) app = params.get(cls._APP_PARAM) ns = params.get(cls.NAMESPACE_PARAM) return model.QuerySpec( entity_kind=cls._g...
python
def _get_query_spec(cls, params): """Construct a model.QuerySpec from model.MapperSpec.""" entity_kind = params[cls.ENTITY_KIND_PARAM] filters = params.get(cls.FILTERS_PARAM) app = params.get(cls._APP_PARAM) ns = params.get(cls.NAMESPACE_PARAM) return model.QuerySpec( entity_kind=cls._g...
[ "def", "_get_query_spec", "(", "cls", ",", "params", ")", ":", "entity_kind", "=", "params", "[", "cls", ".", "ENTITY_KIND_PARAM", "]", "filters", "=", "params", ".", "get", "(", "cls", ".", "FILTERS_PARAM", ")", "app", "=", "params", ".", "get", "(", ...
Construct a model.QuerySpec from model.MapperSpec.
[ "Construct", "a", "model", ".", "QuerySpec", "from", "model", ".", "MapperSpec", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py#L86-L100
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py
AbstractDatastoreInputReader.split_input
def split_input(cls, job_config): """Inherit doc.""" shard_count = job_config.shard_count params = job_config.input_reader_params query_spec = cls._get_query_spec(params) namespaces = None if query_spec.ns is not None: k_ranges = cls._to_key_ranges_by_shard( query_spec.app, [que...
python
def split_input(cls, job_config): """Inherit doc.""" shard_count = job_config.shard_count params = job_config.input_reader_params query_spec = cls._get_query_spec(params) namespaces = None if query_spec.ns is not None: k_ranges = cls._to_key_ranges_by_shard( query_spec.app, [que...
[ "def", "split_input", "(", "cls", ",", "job_config", ")", ":", "shard_count", "=", "job_config", ".", "shard_count", "params", "=", "job_config", ".", "input_reader_params", "query_spec", "=", "cls", ".", "_get_query_spec", "(", "params", ")", "namespaces", "=",...
Inherit doc.
[ "Inherit", "doc", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py#L103-L138
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py
AbstractDatastoreInputReader._to_key_ranges_by_shard
def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec): """Get a list of key_ranges.KeyRanges objects, one for each shard. This method uses scatter index to split each namespace into pieces and assign those pieces to shards. Args: app: app_id in str. namespaces: a list ...
python
def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec): """Get a list of key_ranges.KeyRanges objects, one for each shard. This method uses scatter index to split each namespace into pieces and assign those pieces to shards. Args: app: app_id in str. namespaces: a list ...
[ "def", "_to_key_ranges_by_shard", "(", "cls", ",", "app", ",", "namespaces", ",", "shard_count", ",", "query_spec", ")", ":", "key_ranges_by_ns", "=", "[", "]", "# Split each ns into n splits. If a ns doesn't have enough scatter to", "# split into n, the last few splits are Non...
Get a list of key_ranges.KeyRanges objects, one for each shard. This method uses scatter index to split each namespace into pieces and assign those pieces to shards. Args: app: app_id in str. namespaces: a list of namespaces in str. shard_count: number of shards to split. query_spe...
[ "Get", "a", "list", "of", "key_ranges", ".", "KeyRanges", "objects", "one", "for", "each", "shard", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py#L141-L184
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py
AbstractDatastoreInputReader._split_ns_by_scatter
def _split_ns_by_scatter(cls, shard_count, namespace, raw_entity_kind, app): """Split a namespace by scatter index into key_range.KeyRange. TODO(user): Power this with key_range.KeyRange.compute_split_po...
python
def _split_ns_by_scatter(cls, shard_count, namespace, raw_entity_kind, app): """Split a namespace by scatter index into key_range.KeyRange. TODO(user): Power this with key_range.KeyRange.compute_split_po...
[ "def", "_split_ns_by_scatter", "(", "cls", ",", "shard_count", ",", "namespace", ",", "raw_entity_kind", ",", "app", ")", ":", "if", "shard_count", "==", "1", ":", "# With one shard we don't need to calculate any split points at all.", "return", "[", "key_range", ".", ...
Split a namespace by scatter index into key_range.KeyRange. TODO(user): Power this with key_range.KeyRange.compute_split_points. Args: shard_count: number of shards. namespace: namespace name to split. str. raw_entity_kind: low level datastore API entity kind. app: app id in str. ...
[ "Split", "a", "namespace", "by", "scatter", "index", "into", "key_range", ".", "KeyRange", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py#L187-L264
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py
AbstractDatastoreInputReader.validate
def validate(cls, job_config): """Inherit docs.""" super(AbstractDatastoreInputReader, cls).validate(job_config) params = job_config.input_reader_params # Check for the required entity kind parameter. if cls.ENTITY_KIND_PARAM not in params: raise errors.BadReaderParamsError("Missing input rea...
python
def validate(cls, job_config): """Inherit docs.""" super(AbstractDatastoreInputReader, cls).validate(job_config) params = job_config.input_reader_params # Check for the required entity kind parameter. if cls.ENTITY_KIND_PARAM not in params: raise errors.BadReaderParamsError("Missing input rea...
[ "def", "validate", "(", "cls", ",", "job_config", ")", ":", "super", "(", "AbstractDatastoreInputReader", ",", "cls", ")", ".", "validate", "(", "job_config", ")", "params", "=", "job_config", ".", "input_reader_params", "# Check for the required entity kind parameter...
Inherit docs.
[ "Inherit", "docs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/abstract_datastore_input_reader.py#L275-L321
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
_setup_constants
def _setup_constants(alphabet=NAMESPACE_CHARACTERS, max_length=MAX_NAMESPACE_LENGTH, batch_size=NAMESPACE_BATCH_SIZE): """Calculate derived constant values. Only useful for testing.""" global NAMESPACE_CHARACTERS global MAX_NAMESPACE_LENGTH # pylint: disable=global-var...
python
def _setup_constants(alphabet=NAMESPACE_CHARACTERS, max_length=MAX_NAMESPACE_LENGTH, batch_size=NAMESPACE_BATCH_SIZE): """Calculate derived constant values. Only useful for testing.""" global NAMESPACE_CHARACTERS global MAX_NAMESPACE_LENGTH # pylint: disable=global-var...
[ "def", "_setup_constants", "(", "alphabet", "=", "NAMESPACE_CHARACTERS", ",", "max_length", "=", "MAX_NAMESPACE_LENGTH", ",", "batch_size", "=", "NAMESPACE_BATCH_SIZE", ")", ":", "global", "NAMESPACE_CHARACTERS", "global", "MAX_NAMESPACE_LENGTH", "# pylint: disable=global-var...
Calculate derived constant values. Only useful for testing.
[ "Calculate", "derived", "constant", "values", ".", "Only", "useful", "for", "testing", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L48-L90
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
_ord_to_namespace
def _ord_to_namespace(n, _max_length=None): """Convert a namespace ordinal to a namespace string. Converts an int, representing the sequence number of a namespace ordered lexographically, into a namespace string. >>> _ord_to_namespace(0) '' >>> _ord_to_namespace(1) '-' >>> _ord_to_namespace(2) '--' ...
python
def _ord_to_namespace(n, _max_length=None): """Convert a namespace ordinal to a namespace string. Converts an int, representing the sequence number of a namespace ordered lexographically, into a namespace string. >>> _ord_to_namespace(0) '' >>> _ord_to_namespace(1) '-' >>> _ord_to_namespace(2) '--' ...
[ "def", "_ord_to_namespace", "(", "n", ",", "_max_length", "=", "None", ")", ":", "if", "_max_length", "is", "None", ":", "_max_length", "=", "MAX_NAMESPACE_LENGTH", "length", "=", "_LEX_DISTANCE", "[", "_max_length", "-", "1", "]", "if", "n", "==", "0", ":...
Convert a namespace ordinal to a namespace string. Converts an int, representing the sequence number of a namespace ordered lexographically, into a namespace string. >>> _ord_to_namespace(0) '' >>> _ord_to_namespace(1) '-' >>> _ord_to_namespace(2) '--' >>> _ord_to_namespace(3) '---' Args: n...
[ "Convert", "a", "namespace", "ordinal", "to", "a", "namespace", "string", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L94-L123
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
_namespace_to_ord
def _namespace_to_ord(namespace): """Converts a namespace string into an int representing its lexographic order. >>> _namespace_to_ord('') '' >>> _namespace_to_ord('_') 1 >>> _namespace_to_ord('__') 2 Args: namespace: A namespace string. Returns: An int representing the lexographical order ...
python
def _namespace_to_ord(namespace): """Converts a namespace string into an int representing its lexographic order. >>> _namespace_to_ord('') '' >>> _namespace_to_ord('_') 1 >>> _namespace_to_ord('__') 2 Args: namespace: A namespace string. Returns: An int representing the lexographical order ...
[ "def", "_namespace_to_ord", "(", "namespace", ")", ":", "n", "=", "0", "for", "i", ",", "c", "in", "enumerate", "(", "namespace", ")", ":", "n", "+=", "(", "_LEX_DISTANCE", "[", "MAX_NAMESPACE_LENGTH", "-", "i", "-", "1", "]", "*", "NAMESPACE_CHARACTERS"...
Converts a namespace string into an int representing its lexographic order. >>> _namespace_to_ord('') '' >>> _namespace_to_ord('_') 1 >>> _namespace_to_ord('__') 2 Args: namespace: A namespace string. Returns: An int representing the lexographical order of the given namespace string.
[ "Converts", "a", "namespace", "string", "into", "an", "int", "representing", "its", "lexographic", "order", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L126-L147
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
_key_for_namespace
def _key_for_namespace(namespace, app): """Return the __namespace__ key for a namespace. Args: namespace: The namespace whose key is requested. app: The id of the application that the key belongs to. Returns: A db.Key representing the namespace. """ if namespace: return db.Key.from_path(meta...
python
def _key_for_namespace(namespace, app): """Return the __namespace__ key for a namespace. Args: namespace: The namespace whose key is requested. app: The id of the application that the key belongs to. Returns: A db.Key representing the namespace. """ if namespace: return db.Key.from_path(meta...
[ "def", "_key_for_namespace", "(", "namespace", ",", "app", ")", ":", "if", "namespace", ":", "return", "db", ".", "Key", ".", "from_path", "(", "metadata", ".", "Namespace", ".", "KIND_NAME", ",", "namespace", ",", "_app", "=", "app", ")", "else", ":", ...
Return the __namespace__ key for a namespace. Args: namespace: The namespace whose key is requested. app: The id of the application that the key belongs to. Returns: A db.Key representing the namespace.
[ "Return", "the", "__namespace__", "key", "for", "a", "namespace", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L150-L167
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
get_namespace_keys
def get_namespace_keys(app, limit): """Get namespace keys.""" ns_query = datastore.Query('__namespace__', keys_only=True, _app=app) return list(ns_query.Run(limit=limit, batch_size=limit))
python
def get_namespace_keys(app, limit): """Get namespace keys.""" ns_query = datastore.Query('__namespace__', keys_only=True, _app=app) return list(ns_query.Run(limit=limit, batch_size=limit))
[ "def", "get_namespace_keys", "(", "app", ",", "limit", ")", ":", "ns_query", "=", "datastore", ".", "Query", "(", "'__namespace__'", ",", "keys_only", "=", "True", ",", "_app", "=", "app", ")", "return", "list", "(", "ns_query", ".", "Run", "(", "limit",...
Get namespace keys.
[ "Get", "namespace", "keys", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L457-L460
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
NamespaceRange.split_range
def split_range(self): """Splits the NamespaceRange into two nearly equal-sized ranges. Returns: If this NamespaceRange contains a single namespace then a list containing this NamespaceRange is returned. Otherwise a two-element list containing two NamespaceRanges whose total range is identica...
python
def split_range(self): """Splits the NamespaceRange into two nearly equal-sized ranges. Returns: If this NamespaceRange contains a single namespace then a list containing this NamespaceRange is returned. Otherwise a two-element list containing two NamespaceRanges whose total range is identica...
[ "def", "split_range", "(", "self", ")", ":", "if", "self", ".", "is_single_namespace", ":", "return", "[", "self", "]", "mid_point", "=", "(", "_namespace_to_ord", "(", "self", ".", "namespace_start", ")", "+", "_namespace_to_ord", "(", "self", ".", "namespa...
Splits the NamespaceRange into two nearly equal-sized ranges. Returns: If this NamespaceRange contains a single namespace then a list containing this NamespaceRange is returned. Otherwise a two-element list containing two NamespaceRanges whose total range is identical to this NamespaceRange...
[ "Splits", "the", "NamespaceRange", "into", "two", "nearly", "equal", "-", "sized", "ranges", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L225-L245
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
NamespaceRange.with_start_after
def with_start_after(self, after_namespace): """Returns a copy of this NamespaceName with a new namespace_start. Args: after_namespace: A namespace string. Returns: A NamespaceRange object whose namespace_start is the lexographically next namespace after the given namespace string. ...
python
def with_start_after(self, after_namespace): """Returns a copy of this NamespaceName with a new namespace_start. Args: after_namespace: A namespace string. Returns: A NamespaceRange object whose namespace_start is the lexographically next namespace after the given namespace string. ...
[ "def", "with_start_after", "(", "self", ",", "after_namespace", ")", ":", "namespace_start", "=", "_ord_to_namespace", "(", "_namespace_to_ord", "(", "after_namespace", ")", "+", "1", ")", "return", "NamespaceRange", "(", "namespace_start", ",", "self", ".", "name...
Returns a copy of this NamespaceName with a new namespace_start. Args: after_namespace: A namespace string. Returns: A NamespaceRange object whose namespace_start is the lexographically next namespace after the given namespace string. Raises: ValueError: if the NamespaceRange incl...
[ "Returns", "a", "copy", "of", "this", "NamespaceName", "with", "a", "new", "namespace_start", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L267-L281
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
NamespaceRange.make_datastore_query
def make_datastore_query(self, cursor=None): """Returns a datastore.Query that generates all namespaces in the range. Args: cursor: start cursor for the query. Returns: A datastore.Query instance that generates db.Keys for each namespace in the NamespaceRange. """ filters = {} ...
python
def make_datastore_query(self, cursor=None): """Returns a datastore.Query that generates all namespaces in the range. Args: cursor: start cursor for the query. Returns: A datastore.Query instance that generates db.Keys for each namespace in the NamespaceRange. """ filters = {} ...
[ "def", "make_datastore_query", "(", "self", ",", "cursor", "=", "None", ")", ":", "filters", "=", "{", "}", "filters", "[", "'__key__ >= '", "]", "=", "_key_for_namespace", "(", "self", ".", "namespace_start", ",", "self", ".", "app", ")", "filters", "[", ...
Returns a datastore.Query that generates all namespaces in the range. Args: cursor: start cursor for the query. Returns: A datastore.Query instance that generates db.Keys for each namespace in the NamespaceRange.
[ "Returns", "a", "datastore", ".", "Query", "that", "generates", "all", "namespaces", "in", "the", "range", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L283-L303
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
NamespaceRange.normalized_start
def normalized_start(self): """Returns a NamespaceRange with leading non-existant namespaces removed. Returns: A copy of this NamespaceRange whose namespace_start is adjusted to exclude the portion of the range that contains no actual namespaces in the datastore. None is returned if the Names...
python
def normalized_start(self): """Returns a NamespaceRange with leading non-existant namespaces removed. Returns: A copy of this NamespaceRange whose namespace_start is adjusted to exclude the portion of the range that contains no actual namespaces in the datastore. None is returned if the Names...
[ "def", "normalized_start", "(", "self", ")", ":", "namespaces_after_key", "=", "list", "(", "self", ".", "make_datastore_query", "(", ")", ".", "Run", "(", "limit", "=", "1", ")", ")", "if", "not", "namespaces_after_key", ":", "return", "None", "namespace_af...
Returns a NamespaceRange with leading non-existant namespaces removed. Returns: A copy of this NamespaceRange whose namespace_start is adjusted to exclude the portion of the range that contains no actual namespaces in the datastore. None is returned if the NamespaceRange contains no actual ...
[ "Returns", "a", "NamespaceRange", "with", "leading", "non", "-", "existant", "namespaces", "removed", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L305-L322
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
NamespaceRange.to_json_object
def to_json_object(self): """Returns a dict representation that can be serialized to JSON.""" obj_dict = dict(namespace_start=self.namespace_start, namespace_end=self.namespace_end) if self.app is not None: obj_dict['app'] = self.app return obj_dict
python
def to_json_object(self): """Returns a dict representation that can be serialized to JSON.""" obj_dict = dict(namespace_start=self.namespace_start, namespace_end=self.namespace_end) if self.app is not None: obj_dict['app'] = self.app return obj_dict
[ "def", "to_json_object", "(", "self", ")", ":", "obj_dict", "=", "dict", "(", "namespace_start", "=", "self", ".", "namespace_start", ",", "namespace_end", "=", "self", ".", "namespace_end", ")", "if", "self", ".", "app", "is", "not", "None", ":", "obj_dic...
Returns a dict representation that can be serialized to JSON.
[ "Returns", "a", "dict", "representation", "that", "can", "be", "serialized", "to", "JSON", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L324-L330
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/namespace_range.py
NamespaceRange.split
def split(cls, n, contiguous, can_query=itertools.chain(itertools.repeat(True, 50), itertools.repeat(False)).next, _app=None): # pylint: disable=g-doc-args """Splits the complete NamespaceRange into n equally-sized NamespaceRa...
python
def split(cls, n, contiguous, can_query=itertools.chain(itertools.repeat(True, 50), itertools.repeat(False)).next, _app=None): # pylint: disable=g-doc-args """Splits the complete NamespaceRange into n equally-sized NamespaceRa...
[ "def", "split", "(", "cls", ",", "n", ",", "contiguous", ",", "can_query", "=", "itertools", ".", "chain", "(", "itertools", ".", "repeat", "(", "True", ",", "50", ")", ",", "itertools", ".", "repeat", "(", "False", ")", ")", ".", "next", ",", "_ap...
Splits the complete NamespaceRange into n equally-sized NamespaceRanges. Args: n: The maximum number of NamespaceRanges to return. Fewer than n namespaces may be returned. contiguous: If True then the returned NamespaceRanges will cover the entire space of possible namespaces (i.e. ...
[ "Splits", "the", "complete", "NamespaceRange", "into", "n", "equally", "-", "sized", "NamespaceRanges", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/namespace_range.py#L343-L441
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_RecordsPoolBase.append
def append(self, data): """Append data to a file.""" data_length = len(data) if self._size + data_length > self._flush_size: self.flush() if not self._exclusive and data_length > _FILE_POOL_MAX_SIZE: raise errors.Error( "Too big input %s (%s)." % (data_length, _FILE_POOL_MAX_SIZE...
python
def append(self, data): """Append data to a file.""" data_length = len(data) if self._size + data_length > self._flush_size: self.flush() if not self._exclusive and data_length > _FILE_POOL_MAX_SIZE: raise errors.Error( "Too big input %s (%s)." % (data_length, _FILE_POOL_MAX_SIZE...
[ "def", "append", "(", "self", ",", "data", ")", ":", "data_length", "=", "len", "(", "data", ")", "if", "self", ".", "_size", "+", "data_length", ">", "self", ".", "_flush_size", ":", "self", ".", "flush", "(", ")", "if", "not", "self", ".", "_excl...
Append data to a file.
[ "Append", "data", "to", "a", "file", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L357-L371
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_RecordsPoolBase.flush
def flush(self): """Flush pool contents.""" # Write data to in-memory buffer first. buf = cStringIO.StringIO() with records.RecordsWriter(buf) as w: for record in self._buffer: w.write(record) w._pad_block() str_buf = buf.getvalue() buf.close() if not self._exclusive and...
python
def flush(self): """Flush pool contents.""" # Write data to in-memory buffer first. buf = cStringIO.StringIO() with records.RecordsWriter(buf) as w: for record in self._buffer: w.write(record) w._pad_block() str_buf = buf.getvalue() buf.close() if not self._exclusive and...
[ "def", "flush", "(", "self", ")", ":", "# Write data to in-memory buffer first.", "buf", "=", "cStringIO", ".", "StringIO", "(", ")", "with", "records", ".", "RecordsWriter", "(", "buf", ")", "as", "w", ":", "for", "record", "in", "self", ".", "_buffer", "...
Flush pool contents.
[ "Flush", "pool", "contents", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L373-L404
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
GCSRecordsPool._write
def _write(self, str_buf): """Uses the filehandle to the file in GCS to write to it.""" self._filehandle.write(str_buf) self._buf_size += len(str_buf)
python
def _write(self, str_buf): """Uses the filehandle to the file in GCS to write to it.""" self._filehandle.write(str_buf) self._buf_size += len(str_buf)
[ "def", "_write", "(", "self", ",", "str_buf", ")", ":", "self", ".", "_filehandle", ".", "write", "(", "str_buf", ")", "self", ".", "_buf_size", "+=", "len", "(", "str_buf", ")" ]
Uses the filehandle to the file in GCS to write to it.
[ "Uses", "the", "filehandle", "to", "the", "file", "in", "GCS", "to", "write", "to", "it", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L432-L435
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
GCSRecordsPool.flush
def flush(self, force=False): """Flush pool contents. Args: force: Inserts additional padding to achieve the minimum block size required for GCS. """ super(GCSRecordsPool, self).flush() if force: extra_padding = self._buf_size % self._GCS_BLOCK_SIZE if extra_padding > 0: ...
python
def flush(self, force=False): """Flush pool contents. Args: force: Inserts additional padding to achieve the minimum block size required for GCS. """ super(GCSRecordsPool, self).flush() if force: extra_padding = self._buf_size % self._GCS_BLOCK_SIZE if extra_padding > 0: ...
[ "def", "flush", "(", "self", ",", "force", "=", "False", ")", ":", "super", "(", "GCSRecordsPool", ",", "self", ")", ".", "flush", "(", ")", "if", "force", ":", "extra_padding", "=", "self", ".", "_buf_size", "%", "self", ".", "_GCS_BLOCK_SIZE", "if", ...
Flush pool contents. Args: force: Inserts additional padding to achieve the minimum block size required for GCS.
[ "Flush", "pool", "contents", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L437-L449
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageBase._get_tmp_gcs_bucket
def _get_tmp_gcs_bucket(cls, writer_spec): """Returns bucket used for writing tmp files.""" if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec[cls.TMP_BUCKET_NAME_PARAM] return cls._get_gcs_bucket(writer_spec)
python
def _get_tmp_gcs_bucket(cls, writer_spec): """Returns bucket used for writing tmp files.""" if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec[cls.TMP_BUCKET_NAME_PARAM] return cls._get_gcs_bucket(writer_spec)
[ "def", "_get_tmp_gcs_bucket", "(", "cls", ",", "writer_spec", ")", ":", "if", "cls", ".", "TMP_BUCKET_NAME_PARAM", "in", "writer_spec", ":", "return", "writer_spec", "[", "cls", ".", "TMP_BUCKET_NAME_PARAM", "]", "return", "cls", ".", "_get_gcs_bucket", "(", "wr...
Returns bucket used for writing tmp files.
[ "Returns", "bucket", "used", "for", "writing", "tmp", "files", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L497-L501
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageBase._get_tmp_account_id
def _get_tmp_account_id(cls, writer_spec): """Returns the account id to use with tmp bucket.""" # pick tmp id iff tmp bucket is set explicitly if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec.get(cls._TMP_ACCOUNT_ID_PARAM, None) return cls._get_account_id(writer_spec)
python
def _get_tmp_account_id(cls, writer_spec): """Returns the account id to use with tmp bucket.""" # pick tmp id iff tmp bucket is set explicitly if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec.get(cls._TMP_ACCOUNT_ID_PARAM, None) return cls._get_account_id(writer_spec)
[ "def", "_get_tmp_account_id", "(", "cls", ",", "writer_spec", ")", ":", "# pick tmp id iff tmp bucket is set explicitly", "if", "cls", ".", "TMP_BUCKET_NAME_PARAM", "in", "writer_spec", ":", "return", "writer_spec", ".", "get", "(", "cls", ".", "_TMP_ACCOUNT_ID_PARAM", ...
Returns the account id to use with tmp bucket.
[ "Returns", "the", "account", "id", "to", "use", "with", "tmp", "bucket", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L504-L509
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageOutputWriterBase._generate_filename
def _generate_filename(cls, writer_spec, name, job_id, num, attempt=None, seg_index=None): """Generates a filename for a particular output. Args: writer_spec: specification dictionary for the output writer. name: name of the job. job_id: the ID number assigned to the ...
python
def _generate_filename(cls, writer_spec, name, job_id, num, attempt=None, seg_index=None): """Generates a filename for a particular output. Args: writer_spec: specification dictionary for the output writer. name: name of the job. job_id: the ID number assigned to the ...
[ "def", "_generate_filename", "(", "cls", ",", "writer_spec", ",", "name", ",", "job_id", ",", "num", ",", "attempt", "=", "None", ",", "seg_index", "=", "None", ")", ":", "naming_format", "=", "cls", ".", "_TMP_FILE_NAMING_FORMAT", "if", "seg_index", "is", ...
Generates a filename for a particular output. Args: writer_spec: specification dictionary for the output writer. name: name of the job. job_id: the ID number assigned to the job. num: shard number. attempt: the shard attempt number. seg_index: index of the seg. None means the fi...
[ "Generates", "a", "filename", "for", "a", "particular", "output", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L536-L573
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageOutputWriterBase.validate
def validate(cls, mapper_spec): """Validate mapper specification. Args: mapper_spec: an instance of model.MapperSpec. Raises: BadWriterParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name. """ writer_spe...
python
def validate(cls, mapper_spec): """Validate mapper specification. Args: mapper_spec: an instance of model.MapperSpec. Raises: BadWriterParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name. """ writer_spe...
[ "def", "validate", "(", "cls", ",", "mapper_spec", ")", ":", "writer_spec", "=", "cls", ".", "get_params", "(", "mapper_spec", ",", "allow_old", "=", "False", ")", "# Bucket Name is required", "if", "cls", ".", "BUCKET_NAME_PARAM", "not", "in", "writer_spec", ...
Validate mapper specification. Args: mapper_spec: an instance of model.MapperSpec. Raises: BadWriterParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name.
[ "Validate", "mapper", "specification", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L586-L611
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageOutputWriterBase._open_file
def _open_file(cls, writer_spec, filename_suffix, use_tmp_bucket=False): """Opens a new gcs file for writing.""" if use_tmp_bucket: bucket = cls._get_tmp_gcs_bucket(writer_spec) account_id = cls._get_tmp_account_id(writer_spec) else: bucket = cls._get_gcs_bucket(writer_spec) account_...
python
def _open_file(cls, writer_spec, filename_suffix, use_tmp_bucket=False): """Opens a new gcs file for writing.""" if use_tmp_bucket: bucket = cls._get_tmp_gcs_bucket(writer_spec) account_id = cls._get_tmp_account_id(writer_spec) else: bucket = cls._get_gcs_bucket(writer_spec) account_...
[ "def", "_open_file", "(", "cls", ",", "writer_spec", ",", "filename_suffix", ",", "use_tmp_bucket", "=", "False", ")", ":", "if", "use_tmp_bucket", ":", "bucket", "=", "cls", ".", "_get_tmp_gcs_bucket", "(", "writer_spec", ")", "account_id", "=", "cls", ".", ...
Opens a new gcs file for writing.
[ "Opens", "a", "new", "gcs", "file", "for", "writing", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L614-L633
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageOutputWriterBase.write
def write(self, data): """Write data to the GoogleCloudStorage file. Args: data: string containing the data to be written. """ start_time = time.time() self._get_write_buffer().write(data) ctx = context.get() operation.counters.Increment(COUNTER_IO_WRITE_BYTES, len(data))(ctx) ope...
python
def write(self, data): """Write data to the GoogleCloudStorage file. Args: data: string containing the data to be written. """ start_time = time.time() self._get_write_buffer().write(data) ctx = context.get() operation.counters.Increment(COUNTER_IO_WRITE_BYTES, len(data))(ctx) ope...
[ "def", "write", "(", "self", ",", "data", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "_get_write_buffer", "(", ")", ".", "write", "(", "data", ")", "ctx", "=", "context", ".", "get", "(", ")", "operation", ".", "counte...
Write data to the GoogleCloudStorage file. Args: data: string containing the data to be written.
[ "Write", "data", "to", "the", "GoogleCloudStorage", "file", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L651-L662
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageOutputWriter.validate
def validate(cls, mapper_spec): """Inherit docs.""" writer_spec = cls.get_params(mapper_spec, allow_old=False) if writer_spec.get(cls._NO_DUPLICATE, False) not in (True, False): raise errors.BadWriterParamsError("No duplicate must a boolean.") super(_GoogleCloudStorageOutputWriter, cls).validate(m...
python
def validate(cls, mapper_spec): """Inherit docs.""" writer_spec = cls.get_params(mapper_spec, allow_old=False) if writer_spec.get(cls._NO_DUPLICATE, False) not in (True, False): raise errors.BadWriterParamsError("No duplicate must a boolean.") super(_GoogleCloudStorageOutputWriter, cls).validate(m...
[ "def", "validate", "(", "cls", ",", "mapper_spec", ")", ":", "writer_spec", "=", "cls", ".", "get_params", "(", "mapper_spec", ",", "allow_old", "=", "False", ")", "if", "writer_spec", ".", "get", "(", "cls", ".", "_NO_DUPLICATE", ",", "False", ")", "not...
Inherit docs.
[ "Inherit", "docs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L718-L723
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageOutputWriter.create
def create(cls, mr_spec, shard_number, shard_attempt, _writer_state=None): """Inherit docs.""" writer_spec = cls.get_params(mr_spec.mapper, allow_old=False) seg_index = None if writer_spec.get(cls._NO_DUPLICATE, False): seg_index = 0 # Determine parameters key = cls._generate_filename(wri...
python
def create(cls, mr_spec, shard_number, shard_attempt, _writer_state=None): """Inherit docs.""" writer_spec = cls.get_params(mr_spec.mapper, allow_old=False) seg_index = None if writer_spec.get(cls._NO_DUPLICATE, False): seg_index = 0 # Determine parameters key = cls._generate_filename(wri...
[ "def", "create", "(", "cls", ",", "mr_spec", ",", "shard_number", ",", "shard_attempt", ",", "_writer_state", "=", "None", ")", ":", "writer_spec", "=", "cls", ".", "get_params", "(", "mr_spec", ".", "mapper", ",", "allow_old", "=", "False", ")", "seg_inde...
Inherit docs.
[ "Inherit", "docs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L729-L741
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
_GoogleCloudStorageOutputWriter._create
def _create(cls, writer_spec, filename_suffix): """Helper method that actually creates the file in cloud storage.""" writer = cls._open_file(writer_spec, filename_suffix) return cls(writer, writer_spec=writer_spec)
python
def _create(cls, writer_spec, filename_suffix): """Helper method that actually creates the file in cloud storage.""" writer = cls._open_file(writer_spec, filename_suffix) return cls(writer, writer_spec=writer_spec)
[ "def", "_create", "(", "cls", ",", "writer_spec", ",", "filename_suffix", ")", ":", "writer", "=", "cls", ".", "_open_file", "(", "writer_spec", ",", "filename_suffix", ")", "return", "cls", "(", "writer", ",", "writer_spec", "=", "writer_spec", ")" ]
Helper method that actually creates the file in cloud storage.
[ "Helper", "method", "that", "actually", "creates", "the", "file", "in", "cloud", "storage", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L744-L747
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
GoogleCloudStorageConsistentOutputWriter.create
def create(cls, mr_spec, shard_number, shard_attempt, _writer_state=None): """Inherit docs.""" writer_spec = cls.get_params(mr_spec.mapper, allow_old=False) # Determine parameters key = cls._generate_filename(writer_spec, mr_spec.name, mr_spec.mapreduce_id, ...
python
def create(cls, mr_spec, shard_number, shard_attempt, _writer_state=None): """Inherit docs.""" writer_spec = cls.get_params(mr_spec.mapper, allow_old=False) # Determine parameters key = cls._generate_filename(writer_spec, mr_spec.name, mr_spec.mapreduce_id, ...
[ "def", "create", "(", "cls", ",", "mr_spec", ",", "shard_number", ",", "shard_attempt", ",", "_writer_state", "=", "None", ")", ":", "writer_spec", "=", "cls", ".", "get_params", "(", "mr_spec", ".", "mapper", ",", "allow_old", "=", "False", ")", "# Determ...
Inherit docs.
[ "Inherit", "docs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L912-L927
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
GoogleCloudStorageConsistentOutputWriter._rewrite_tmpfile
def _rewrite_tmpfile(self, mainfile, tmpfile, writer_spec): """Copies contents of tmpfile (name) to mainfile (buffer).""" if mainfile.closed: # can happen when finalize fails return account_id = self._get_tmp_account_id(writer_spec) f = cloudstorage_api.open(tmpfile, _account_id=account_id)...
python
def _rewrite_tmpfile(self, mainfile, tmpfile, writer_spec): """Copies contents of tmpfile (name) to mainfile (buffer).""" if mainfile.closed: # can happen when finalize fails return account_id = self._get_tmp_account_id(writer_spec) f = cloudstorage_api.open(tmpfile, _account_id=account_id)...
[ "def", "_rewrite_tmpfile", "(", "self", ",", "mainfile", ",", "tmpfile", ",", "writer_spec", ")", ":", "if", "mainfile", ".", "closed", ":", "# can happen when finalize fails", "return", "account_id", "=", "self", ".", "_get_tmp_account_id", "(", "writer_spec", ")...
Copies contents of tmpfile (name) to mainfile (buffer).
[ "Copies", "contents", "of", "tmpfile", "(", "name", ")", "to", "mainfile", "(", "buffer", ")", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L938-L952
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
GoogleCloudStorageConsistentOutputWriter._create_tmpfile
def _create_tmpfile(cls, status): """Creates a new random-named tmpfile.""" # We can't put the tmpfile in the same directory as the output. There are # rare circumstances when we leave trash behind and we don't want this trash # to be loaded into bigquery and/or used for restore. # # We used ma...
python
def _create_tmpfile(cls, status): """Creates a new random-named tmpfile.""" # We can't put the tmpfile in the same directory as the output. There are # rare circumstances when we leave trash behind and we don't want this trash # to be loaded into bigquery and/or used for restore. # # We used ma...
[ "def", "_create_tmpfile", "(", "cls", ",", "status", ")", ":", "# We can't put the tmpfile in the same directory as the output. There are", "# rare circumstances when we leave trash behind and we don't want this trash", "# to be loaded into bigquery and/or used for restore.", "#", "# We used...
Creates a new random-named tmpfile.
[ "Creates", "a", "new", "random", "-", "named", "tmpfile", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L955-L969
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/output_writers.py
GoogleCloudStorageConsistentOutputWriter._try_to_clean_garbage
def _try_to_clean_garbage(self, writer_spec, exclude_list=()): """Tries to remove any files created by this shard that aren't needed. Args: writer_spec: writer_spec for the MR. exclude_list: A list of filenames (strings) that should not be removed. """ # Try to remove garbage (if an...
python
def _try_to_clean_garbage(self, writer_spec, exclude_list=()): """Tries to remove any files created by this shard that aren't needed. Args: writer_spec: writer_spec for the MR. exclude_list: A list of filenames (strings) that should not be removed. """ # Try to remove garbage (if an...
[ "def", "_try_to_clean_garbage", "(", "self", ",", "writer_spec", ",", "exclude_list", "=", "(", ")", ")", ":", "# Try to remove garbage (if any). Note that listbucket is not strongly", "# consistent so something might survive.", "tmpl", "=", "string", ".", "Template", "(", ...
Tries to remove any files created by this shard that aren't needed. Args: writer_spec: writer_spec for the MR. exclude_list: A list of filenames (strings) that should not be removed.
[ "Tries", "to", "remove", "any", "files", "created", "by", "this", "shard", "that", "aren", "t", "needed", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/output_writers.py#L1014-L1032
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/sample_input_reader.py
SampleInputReader.from_json
def from_json(cls, state): """Inherit docs.""" return cls(state[cls.COUNT], state[cls.STRING_LENGTH])
python
def from_json(cls, state): """Inherit docs.""" return cls(state[cls.COUNT], state[cls.STRING_LENGTH])
[ "def", "from_json", "(", "cls", ",", "state", ")", ":", "return", "cls", "(", "state", "[", "cls", ".", "COUNT", "]", ",", "state", "[", "cls", ".", "STRING_LENGTH", "]", ")" ]
Inherit docs.
[ "Inherit", "docs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/sample_input_reader.py#L73-L75
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/sample_input_reader.py
SampleInputReader.split_input
def split_input(cls, job_config): """Inherit docs.""" params = job_config.input_reader_params count = params[cls.COUNT] string_length = params.get(cls.STRING_LENGTH, cls._DEFAULT_STRING_LENGTH) shard_count = job_config.shard_count count_per_shard = count // shard_count mr_input_readers = [...
python
def split_input(cls, job_config): """Inherit docs.""" params = job_config.input_reader_params count = params[cls.COUNT] string_length = params.get(cls.STRING_LENGTH, cls._DEFAULT_STRING_LENGTH) shard_count = job_config.shard_count count_per_shard = count // shard_count mr_input_readers = [...
[ "def", "split_input", "(", "cls", ",", "job_config", ")", ":", "params", "=", "job_config", ".", "input_reader_params", "count", "=", "params", "[", "cls", ".", "COUNT", "]", "string_length", "=", "params", ".", "get", "(", "cls", ".", "STRING_LENGTH", ","...
Inherit docs.
[ "Inherit", "docs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/sample_input_reader.py#L82-L98
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/sample_input_reader.py
SampleInputReader.validate
def validate(cls, job_config): """Inherit docs.""" super(SampleInputReader, cls).validate(job_config) params = job_config.input_reader_params # Validate count. if cls.COUNT not in params: raise errors.BadReaderParamsError("Must specify %s" % cls.COUNT) if not isinstance(params[cls.COUNT],...
python
def validate(cls, job_config): """Inherit docs.""" super(SampleInputReader, cls).validate(job_config) params = job_config.input_reader_params # Validate count. if cls.COUNT not in params: raise errors.BadReaderParamsError("Must specify %s" % cls.COUNT) if not isinstance(params[cls.COUNT],...
[ "def", "validate", "(", "cls", ",", "job_config", ")", ":", "super", "(", "SampleInputReader", ",", "cls", ")", ".", "validate", "(", "job_config", ")", "params", "=", "job_config", ".", "input_reader_params", "# Validate count.", "if", "cls", ".", "COUNT", ...
Inherit docs.
[ "Inherit", "docs", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/sample_input_reader.py#L101-L121
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/property_range.py
_get_weights
def _get_weights(max_length): """Get weights for each offset in str of certain max length. Args: max_length: max length of the strings. Returns: A list of ints as weights. Example: If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa", "ab", "b", "ba", "bb". So the weight fo...
python
def _get_weights(max_length): """Get weights for each offset in str of certain max length. Args: max_length: max length of the strings. Returns: A list of ints as weights. Example: If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa", "ab", "b", "ba", "bb". So the weight fo...
[ "def", "_get_weights", "(", "max_length", ")", ":", "weights", "=", "[", "1", "]", "for", "i", "in", "range", "(", "1", ",", "max_length", ")", ":", "weights", ".", "append", "(", "weights", "[", "i", "-", "1", "]", "*", "len", "(", "_ALPHABET", ...
Get weights for each offset in str of certain max length. Args: max_length: max length of the strings. Returns: A list of ints as weights. Example: If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa", "ab", "b", "ba", "bb". So the weight for the first char is 3.
[ "Get", "weights", "for", "each", "offset", "in", "str", "of", "certain", "max", "length", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/property_range.py#L355-L372
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/property_range.py
_str_to_ord
def _str_to_ord(content, weights): """Converts a string to its lexicographical order. Args: content: the string to convert. Of type str. weights: weights from _get_weights. Returns: an int or long that represents the order of this string. "" has order 0. """ ordinal = 0 for i, c in enumerate(c...
python
def _str_to_ord(content, weights): """Converts a string to its lexicographical order. Args: content: the string to convert. Of type str. weights: weights from _get_weights. Returns: an int or long that represents the order of this string. "" has order 0. """ ordinal = 0 for i, c in enumerate(c...
[ "def", "_str_to_ord", "(", "content", ",", "weights", ")", ":", "ordinal", "=", "0", "for", "i", ",", "c", "in", "enumerate", "(", "content", ")", ":", "ordinal", "+=", "weights", "[", "i", "]", "*", "_ALPHABET", ".", "index", "(", "c", ")", "+", ...
Converts a string to its lexicographical order. Args: content: the string to convert. Of type str. weights: weights from _get_weights. Returns: an int or long that represents the order of this string. "" has order 0.
[ "Converts", "a", "string", "to", "its", "lexicographical", "order", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/property_range.py#L375-L388
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/property_range.py
_ord_to_str
def _ord_to_str(ordinal, weights): """Reverse function of _str_to_ord.""" chars = [] for weight in weights: if ordinal == 0: return "".join(chars) ordinal -= 1 index, ordinal = divmod(ordinal, weight) chars.append(_ALPHABET[index]) return "".join(chars)
python
def _ord_to_str(ordinal, weights): """Reverse function of _str_to_ord.""" chars = [] for weight in weights: if ordinal == 0: return "".join(chars) ordinal -= 1 index, ordinal = divmod(ordinal, weight) chars.append(_ALPHABET[index]) return "".join(chars)
[ "def", "_ord_to_str", "(", "ordinal", ",", "weights", ")", ":", "chars", "=", "[", "]", "for", "weight", "in", "weights", ":", "if", "ordinal", "==", "0", ":", "return", "\"\"", ".", "join", "(", "chars", ")", "ordinal", "-=", "1", "index", ",", "o...
Reverse function of _str_to_ord.
[ "Reverse", "function", "of", "_str_to_ord", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/property_range.py#L391-L400
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/property_range.py
PropertyRange._get_range_from_filters
def _get_range_from_filters(cls, filters, model_class): """Get property range from filters user provided. This method also validates there is one and only one closed range on a single property. Args: filters: user supplied filters. Each filter should be a list or tuple of format (<proper...
python
def _get_range_from_filters(cls, filters, model_class): """Get property range from filters user provided. This method also validates there is one and only one closed range on a single property. Args: filters: user supplied filters. Each filter should be a list or tuple of format (<proper...
[ "def", "_get_range_from_filters", "(", "cls", ",", "filters", ",", "model_class", ")", ":", "if", "not", "filters", ":", "return", "None", ",", "None", ",", "None", "range_property", "=", "None", "start_val", "=", "None", "end_val", "=", "None", "start_filte...
Get property range from filters user provided. This method also validates there is one and only one closed range on a single property. Args: filters: user supplied filters. Each filter should be a list or tuple of format (<property_name_as_str>, <query_operator_as_str>, <value_of_cer...
[ "Get", "property", "range", "from", "filters", "user", "provided", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/property_range.py#L81-L162
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/property_range.py
PropertyRange.split
def split(self, n): """Evenly split this range into contiguous, non overlapping subranges. Args: n: number of splits. Returns: a list of contiguous, non overlapping sub PropertyRanges. Maybe less than n when not enough subranges. """ new_range_filters = [] name = self.start[0] ...
python
def split(self, n): """Evenly split this range into contiguous, non overlapping subranges. Args: n: number of splits. Returns: a list of contiguous, non overlapping sub PropertyRanges. Maybe less than n when not enough subranges. """ new_range_filters = [] name = self.start[0] ...
[ "def", "split", "(", "self", ",", "n", ")", ":", "new_range_filters", "=", "[", "]", "name", "=", "self", ".", "start", "[", "0", "]", "prop_cls", "=", "self", ".", "prop", ".", "__class__", "if", "prop_cls", "in", "_DISCRETE_PROPERTY_SPLIT_FUNCTIONS", "...
Evenly split this range into contiguous, non overlapping subranges. Args: n: number of splits. Returns: a list of contiguous, non overlapping sub PropertyRanges. Maybe less than n when not enough subranges.
[ "Evenly", "split", "this", "range", "into", "contiguous", "non", "overlapping", "subranges", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/property_range.py#L164-L199
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/property_range.py
PropertyRange.make_query
def make_query(self, ns): """Make a query of entities within this range. Query options are not supported. They should be specified when the query is run. Args: ns: namespace of this query. Returns: a db.Query or ndb.Query, depends on the model class's type. """ if issubclass(s...
python
def make_query(self, ns): """Make a query of entities within this range. Query options are not supported. They should be specified when the query is run. Args: ns: namespace of this query. Returns: a db.Query or ndb.Query, depends on the model class's type. """ if issubclass(s...
[ "def", "make_query", "(", "self", ",", "ns", ")", ":", "if", "issubclass", "(", "self", ".", "model_class", ",", "db", ".", "Model", ")", ":", "query", "=", "db", ".", "Query", "(", "self", ".", "model_class", ",", "namespace", "=", "ns", ")", "for...
Make a query of entities within this range. Query options are not supported. They should be specified when the query is run. Args: ns: namespace of this query. Returns: a db.Query or ndb.Query, depends on the model class's type.
[ "Make", "a", "query", "of", "entities", "within", "this", "range", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/property_range.py#L201-L221
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/output_writer.py
OutputWriter.validate
def validate(cls, job_config): """Validates relevant parameters. This method can validate fields which it deems relevant. Args: job_config: an instance of map_job.JobConfig. Raises: errors.BadWriterParamsError: required parameters are missing or invalid. """ if job_config.output_w...
python
def validate(cls, job_config): """Validates relevant parameters. This method can validate fields which it deems relevant. Args: job_config: an instance of map_job.JobConfig. Raises: errors.BadWriterParamsError: required parameters are missing or invalid. """ if job_config.output_w...
[ "def", "validate", "(", "cls", ",", "job_config", ")", ":", "if", "job_config", ".", "output_writer_cls", "!=", "cls", ":", "raise", "errors", ".", "BadWriterParamsError", "(", "\"Expect output writer class %r, got %r.\"", "%", "(", "cls", ",", "job_config", ".", ...
Validates relevant parameters. This method can validate fields which it deems relevant. Args: job_config: an instance of map_job.JobConfig. Raises: errors.BadWriterParamsError: required parameters are missing or invalid.
[ "Validates", "relevant", "parameters", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/output_writer.py#L50-L64
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/api/map_job/output_writer.py
OutputWriter.commit_output
def commit_output(cls, shard_ctx, iterator): """Saves output references when a shard finishes. Inside end_shard(), an output writer can optionally use this method to persist some references to the outputs from this shard (e.g a list of filenames) Args: shard_ctx: map_job_context.ShardContext...
python
def commit_output(cls, shard_ctx, iterator): """Saves output references when a shard finishes. Inside end_shard(), an output writer can optionally use this method to persist some references to the outputs from this shard (e.g a list of filenames) Args: shard_ctx: map_job_context.ShardContext...
[ "def", "commit_output", "(", "cls", ",", "shard_ctx", ",", "iterator", ")", ":", "# We accept an iterator just in case output references get too big.", "outs", "=", "tuple", "(", "iterator", ")", "shard_ctx", ".", "_state", ".", "writer_state", "[", "\"outs\"", "]", ...
Saves output references when a shard finishes. Inside end_shard(), an output writer can optionally use this method to persist some references to the outputs from this shard (e.g a list of filenames) Args: shard_ctx: map_job_context.ShardContext for this shard. iterator: an iterator that yi...
[ "Saves", "output", "references", "when", "a", "shard", "finishes", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/output_writer.py#L111-L127
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/main.py
create_handlers_map
def create_handlers_map(): """Create new handlers map. Returns: list of (regexp, handler) pairs for WSGIApplication constructor. """ pipeline_handlers_map = [] if pipeline: pipeline_handlers_map = pipeline.create_handlers_map(prefix=".*/pipeline") return pipeline_handlers_map + [ # Task que...
python
def create_handlers_map(): """Create new handlers map. Returns: list of (regexp, handler) pairs for WSGIApplication constructor. """ pipeline_handlers_map = [] if pipeline: pipeline_handlers_map = pipeline.create_handlers_map(prefix=".*/pipeline") return pipeline_handlers_map + [ # Task que...
[ "def", "create_handlers_map", "(", ")", ":", "pipeline_handlers_map", "=", "[", "]", "if", "pipeline", ":", "pipeline_handlers_map", "=", "pipeline", ".", "create_handlers_map", "(", "prefix", "=", "\".*/pipeline\"", ")", "return", "pipeline_handlers_map", "+", "[",...
Create new handlers map. Returns: list of (regexp, handler) pairs for WSGIApplication constructor.
[ "Create", "new", "handlers", "map", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/main.py#L58-L92
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/key_ranges.py
KeyRangesFactory.from_json
def from_json(cls, json): """Deserialize from json. Args: json: a dict of json compatible fields. Returns: a KeyRanges object. Raises: ValueError: if the json is invalid. """ if json["name"] in _KEYRANGES_CLASSES: return _KEYRANGES_CLASSES[json["name"]].from_json(json)...
python
def from_json(cls, json): """Deserialize from json. Args: json: a dict of json compatible fields. Returns: a KeyRanges object. Raises: ValueError: if the json is invalid. """ if json["name"] in _KEYRANGES_CLASSES: return _KEYRANGES_CLASSES[json["name"]].from_json(json)...
[ "def", "from_json", "(", "cls", ",", "json", ")", ":", "if", "json", "[", "\"name\"", "]", "in", "_KEYRANGES_CLASSES", ":", "return", "_KEYRANGES_CLASSES", "[", "json", "[", "\"name\"", "]", "]", ".", "from_json", "(", "json", ")", "raise", "ValueError", ...
Deserialize from json. Args: json: a dict of json compatible fields. Returns: a KeyRanges object. Raises: ValueError: if the json is invalid.
[ "Deserialize", "from", "json", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/key_ranges.py#L58-L72
GoogleCloudPlatform/appengine-mapreduce
python/demo/main.py
split_into_sentences
def split_into_sentences(s): """Split text into list of sentences.""" s = re.sub(r"\s+", " ", s) s = re.sub(r"[\\.\\?\\!]", "\n", s) return s.split("\n")
python
def split_into_sentences(s): """Split text into list of sentences.""" s = re.sub(r"\s+", " ", s) s = re.sub(r"[\\.\\?\\!]", "\n", s) return s.split("\n")
[ "def", "split_into_sentences", "(", "s", ")", ":", "s", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "\" \"", ",", "s", ")", "s", "=", "re", ".", "sub", "(", "r\"[\\\\.\\\\?\\\\!]\"", ",", "\"\\n\"", ",", "s", ")", "return", "s", ".", "split", "("...
Split text into list of sentences.
[ "Split", "text", "into", "list", "of", "sentences", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/demo/main.py#L181-L185
GoogleCloudPlatform/appengine-mapreduce
python/demo/main.py
split_into_words
def split_into_words(s): """Split a sentence into list of words.""" s = re.sub(r"\W+", " ", s) s = re.sub(r"[_0-9]+", " ", s) return s.split()
python
def split_into_words(s): """Split a sentence into list of words.""" s = re.sub(r"\W+", " ", s) s = re.sub(r"[_0-9]+", " ", s) return s.split()
[ "def", "split_into_words", "(", "s", ")", ":", "s", "=", "re", ".", "sub", "(", "r\"\\W+\"", ",", "\" \"", ",", "s", ")", "s", "=", "re", ".", "sub", "(", "r\"[_0-9]+\"", ",", "\" \"", ",", "s", ")", "return", "s", ".", "split", "(", ")" ]
Split a sentence into list of words.
[ "Split", "a", "sentence", "into", "list", "of", "words", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/demo/main.py#L188-L192
GoogleCloudPlatform/appengine-mapreduce
python/demo/main.py
index_map
def index_map(data): """Index demo map function.""" (entry, text_fn) = data text = text_fn() logging.debug("Got %s", entry.filename) for s in split_into_sentences(text): for w in split_into_words(s.lower()): yield (w, entry.filename)
python
def index_map(data): """Index demo map function.""" (entry, text_fn) = data text = text_fn() logging.debug("Got %s", entry.filename) for s in split_into_sentences(text): for w in split_into_words(s.lower()): yield (w, entry.filename)
[ "def", "index_map", "(", "data", ")", ":", "(", "entry", ",", "text_fn", ")", "=", "data", "text", "=", "text_fn", "(", ")", "logging", ".", "debug", "(", "\"Got %s\"", ",", "entry", ".", "filename", ")", "for", "s", "in", "split_into_sentences", "(", ...
Index demo map function.
[ "Index", "demo", "map", "function", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/demo/main.py#L211-L219
GoogleCloudPlatform/appengine-mapreduce
python/demo/main.py
phrases_map
def phrases_map(data): """Phrases demo map function.""" (entry, text_fn) = data text = text_fn() filename = entry.filename logging.debug("Got %s", filename) for s in split_into_sentences(text): words = split_into_words(s.lower()) if len(words) < PHRASE_LENGTH: yield (":".join(words), filename...
python
def phrases_map(data): """Phrases demo map function.""" (entry, text_fn) = data text = text_fn() filename = entry.filename logging.debug("Got %s", filename) for s in split_into_sentences(text): words = split_into_words(s.lower()) if len(words) < PHRASE_LENGTH: yield (":".join(words), filename...
[ "def", "phrases_map", "(", "data", ")", ":", "(", "entry", ",", "text_fn", ")", "=", "data", "text", "=", "text_fn", "(", ")", "filename", "=", "entry", ".", "filename", "logging", ".", "debug", "(", "\"Got %s\"", ",", "filename", ")", "for", "s", "i...
Phrases demo map function.
[ "Phrases", "demo", "map", "function", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/demo/main.py#L230-L243
GoogleCloudPlatform/appengine-mapreduce
python/demo/main.py
phrases_reduce
def phrases_reduce(key, values): """Phrases demo reduce function.""" if len(values) < 10: return counts = {} for filename in values: counts[filename] = counts.get(filename, 0) + 1 words = re.sub(r":", " ", key) threshold = len(values) / 2 for filename, count in counts.items(): if count > thre...
python
def phrases_reduce(key, values): """Phrases demo reduce function.""" if len(values) < 10: return counts = {} for filename in values: counts[filename] = counts.get(filename, 0) + 1 words = re.sub(r":", " ", key) threshold = len(values) / 2 for filename, count in counts.items(): if count > thre...
[ "def", "phrases_reduce", "(", "key", ",", "values", ")", ":", "if", "len", "(", "values", ")", "<", "10", ":", "return", "counts", "=", "{", "}", "for", "filename", "in", "values", ":", "counts", "[", "filename", "]", "=", "counts", ".", "get", "("...
Phrases demo reduce function.
[ "Phrases", "demo", "reduce", "function", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/demo/main.py#L246-L258
GoogleCloudPlatform/appengine-mapreduce
python/demo/main.py
FileMetadata.getKeyName
def getKeyName(username, date, blob_key): """Returns the internal key for a particular item in the database. Our items are stored with keys of the form 'user/date/blob_key' ('/' is not the real separator, but __SEP is). Args: username: The given user's e-mail address. date: A datetime obje...
python
def getKeyName(username, date, blob_key): """Returns the internal key for a particular item in the database. Our items are stored with keys of the form 'user/date/blob_key' ('/' is not the real separator, but __SEP is). Args: username: The given user's e-mail address. date: A datetime obje...
[ "def", "getKeyName", "(", "username", ",", "date", ",", "blob_key", ")", ":", "sep", "=", "FileMetadata", ".", "__SEP", "return", "str", "(", "username", "+", "sep", "+", "str", "(", "date", ")", "+", "sep", "+", "blob_key", ")" ]
Returns the internal key for a particular item in the database. Our items are stored with keys of the form 'user/date/blob_key' ('/' is not the real separator, but __SEP is). Args: username: The given user's e-mail address. date: A datetime object representing the date and time that an input ...
[ "Returns", "the", "internal", "key", "for", "a", "particular", "item", "in", "the", "database", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/demo/main.py#L113-L130
materialsproject/custodian
custodian/custodian.py
Custodian.from_spec
def from_spec(cls, spec): """ Load a Custodian instance where the jobs are specified from a structure and a spec dict. This allows simple custom job sequences to be constructed quickly via a YAML file. Args: spec (dict): A dict specifying job. A sample of the dict in...
python
def from_spec(cls, spec): """ Load a Custodian instance where the jobs are specified from a structure and a spec dict. This allows simple custom job sequences to be constructed quickly via a YAML file. Args: spec (dict): A dict specifying job. A sample of the dict in...
[ "def", "from_spec", "(", "cls", ",", "spec", ")", ":", "dec", "=", "MontyDecoder", "(", ")", "def", "load_class", "(", "dotpath", ")", ":", "modname", ",", "classname", "=", "dotpath", ".", "rsplit", "(", "\".\"", ",", "1", ")", "mod", "=", "__import...
Load a Custodian instance where the jobs are specified from a structure and a spec dict. This allows simple custom job sequences to be constructed quickly via a YAML file. Args: spec (dict): A dict specifying job. A sample of the dict in YAML format for the usual MP ...
[ "Load", "a", "Custodian", "instance", "where", "the", "jobs", "are", "specified", "from", "a", "structure", "and", "a", "spec", "dict", ".", "This", "allows", "simple", "custom", "job", "sequences", "to", "be", "constructed", "quickly", "via", "a", "YAML", ...
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/custodian.py#L204-L292
materialsproject/custodian
custodian/custodian.py
Custodian.run
def run(self): """ Runs all jobs. Returns: All errors encountered as a list of list. [[error_dicts for job 1], [error_dicts for job 2], ....] Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return ...
python
def run(self): """ Runs all jobs. Returns: All errors encountered as a list of list. [[error_dicts for job 1], [error_dicts for job 2], ....] Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return ...
[ "def", "run", "(", "self", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "with", "ScratchDir", "(", "self", ".", "scratch_dir", ",", "create_symbolic_link", "=", "True", ",", "copy_to_current_on_exit", "=", "True", ",", "copy_from_current_on_enter", "...
Runs all jobs. Returns: All errors encountered as a list of list. [[error_dicts for job 1], [error_dicts for job 2], ....] Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return code different from 0 N...
[ "Runs", "all", "jobs", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/custodian.py#L294-L357
materialsproject/custodian
custodian/custodian.py
Custodian._run_job
def _run_job(self, job_n, job): """ Runs a single job. Args: job_n: job number (1 index) job: Custodian job Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return code different from 0 ...
python
def _run_job(self, job_n, job): """ Runs a single job. Args: job_n: job number (1 index) job: Custodian job Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return code different from 0 ...
[ "def", "_run_job", "(", "self", ",", "job_n", ",", "job", ")", ":", "self", ".", "run_log", ".", "append", "(", "{", "\"job\"", ":", "job", ".", "as_dict", "(", ")", ",", "\"corrections\"", ":", "[", "]", ",", "\"handler\"", ":", "None", ",", "\"va...
Runs a single job. Args: job_n: job number (1 index) job: Custodian job Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return code different from 0 NonRecoverableError: if an unrecoverable occurs ...
[ "Runs", "a", "single", "job", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/custodian.py#L359-L487
materialsproject/custodian
custodian/custodian.py
Custodian.run_interrupted
def run_interrupted(self): """ Runs custodian in a interuppted mode, which sets up and validates jobs but doesn't run the executable Returns: number of remaining jobs Raises: ValidationError: if a job fails validation ReturnCodeError: if the ...
python
def run_interrupted(self): """ Runs custodian in a interuppted mode, which sets up and validates jobs but doesn't run the executable Returns: number of remaining jobs Raises: ValidationError: if a job fails validation ReturnCodeError: if the ...
[ "def", "run_interrupted", "(", "self", ")", ":", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "try", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "v", "=", "sys", ".", "version", ".", "replace", "(", "\"\\n\"", ",", "\" \"", ...
Runs custodian in a interuppted mode, which sets up and validates jobs but doesn't run the executable Returns: number of remaining jobs Raises: ValidationError: if a job fails validation ReturnCodeError: if the process has a return code different from 0 ...
[ "Runs", "custodian", "in", "a", "interuppted", "mode", "which", "sets", "up", "and", "validates", "jobs", "but", "doesn", "t", "run", "the", "executable" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/custodian.py#L489-L596
materialsproject/custodian
custodian/custodian.py
Custodian._do_check
def _do_check(self, handlers, terminate_func=None): """ checks the specified handlers. Returns True iff errors caught """ corrections = [] for h in handlers: try: if h.check(): if h.max_num_corrections is not None \ ...
python
def _do_check(self, handlers, terminate_func=None): """ checks the specified handlers. Returns True iff errors caught """ corrections = [] for h in handlers: try: if h.check(): if h.max_num_corrections is not None \ ...
[ "def", "_do_check", "(", "self", ",", "handlers", ",", "terminate_func", "=", "None", ")", ":", "corrections", "=", "[", "]", "for", "h", "in", "handlers", ":", "try", ":", "if", "h", ".", "check", "(", ")", ":", "if", "h", ".", "max_num_corrections"...
checks the specified handlers. Returns True iff errors caught
[ "checks", "the", "specified", "handlers", ".", "Returns", "True", "iff", "errors", "caught" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/custodian.py#L598-L643
materialsproject/custodian
custodian/feff/interpreter.py
FeffModder.apply_actions
def apply_actions(self, actions): """ Applies a list of actions to the FEFF Input Set and rewrites modified files. Args: actions [dict]: A list of actions of the form {'file': filename, 'action': moddermodification} or {'dict': feffinput_key, ...
python
def apply_actions(self, actions): """ Applies a list of actions to the FEFF Input Set and rewrites modified files. Args: actions [dict]: A list of actions of the form {'file': filename, 'action': moddermodification} or {'dict': feffinput_key, ...
[ "def", "apply_actions", "(", "self", ",", "actions", ")", ":", "modified", "=", "[", "]", "for", "a", "in", "actions", ":", "if", "\"dict\"", "in", "a", ":", "k", "=", "a", "[", "\"dict\"", "]", "modified", ".", "append", "(", "k", ")", "self", "...
Applies a list of actions to the FEFF Input Set and rewrites modified files. Args: actions [dict]: A list of actions of the form {'file': filename, 'action': moddermodification} or {'dict': feffinput_key, 'action': moddermodification}
[ "Applies", "a", "list", "of", "actions", "to", "the", "FEFF", "Input", "Set", "and", "rewrites", "modified", "files", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/feff/interpreter.py#L35-L65
materialsproject/custodian
custodian/ansible/actions.py
FileActions.file_create
def file_create(filename, settings): """ Creates a file. Args: filename (str): Filename. settings (dict): Must be {"content": actual_content} """ if len(settings) != 1: raise ValueError("Settings must only contain one item with key " ...
python
def file_create(filename, settings): """ Creates a file. Args: filename (str): Filename. settings (dict): Must be {"content": actual_content} """ if len(settings) != 1: raise ValueError("Settings must only contain one item with key " ...
[ "def", "file_create", "(", "filename", ",", "settings", ")", ":", "if", "len", "(", "settings", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Settings must only contain one item with key \"", "\"'content'.\"", ")", "for", "k", ",", "v", "in", "settings", ...
Creates a file. Args: filename (str): Filename. settings (dict): Must be {"content": actual_content}
[ "Creates", "a", "file", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/ansible/actions.py#L154-L168
materialsproject/custodian
custodian/ansible/actions.py
FileActions.file_move
def file_move(filename, settings): """ Moves a file. {'_file_move': {'dest': 'new_file_name'}} Args: filename (str): Filename. settings (dict): Must be {"dest": path of new file} """ if len(settings) != 1: raise ValueError("Settings must only ...
python
def file_move(filename, settings): """ Moves a file. {'_file_move': {'dest': 'new_file_name'}} Args: filename (str): Filename. settings (dict): Must be {"dest": path of new file} """ if len(settings) != 1: raise ValueError("Settings must only ...
[ "def", "file_move", "(", "filename", ",", "settings", ")", ":", "if", "len", "(", "settings", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Settings must only contain one item with key \"", "\"'dest'.\"", ")", "for", "k", ",", "v", "in", "settings", ".",...
Moves a file. {'_file_move': {'dest': 'new_file_name'}} Args: filename (str): Filename. settings (dict): Must be {"dest": path of new file}
[ "Moves", "a", "file", ".", "{", "_file_move", ":", "{", "dest", ":", "new_file_name", "}}" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/ansible/actions.py#L171-L184
materialsproject/custodian
custodian/ansible/actions.py
FileActions.file_delete
def file_delete(filename, settings): """ Deletes a file. {'_file_delete': {'mode': "actual"}} Args: filename (str): Filename. settings (dict): Must be {"mode": actual/simulated}. Simulated mode only prints the action without performing it. """ ...
python
def file_delete(filename, settings): """ Deletes a file. {'_file_delete': {'mode': "actual"}} Args: filename (str): Filename. settings (dict): Must be {"mode": actual/simulated}. Simulated mode only prints the action without performing it. """ ...
[ "def", "file_delete", "(", "filename", ",", "settings", ")", ":", "if", "len", "(", "settings", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Settings must only contain one item with key \"", "\"'mode'.\"", ")", "for", "k", ",", "v", "in", "settings", "....
Deletes a file. {'_file_delete': {'mode': "actual"}} Args: filename (str): Filename. settings (dict): Must be {"mode": actual/simulated}. Simulated mode only prints the action without performing it.
[ "Deletes", "a", "file", ".", "{", "_file_delete", ":", "{", "mode", ":", "actual", "}}" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/ansible/actions.py#L187-L207
materialsproject/custodian
custodian/ansible/actions.py
FileActions.file_copy
def file_copy(filename, settings): """ Copies a file. {'_file_copy': {'dest': 'new_file_name'}} Args: filename (str): Filename. settings (dict): Must be {"dest": path of new file} """ for k, v in settings.items(): if k.startswith("dest"): ...
python
def file_copy(filename, settings): """ Copies a file. {'_file_copy': {'dest': 'new_file_name'}} Args: filename (str): Filename. settings (dict): Must be {"dest": path of new file} """ for k, v in settings.items(): if k.startswith("dest"): ...
[ "def", "file_copy", "(", "filename", ",", "settings", ")", ":", "for", "k", ",", "v", "in", "settings", ".", "items", "(", ")", ":", "if", "k", ".", "startswith", "(", "\"dest\"", ")", ":", "shutil", ".", "copyfile", "(", "filename", ",", "v", ")" ...
Copies a file. {'_file_copy': {'dest': 'new_file_name'}} Args: filename (str): Filename. settings (dict): Must be {"dest": path of new file}
[ "Copies", "a", "file", ".", "{", "_file_copy", ":", "{", "dest", ":", "new_file_name", "}}" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/ansible/actions.py#L210-L220
materialsproject/custodian
custodian/ansible/actions.py
FileActions.file_modify
def file_modify(filename, settings): """ Modifies file access Args: filename (str): Filename. settings (dict): Can be "mode" or "owners" """ for k, v in settings.items(): if k == "mode": os.chmod(filename,v) if k ==...
python
def file_modify(filename, settings): """ Modifies file access Args: filename (str): Filename. settings (dict): Can be "mode" or "owners" """ for k, v in settings.items(): if k == "mode": os.chmod(filename,v) if k ==...
[ "def", "file_modify", "(", "filename", ",", "settings", ")", ":", "for", "k", ",", "v", "in", "settings", ".", "items", "(", ")", ":", "if", "k", "==", "\"mode\"", ":", "os", ".", "chmod", "(", "filename", ",", "v", ")", "if", "k", "==", "\"owner...
Modifies file access Args: filename (str): Filename. settings (dict): Can be "mode" or "owners"
[ "Modifies", "file", "access" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/ansible/actions.py#L223-L235
materialsproject/custodian
custodian/feff/jobs.py
FeffJob.setup
def setup(self): """ Performs initial setup for FeffJob, do backing up. Returns: """ decompress_dir('.') if self.backup: for f in FEFF_INPUT_FILES: shutil.copy(f, "{}.orig".format(f)) for f in FEFF_BACKUP_FILES: i...
python
def setup(self): """ Performs initial setup for FeffJob, do backing up. Returns: """ decompress_dir('.') if self.backup: for f in FEFF_INPUT_FILES: shutil.copy(f, "{}.orig".format(f)) for f in FEFF_BACKUP_FILES: i...
[ "def", "setup", "(", "self", ")", ":", "decompress_dir", "(", "'.'", ")", "if", "self", ".", "backup", ":", "for", "f", "in", "FEFF_INPUT_FILES", ":", "shutil", ".", "copy", "(", "f", ",", "\"{}.orig\"", ".", "format", "(", "f", ")", ")", "for", "f...
Performs initial setup for FeffJob, do backing up. Returns:
[ "Performs", "initial", "setup", "for", "FeffJob", "do", "backing", "up", ".", "Returns", ":" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/feff/jobs.py#L59-L73
materialsproject/custodian
custodian/feff/jobs.py
FeffJob.run
def run(self): """ Performs the actual FEFF run Returns: (subprocess.Popen) Used for monitoring. """ with open(self.output_file, "w") as f_std, \ open(self.stderr_file, "w", buffering=1) as f_err: # Use line buffering for stderr ...
python
def run(self): """ Performs the actual FEFF run Returns: (subprocess.Popen) Used for monitoring. """ with open(self.output_file, "w") as f_std, \ open(self.stderr_file, "w", buffering=1) as f_err: # Use line buffering for stderr ...
[ "def", "run", "(", "self", ")", ":", "with", "open", "(", "self", ".", "output_file", ",", "\"w\"", ")", "as", "f_std", ",", "open", "(", "self", ".", "stderr_file", ",", "\"w\"", ",", "buffering", "=", "1", ")", "as", "f_err", ":", "# Use line buffe...
Performs the actual FEFF run Returns: (subprocess.Popen) Used for monitoring.
[ "Performs", "the", "actual", "FEFF", "run", "Returns", ":", "(", "subprocess", ".", "Popen", ")", "Used", "for", "monitoring", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/feff/jobs.py#L75-L88
materialsproject/custodian
custodian/ansible/interpreter.py
Modder.modify
def modify(self, modification, obj): """ Note that modify makes actual in-place modifications. It does not return a copy. Args: modification (dict): Modification must be {action_keyword : settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}} ...
python
def modify(self, modification, obj): """ Note that modify makes actual in-place modifications. It does not return a copy. Args: modification (dict): Modification must be {action_keyword : settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}} ...
[ "def", "modify", "(", "self", ",", "modification", ",", "obj", ")", ":", "for", "action", ",", "settings", "in", "modification", ".", "items", "(", ")", ":", "if", "action", "in", "self", ".", "supported_actions", ":", "self", ".", "supported_actions", "...
Note that modify makes actual in-place modifications. It does not return a copy. Args: modification (dict): Modification must be {action_keyword : settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}} obj (dict/str/object): Object to modify depending on...
[ "Note", "that", "modify", "makes", "actual", "in", "-", "place", "modifications", ".", "It", "does", "not", "return", "a", "copy", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/ansible/interpreter.py#L67-L85
materialsproject/custodian
custodian/ansible/interpreter.py
Modder.modify_object
def modify_object(self, modification, obj): """ Modify an object that supports pymatgen's as_dict() and from_dict API. Args: modification (dict): Modification must be {action_keyword : settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}} obj (o...
python
def modify_object(self, modification, obj): """ Modify an object that supports pymatgen's as_dict() and from_dict API. Args: modification (dict): Modification must be {action_keyword : settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}} obj (o...
[ "def", "modify_object", "(", "self", ",", "modification", ",", "obj", ")", ":", "d", "=", "obj", ".", "as_dict", "(", ")", "self", ".", "modify", "(", "modification", ",", "d", ")", "return", "obj", ".", "from_dict", "(", "d", ")" ]
Modify an object that supports pymatgen's as_dict() and from_dict API. Args: modification (dict): Modification must be {action_keyword : settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}} obj (object): Object to modify
[ "Modify", "an", "object", "that", "supports", "pymatgen", "s", "as_dict", "()", "and", "from_dict", "API", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/ansible/interpreter.py#L87-L98
materialsproject/custodian
custodian/vasp/interpreter.py
VaspModder.apply_actions
def apply_actions(self, actions): """ Applies a list of actions to the Vasp Input Set and rewrites modified files. Args: actions [dict]: A list of actions of the form {'file': filename, 'action': moddermodification} or {'dict': vaspinput_key, '...
python
def apply_actions(self, actions): """ Applies a list of actions to the Vasp Input Set and rewrites modified files. Args: actions [dict]: A list of actions of the form {'file': filename, 'action': moddermodification} or {'dict': vaspinput_key, '...
[ "def", "apply_actions", "(", "self", ",", "actions", ")", ":", "modified", "=", "[", "]", "for", "a", "in", "actions", ":", "if", "\"dict\"", "in", "a", ":", "k", "=", "a", "[", "\"dict\"", "]", "modified", ".", "append", "(", "k", ")", "self", "...
Applies a list of actions to the Vasp Input Set and rewrites modified files. Args: actions [dict]: A list of actions of the form {'file': filename, 'action': moddermodification} or {'dict': vaspinput_key, 'action': moddermodification}
[ "Applies", "a", "list", "of", "actions", "to", "the", "Vasp", "Input", "Set", "and", "rewrites", "modified", "files", ".", "Args", ":", "actions", "[", "dict", "]", ":", "A", "list", "of", "actions", "of", "the", "form", "{", "file", ":", "filename", ...
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/interpreter.py#L31-L51
materialsproject/custodian
custodian/utils.py
backup
def backup(filenames, prefix="error"): """ Backup files to a tar.gz file. Used, for example, in backing up the files of an errored run before performing corrections. Args: filenames ([str]): List of files to backup. Supports wildcards, e.g., *.*. prefix (str): prefix to the ...
python
def backup(filenames, prefix="error"): """ Backup files to a tar.gz file. Used, for example, in backing up the files of an errored run before performing corrections. Args: filenames ([str]): List of files to backup. Supports wildcards, e.g., *.*. prefix (str): prefix to the ...
[ "def", "backup", "(", "filenames", ",", "prefix", "=", "\"error\"", ")", ":", "num", "=", "max", "(", "[", "0", "]", "+", "[", "int", "(", "f", ".", "split", "(", "\".\"", ")", "[", "1", "]", ")", "for", "f", "in", "glob", "(", "\"{}.*.tar.gz\"...
Backup files to a tar.gz file. Used, for example, in backing up the files of an errored run before performing corrections. Args: filenames ([str]): List of files to backup. Supports wildcards, e.g., *.*. prefix (str): prefix to the files. Defaults to error, which means a ...
[ "Backup", "files", "to", "a", "tar", ".", "gz", "file", ".", "Used", "for", "example", "in", "backing", "up", "the", "files", "of", "an", "errored", "run", "before", "performing", "corrections", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/utils.py#L23-L41
materialsproject/custodian
custodian/utils.py
get_execution_host_info
def get_execution_host_info(): """ Tries to return a tuple describing the execution host. Doesn't work for all queueing systems Returns: (HOSTNAME, CLUSTER_NAME) """ host = os.environ.get('HOSTNAME', None) cluster = os.environ.get('SGE_O_HOST', None) if host is None: try...
python
def get_execution_host_info(): """ Tries to return a tuple describing the execution host. Doesn't work for all queueing systems Returns: (HOSTNAME, CLUSTER_NAME) """ host = os.environ.get('HOSTNAME', None) cluster = os.environ.get('SGE_O_HOST', None) if host is None: try...
[ "def", "get_execution_host_info", "(", ")", ":", "host", "=", "os", ".", "environ", ".", "get", "(", "'HOSTNAME'", ",", "None", ")", "cluster", "=", "os", ".", "environ", ".", "get", "(", "'SGE_O_HOST'", ",", "None", ")", "if", "host", "is", "None", ...
Tries to return a tuple describing the execution host. Doesn't work for all queueing systems Returns: (HOSTNAME, CLUSTER_NAME)
[ "Tries", "to", "return", "a", "tuple", "describing", "the", "execution", "host", ".", "Doesn", "t", "work", "for", "all", "queueing", "systems" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/utils.py#L44-L60
materialsproject/custodian
custodian/qchem/jobs.py
QCJob.run
def run(self): """ Perform the actual QChem run. Returns: (subprocess.Popen) Used for monitoring. """ qclog = open(self.qclog_file, 'w') p = subprocess.Popen(self.current_command, stdout=qclog) return p
python
def run(self): """ Perform the actual QChem run. Returns: (subprocess.Popen) Used for monitoring. """ qclog = open(self.qclog_file, 'w') p = subprocess.Popen(self.current_command, stdout=qclog) return p
[ "def", "run", "(", "self", ")", ":", "qclog", "=", "open", "(", "self", ".", "qclog_file", ",", "'w'", ")", "p", "=", "subprocess", ".", "Popen", "(", "self", ".", "current_command", ",", "stdout", "=", "qclog", ")", "return", "p" ]
Perform the actual QChem run. Returns: (subprocess.Popen) Used for monitoring.
[ "Perform", "the", "actual", "QChem", "run", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/qchem/jobs.py#L120-L129
materialsproject/custodian
custodian/qchem/jobs.py
QCJob.opt_with_frequency_flattener
def opt_with_frequency_flattener(cls, qchem_command, multimode="openmp", input_file="mol.qin", output_file="mol.qout", qclog_file="mol....
python
def opt_with_frequency_flattener(cls, qchem_command, multimode="openmp", input_file="mol.qin", output_file="mol.qout", qclog_file="mol....
[ "def", "opt_with_frequency_flattener", "(", "cls", ",", "qchem_command", ",", "multimode", "=", "\"openmp\"", ",", "input_file", "=", "\"mol.qin\"", ",", "output_file", "=", "\"mol.qout\"", ",", "qclog_file", "=", "\"mol.qclog\"", ",", "max_iterations", "=", "10", ...
Optimize a structure and calculate vibrational frequencies to check if the structure is in a true minima. If a frequency is negative, iteratively perturbe the geometry, optimize, and recalculate frequencies until all are positive, aka a true minima has been found. Args: qche...
[ "Optimize", "a", "structure", "and", "calculate", "vibrational", "frequencies", "to", "check", "if", "the", "structure", "is", "in", "a", "true", "minima", ".", "If", "a", "frequency", "is", "negative", "iteratively", "perturbe", "the", "geometry", "optimize", ...
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/qchem/jobs.py#L132-L270
materialsproject/custodian
custodian/vasp/jobs.py
VaspJob.setup
def setup(self): """ Performs initial setup for VaspJob, including overriding any settings and backing up. """ decompress_dir('.') if self.backup: for f in VASP_INPUT_FILES: shutil.copy(f, "{}.orig".format(f)) if self.auto_npar: ...
python
def setup(self): """ Performs initial setup for VaspJob, including overriding any settings and backing up. """ decompress_dir('.') if self.backup: for f in VASP_INPUT_FILES: shutil.copy(f, "{}.orig".format(f)) if self.auto_npar: ...
[ "def", "setup", "(", "self", ")", ":", "decompress_dir", "(", "'.'", ")", "if", "self", ".", "backup", ":", "for", "f", "in", "VASP_INPUT_FILES", ":", "shutil", ".", "copy", "(", "f", ",", "\"{}.orig\"", ".", "format", "(", "f", ")", ")", "if", "se...
Performs initial setup for VaspJob, including overriding any settings and backing up.
[ "Performs", "initial", "setup", "for", "VaspJob", "including", "overriding", "any", "settings", "and", "backing", "up", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L131-L189
materialsproject/custodian
custodian/vasp/jobs.py
VaspJob.run
def run(self): """ Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring. """ cmd = list(self.vasp_cmd) if self.auto_gamma: vi = VaspInput.from_directory(".") kpts = vi["KPOINTS"] if kpts.style == Kpo...
python
def run(self): """ Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring. """ cmd = list(self.vasp_cmd) if self.auto_gamma: vi = VaspInput.from_directory(".") kpts = vi["KPOINTS"] if kpts.style == Kpo...
[ "def", "run", "(", "self", ")", ":", "cmd", "=", "list", "(", "self", ".", "vasp_cmd", ")", "if", "self", ".", "auto_gamma", ":", "vi", "=", "VaspInput", ".", "from_directory", "(", "\".\"", ")", "kpts", "=", "vi", "[", "\"KPOINTS\"", "]", "if", "k...
Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring.
[ "Perform", "the", "actual", "VASP", "run", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L191-L214
materialsproject/custodian
custodian/vasp/jobs.py
VaspJob.postprocess
def postprocess(self): """ Postprocessing includes renaming and gzipping where necessary. Also copies the magmom to the incar if necessary """ for f in VASP_OUTPUT_FILES + [self.output_file]: if os.path.exists(f): if self.final and self.suffix != "": ...
python
def postprocess(self): """ Postprocessing includes renaming and gzipping where necessary. Also copies the magmom to the incar if necessary """ for f in VASP_OUTPUT_FILES + [self.output_file]: if os.path.exists(f): if self.final and self.suffix != "": ...
[ "def", "postprocess", "(", "self", ")", ":", "for", "f", "in", "VASP_OUTPUT_FILES", "+", "[", "self", ".", "output_file", "]", ":", "if", "os", ".", "path", ".", "exists", "(", "f", ")", ":", "if", "self", ".", "final", "and", "self", ".", "suffix"...
Postprocessing includes renaming and gzipping where necessary. Also copies the magmom to the incar if necessary
[ "Postprocessing", "includes", "renaming", "and", "gzipping", "where", "necessary", ".", "Also", "copies", "the", "magmom", "to", "the", "incar", "if", "necessary" ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L216-L241
materialsproject/custodian
custodian/vasp/jobs.py
VaspJob.double_relaxation_run
def double_relaxation_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05, half_kpts_first_relax=False, auto_continue=False): """ Returns a list of two jobs corresponding to an AFLOW style double relaxation run. Args: vasp_cmd (str): Command to run ...
python
def double_relaxation_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05, half_kpts_first_relax=False, auto_continue=False): """ Returns a list of two jobs corresponding to an AFLOW style double relaxation run. Args: vasp_cmd (str): Command to run ...
[ "def", "double_relaxation_run", "(", "cls", ",", "vasp_cmd", ",", "auto_npar", "=", "True", ",", "ediffg", "=", "-", "0.05", ",", "half_kpts_first_relax", "=", "False", ",", "auto_continue", "=", "False", ")", ":", "incar_update", "=", "{", "\"ISTART\"", ":"...
Returns a list of two jobs corresponding to an AFLOW style double relaxation run. Args: vasp_cmd (str): Command to run vasp as a list of args. For example, if you are using mpirun, it can be something like ["mpirun", "pvasp.5.2.11"] auto_npar (boo...
[ "Returns", "a", "list", "of", "two", "jobs", "corresponding", "to", "an", "AFLOW", "style", "double", "relaxation", "run", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L244-L298
materialsproject/custodian
custodian/vasp/jobs.py
VaspJob.metagga_opt_run
def metagga_opt_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05, half_kpts_first_relax=False, auto_continue=False): """ Returns a list of thres jobs to perform an optimization for any metaGGA functional. There is an initial calculation of the GGA wavefunction whic...
python
def metagga_opt_run(cls, vasp_cmd, auto_npar=True, ediffg=-0.05, half_kpts_first_relax=False, auto_continue=False): """ Returns a list of thres jobs to perform an optimization for any metaGGA functional. There is an initial calculation of the GGA wavefunction whic...
[ "def", "metagga_opt_run", "(", "cls", ",", "vasp_cmd", ",", "auto_npar", "=", "True", ",", "ediffg", "=", "-", "0.05", ",", "half_kpts_first_relax", "=", "False", ",", "auto_continue", "=", "False", ")", ":", "incar", "=", "Incar", ".", "from_file", "(", ...
Returns a list of thres jobs to perform an optimization for any metaGGA functional. There is an initial calculation of the GGA wavefunction which is fed into the initial metaGGA optimization to precondition the electronic structure optimizer. The metaGGA optimization is performed using t...
[ "Returns", "a", "list", "of", "thres", "jobs", "to", "perform", "an", "optimization", "for", "any", "metaGGA", "functional", ".", "There", "is", "an", "initial", "calculation", "of", "the", "GGA", "wavefunction", "which", "is", "fed", "into", "the", "initial...
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L301-L343
materialsproject/custodian
custodian/vasp/jobs.py
VaspJob.full_opt_run
def full_opt_run(cls, vasp_cmd, vol_change_tol=0.02, max_steps=10, ediffg=-0.05, half_kpts_first_relax=False, **vasp_job_kwargs): """ Returns a generator of jobs for a full optimization run. Basically, this runs an infinite series of geometry optimizatio...
python
def full_opt_run(cls, vasp_cmd, vol_change_tol=0.02, max_steps=10, ediffg=-0.05, half_kpts_first_relax=False, **vasp_job_kwargs): """ Returns a generator of jobs for a full optimization run. Basically, this runs an infinite series of geometry optimizatio...
[ "def", "full_opt_run", "(", "cls", ",", "vasp_cmd", ",", "vol_change_tol", "=", "0.02", ",", "max_steps", "=", "10", ",", "ediffg", "=", "-", "0.05", ",", "half_kpts_first_relax", "=", "False", ",", "*", "*", "vasp_job_kwargs", ")", ":", "for", "i", "in"...
Returns a generator of jobs for a full optimization run. Basically, this runs an infinite series of geometry optimization jobs until the % vol change in a particular optimization is less than vol_change_tol. Args: vasp_cmd (str): Command to run vasp as a list of args. For example, ...
[ "Returns", "a", "generator", "of", "jobs", "for", "a", "full", "optimization", "run", ".", "Basically", "this", "runs", "an", "infinite", "series", "of", "geometry", "optimization", "jobs", "until", "the", "%", "vol", "change", "in", "a", "particular", "opti...
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L346-L412
materialsproject/custodian
custodian/vasp/jobs.py
VaspJob.constrained_opt_run
def constrained_opt_run(cls, vasp_cmd, lattice_direction, initial_strain, atom_relax=True, max_steps=20, algo="bfgs", **vasp_job_kwargs): """ Returns a generator of jobs for a constrained optimization run. Typical use case is when you want ...
python
def constrained_opt_run(cls, vasp_cmd, lattice_direction, initial_strain, atom_relax=True, max_steps=20, algo="bfgs", **vasp_job_kwargs): """ Returns a generator of jobs for a constrained optimization run. Typical use case is when you want ...
[ "def", "constrained_opt_run", "(", "cls", ",", "vasp_cmd", ",", "lattice_direction", ",", "initial_strain", ",", "atom_relax", "=", "True", ",", "max_steps", "=", "20", ",", "algo", "=", "\"bfgs\"", ",", "*", "*", "vasp_job_kwargs", ")", ":", "nsw", "=", "...
Returns a generator of jobs for a constrained optimization run. Typical use case is when you want to approximate a biaxial strain situation, e.g., you apply a defined strain to a and b directions of the lattice, but allows the c-direction to relax. Some guidelines on the use of this met...
[ "Returns", "a", "generator", "of", "jobs", "for", "a", "constrained", "optimization", "run", ".", "Typical", "use", "case", "is", "when", "you", "want", "to", "approximate", "a", "biaxial", "strain", "situation", "e", ".", "g", ".", "you", "apply", "a", ...
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L415-L590
materialsproject/custodian
custodian/vasp/jobs.py
VaspNEBJob.setup
def setup(self): """ Performs initial setup for VaspNEBJob, including overriding any settings and backing up. """ neb_dirs = self.neb_dirs if self.backup: # Back up KPOINTS, INCAR, POTCAR for f in VASP_NEB_INPUT_FILES: shutil.copy(...
python
def setup(self): """ Performs initial setup for VaspNEBJob, including overriding any settings and backing up. """ neb_dirs = self.neb_dirs if self.backup: # Back up KPOINTS, INCAR, POTCAR for f in VASP_NEB_INPUT_FILES: shutil.copy(...
[ "def", "setup", "(", "self", ")", ":", "neb_dirs", "=", "self", ".", "neb_dirs", "if", "self", ".", "backup", ":", "# Back up KPOINTS, INCAR, POTCAR", "for", "f", "in", "VASP_NEB_INPUT_FILES", ":", "shutil", ".", "copy", "(", "f", ",", "\"{}.orig\"", ".", ...
Performs initial setup for VaspNEBJob, including overriding any settings and backing up.
[ "Performs", "initial", "setup", "for", "VaspNEBJob", "including", "overriding", "any", "settings", "and", "backing", "up", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L686-L744
materialsproject/custodian
custodian/vasp/jobs.py
VaspNEBJob.postprocess
def postprocess(self): """ Postprocessing includes renaming and gzipping where necessary. """ # Add suffix to all sub_dir/{items} for path in self.neb_dirs: for f in VASP_NEB_OUTPUT_SUB_FILES: f = os.path.join(path, f) if os.path.exists...
python
def postprocess(self): """ Postprocessing includes renaming and gzipping where necessary. """ # Add suffix to all sub_dir/{items} for path in self.neb_dirs: for f in VASP_NEB_OUTPUT_SUB_FILES: f = os.path.join(path, f) if os.path.exists...
[ "def", "postprocess", "(", "self", ")", ":", "# Add suffix to all sub_dir/{items}", "for", "path", "in", "self", ".", "neb_dirs", ":", "for", "f", "in", "VASP_NEB_OUTPUT_SUB_FILES", ":", "f", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")",...
Postprocessing includes renaming and gzipping where necessary.
[ "Postprocessing", "includes", "renaming", "and", "gzipping", "where", "necessary", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L771-L791
materialsproject/custodian
custodian/nwchem/jobs.py
NwchemJob.setup
def setup(self): """ Performs backup if necessary. """ if self.backup: shutil.copy(self.input_file, "{}.orig".format(self.input_file))
python
def setup(self): """ Performs backup if necessary. """ if self.backup: shutil.copy(self.input_file, "{}.orig".format(self.input_file))
[ "def", "setup", "(", "self", ")", ":", "if", "self", ".", "backup", ":", "shutil", ".", "copy", "(", "self", ".", "input_file", ",", "\"{}.orig\"", ".", "format", "(", "self", ".", "input_file", ")", ")" ]
Performs backup if necessary.
[ "Performs", "backup", "if", "necessary", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/nwchem/jobs.py#L58-L63
materialsproject/custodian
custodian/nwchem/jobs.py
NwchemJob.run
def run(self): """ Performs actual nwchem run. """ with zopen(self.output_file, 'w') as fout: return subprocess.Popen(self.nwchem_cmd + [self.input_file], stdout=fout)
python
def run(self): """ Performs actual nwchem run. """ with zopen(self.output_file, 'w') as fout: return subprocess.Popen(self.nwchem_cmd + [self.input_file], stdout=fout)
[ "def", "run", "(", "self", ")", ":", "with", "zopen", "(", "self", ".", "output_file", ",", "'w'", ")", "as", "fout", ":", "return", "subprocess", ".", "Popen", "(", "self", ".", "nwchem_cmd", "+", "[", "self", ".", "input_file", "]", ",", "stdout", ...
Performs actual nwchem run.
[ "Performs", "actual", "nwchem", "run", "." ]
train
https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/nwchem/jobs.py#L65-L71
wdecoster/nanofilt
nanofilt/NanoFilt.py
valid_GC
def valid_GC(x): """type function for argparse to check GC values. Check if the supplied value for minGC and maxGC is a valid input, being between 0 and 1 """ x = float(x) if x < 0.0 or x > 1.0: raise ArgumentTypeError("{} not in range [0.0, 1.0]".format(x)) return x
python
def valid_GC(x): """type function for argparse to check GC values. Check if the supplied value for minGC and maxGC is a valid input, being between 0 and 1 """ x = float(x) if x < 0.0 or x > 1.0: raise ArgumentTypeError("{} not in range [0.0, 1.0]".format(x)) return x
[ "def", "valid_GC", "(", "x", ")", ":", "x", "=", "float", "(", "x", ")", "if", "x", "<", "0.0", "or", "x", ">", "1.0", ":", "raise", "ArgumentTypeError", "(", "\"{} not in range [0.0, 1.0]\"", ".", "format", "(", "x", ")", ")", "return", "x" ]
type function for argparse to check GC values. Check if the supplied value for minGC and maxGC is a valid input, being between 0 and 1
[ "type", "function", "for", "argparse", "to", "check", "GC", "values", "." ]
train
https://github.com/wdecoster/nanofilt/blob/513bdc529317bebbd743c0dff799472f35d92f45/nanofilt/NanoFilt.py#L157-L165
wdecoster/nanofilt
nanofilt/NanoFilt.py
filter_stream
def filter_stream(fq, args): """Filter a fastq file on stdin. Print fastq record to stdout if it passes - quality filter (optional) - length filter (optional) - min/maxGC filter (optional) Optionally trim a number of nucleotides from beginning and end. Record has to be longer than args.leng...
python
def filter_stream(fq, args): """Filter a fastq file on stdin. Print fastq record to stdout if it passes - quality filter (optional) - length filter (optional) - min/maxGC filter (optional) Optionally trim a number of nucleotides from beginning and end. Record has to be longer than args.leng...
[ "def", "filter_stream", "(", "fq", ",", "args", ")", ":", "if", "args", ".", "quality", ":", "quality_check", "=", "ave_qual", "else", ":", "quality_check", "=", "silent_quality_check", "minlen", "=", "args", ".", "length", "+", "int", "(", "args", ".", ...
Filter a fastq file on stdin. Print fastq record to stdout if it passes - quality filter (optional) - length filter (optional) - min/maxGC filter (optional) Optionally trim a number of nucleotides from beginning and end. Record has to be longer than args.length (default 1) after trimming Us...
[ "Filter", "a", "fastq", "file", "on", "stdin", "." ]
train
https://github.com/wdecoster/nanofilt/blob/513bdc529317bebbd743c0dff799472f35d92f45/nanofilt/NanoFilt.py#L173-L197
wdecoster/nanofilt
nanofilt/NanoFilt.py
filter_using_summary
def filter_using_summary(fq, args): """Use quality scores from albacore summary file for filtering Use the summary file from albacore for more accurate quality estimate Get the dataframe from nanoget, convert to dictionary """ data = {entry[0]: entry[1] for entry in process_summary( summary...
python
def filter_using_summary(fq, args): """Use quality scores from albacore summary file for filtering Use the summary file from albacore for more accurate quality estimate Get the dataframe from nanoget, convert to dictionary """ data = {entry[0]: entry[1] for entry in process_summary( summary...
[ "def", "filter_using_summary", "(", "fq", ",", "args", ")", ":", "data", "=", "{", "entry", "[", "0", "]", ":", "entry", "[", "1", "]", "for", "entry", "in", "process_summary", "(", "summaryfile", "=", "args", ".", "summary", ",", "threads", "=", "\"...
Use quality scores from albacore summary file for filtering Use the summary file from albacore for more accurate quality estimate Get the dataframe from nanoget, convert to dictionary
[ "Use", "quality", "scores", "from", "albacore", "summary", "file", "for", "filtering" ]
train
https://github.com/wdecoster/nanofilt/blob/513bdc529317bebbd743c0dff799472f35d92f45/nanofilt/NanoFilt.py#L200-L221
milesrichardson/ParsePy
parse_rest/connection.py
master_key_required
def master_key_required(func): '''decorator describing methods that require the master key''' def ret(obj, *args, **kw): conn = ACCESS_KEYS if not (conn and conn.get('master_key')): message = '%s requires the master key' % func.__name__ raise core.ParseError(message) ...
python
def master_key_required(func): '''decorator describing methods that require the master key''' def ret(obj, *args, **kw): conn = ACCESS_KEYS if not (conn and conn.get('master_key')): message = '%s requires the master key' % func.__name__ raise core.ParseError(message) ...
[ "def", "master_key_required", "(", "func", ")", ":", "def", "ret", "(", "obj", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "conn", "=", "ACCESS_KEYS", "if", "not", "(", "conn", "and", "conn", ".", "get", "(", "'master_key'", ")", ")", ":", "...
decorator describing methods that require the master key
[ "decorator", "describing", "methods", "that", "require", "the", "master", "key" ]
train
https://github.com/milesrichardson/ParsePy/blob/7c52d8a5dc63bb7c3b0b8c0c09d032b4bc7299ea/parse_rest/connection.py#L66-L74
milesrichardson/ParsePy
parse_rest/connection.py
ParseBase.execute
def execute(cls, uri, http_verb, extra_headers=None, batch=False, _body=None, **kw): """ if batch == False, execute a command with the given parameters and return the response JSON. If batch == True, return the dictionary that would be used in a batch command. """ ...
python
def execute(cls, uri, http_verb, extra_headers=None, batch=False, _body=None, **kw): """ if batch == False, execute a command with the given parameters and return the response JSON. If batch == True, return the dictionary that would be used in a batch command. """ ...
[ "def", "execute", "(", "cls", ",", "uri", ",", "http_verb", ",", "extra_headers", "=", "None", ",", "batch", "=", "False", ",", "_body", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "batch", ":", "urlsplitter", "=", "urlparse", "(", "API_ROOT", ...
if batch == False, execute a command with the given parameters and return the response JSON. If batch == True, return the dictionary that would be used in a batch command.
[ "if", "batch", "==", "False", "execute", "a", "command", "with", "the", "given", "parameters", "and", "return", "the", "response", "JSON", ".", "If", "batch", "==", "True", "return", "the", "dictionary", "that", "would", "be", "used", "in", "a", "batch", ...
train
https://github.com/milesrichardson/ParsePy/blob/7c52d8a5dc63bb7c3b0b8c0c09d032b4bc7299ea/parse_rest/connection.py#L85-L150