repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.put_alias
def put_alias(self, using=None, **kwargs): """ Create an alias for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_alias`` unchanged. """ return self._get_connection(using).indices.put_alias(index=self._name, **kwargs)
python
def put_alias(self, using=None, **kwargs): """ Create an alias for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_alias`` unchanged. """ return self._get_connection(using).indices.put_alias(index=self._name, **kwargs)
[ "def", "put_alias", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "put_alias", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "k...
Create an alias for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_alias`` unchanged.
[ "Create", "an", "alias", "for", "the", "index", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L418-L425
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.exists_alias
def exists_alias(self, using=None, **kwargs): """ Return a boolean indicating whether given alias exists for this index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.exists_alias`` unchanged. """ return self._get_connection(using).indices.exists_alias(index=self._name, **kwargs)
python
def exists_alias(self, using=None, **kwargs): """ Return a boolean indicating whether given alias exists for this index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.exists_alias`` unchanged. """ return self._get_connection(using).indices.exists_alias(index=self._name, **kwargs)
[ "def", "exists_alias", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "exists_alias", "(", "index", "=", "self", ".", "_name", ",", "*", "*"...
Return a boolean indicating whether given alias exists for this index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.exists_alias`` unchanged.
[ "Return", "a", "boolean", "indicating", "whether", "given", "alias", "exists", "for", "this", "index", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L427-L434
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.get_alias
def get_alias(self, using=None, **kwargs): """ Retrieve a specified alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_alias`` unchanged. """ return self._get_connection(using).indices.get_alias(index=self._name, **kwargs)
python
def get_alias(self, using=None, **kwargs): """ Retrieve a specified alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_alias`` unchanged. """ return self._get_connection(using).indices.get_alias(index=self._name, **kwargs)
[ "def", "get_alias", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "get_alias", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "k...
Retrieve a specified alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_alias`` unchanged.
[ "Retrieve", "a", "specified", "alias", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L436-L443
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.delete_alias
def delete_alias(self, using=None, **kwargs): """ Delete specific alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete_alias`` unchanged. """ return self._get_connection(using).indices.delete_alias(index=self._name, **kwargs)
python
def delete_alias(self, using=None, **kwargs): """ Delete specific alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete_alias`` unchanged. """ return self._get_connection(using).indices.delete_alias(index=self._name, **kwargs)
[ "def", "delete_alias", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "delete_alias", "(", "index", "=", "self", ".", "_name", ",", "*", "*"...
Delete specific alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete_alias`` unchanged.
[ "Delete", "specific", "alias", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L445-L452
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.get_settings
def get_settings(self, using=None, **kwargs): """ Retrieve settings for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_settings`` unchanged. """ return self._get_connection(using).indices.get_settings(index=self._name, **kwargs)
python
def get_settings(self, using=None, **kwargs): """ Retrieve settings for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_settings`` unchanged. """ return self._get_connection(using).indices.get_settings(index=self._name, **kwargs)
[ "def", "get_settings", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "get_settings", "(", "index", "=", "self", ".", "_name", ",", "*", "*"...
Retrieve settings for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_settings`` unchanged.
[ "Retrieve", "settings", "for", "the", "index", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L454-L461
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.put_settings
def put_settings(self, using=None, **kwargs): """ Change specific index level settings in real time. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_settings`` unchanged. """ return self._get_connection(using).indices.put_settings(index=self._name, **kwargs)
python
def put_settings(self, using=None, **kwargs): """ Change specific index level settings in real time. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_settings`` unchanged. """ return self._get_connection(using).indices.put_settings(index=self._name, **kwargs)
[ "def", "put_settings", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "put_settings", "(", "index", "=", "self", ".", "_name", ",", "*", "*"...
Change specific index level settings in real time. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_settings`` unchanged.
[ "Change", "specific", "index", "level", "settings", "in", "real", "time", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L463-L470
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.stats
def stats(self, using=None, **kwargs): """ Retrieve statistics on different operations happening on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.stats`` unchanged. """ return self._get_connection(using).indices.stats(index=self._name, **kwargs)
python
def stats(self, using=None, **kwargs): """ Retrieve statistics on different operations happening on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.stats`` unchanged. """ return self._get_connection(using).indices.stats(index=self._name, **kwargs)
[ "def", "stats", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "stats", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "kwargs", ...
Retrieve statistics on different operations happening on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.stats`` unchanged.
[ "Retrieve", "statistics", "on", "different", "operations", "happening", "on", "the", "index", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L472-L479
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.segments
def segments(self, using=None, **kwargs): """ Provide low level segments information that a Lucene index (shard level) is built with. Any additional keyword arguments will be passed to ``Elasticsearch.indices.segments`` unchanged. """ return self._get_connection(using).indices.segments(index=self._name, **kwargs)
python
def segments(self, using=None, **kwargs): """ Provide low level segments information that a Lucene index (shard level) is built with. Any additional keyword arguments will be passed to ``Elasticsearch.indices.segments`` unchanged. """ return self._get_connection(using).indices.segments(index=self._name, **kwargs)
[ "def", "segments", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "segments", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "kwa...
Provide low level segments information that a Lucene index (shard level) is built with. Any additional keyword arguments will be passed to ``Elasticsearch.indices.segments`` unchanged.
[ "Provide", "low", "level", "segments", "information", "that", "a", "Lucene", "index", "(", "shard", "level", ")", "is", "built", "with", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L481-L489
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.validate_query
def validate_query(self, using=None, **kwargs): """ Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed to ``Elasticsearch.indices.validate_query`` unchanged. """ return self._get_connection(using).indices.validate_query(index=self._name, **kwargs)
python
def validate_query(self, using=None, **kwargs): """ Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed to ``Elasticsearch.indices.validate_query`` unchanged. """ return self._get_connection(using).indices.validate_query(index=self._name, **kwargs)
[ "def", "validate_query", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "validate_query", "(", "index", "=", "self", ".", "_name", ",", "*", ...
Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed to ``Elasticsearch.indices.validate_query`` unchanged.
[ "Validate", "a", "potentially", "expensive", "query", "without", "executing", "it", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L491-L498
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.clear_cache
def clear_cache(self, using=None, **kwargs): """ Clear all caches or specific cached associated with the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.clear_cache`` unchanged. """ return self._get_connection(using).indices.clear_cache(index=self._name, **kwargs)
python
def clear_cache(self, using=None, **kwargs): """ Clear all caches or specific cached associated with the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.clear_cache`` unchanged. """ return self._get_connection(using).indices.clear_cache(index=self._name, **kwargs)
[ "def", "clear_cache", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "clear_cache", "(", "index", "=", "self", ".", "_name", ",", "*", "*", ...
Clear all caches or specific cached associated with the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.clear_cache`` unchanged.
[ "Clear", "all", "caches", "or", "specific", "cached", "associated", "with", "the", "index", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L500-L507
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.recovery
def recovery(self, using=None, **kwargs): """ The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged. """ return self._get_connection(using).indices.recovery(index=self._name, **kwargs)
python
def recovery(self, using=None, **kwargs): """ The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged. """ return self._get_connection(using).indices.recovery(index=self._name, **kwargs)
[ "def", "recovery", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "recovery", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "kwa...
The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged.
[ "The", "indices", "recovery", "API", "provides", "insight", "into", "on", "-", "going", "shard", "recoveries", "for", "the", "index", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L509-L517
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.upgrade
def upgrade(self, using=None, **kwargs): """ Upgrade the index to the latest format. Any additional keyword arguments will be passed to ``Elasticsearch.indices.upgrade`` unchanged. """ return self._get_connection(using).indices.upgrade(index=self._name, **kwargs)
python
def upgrade(self, using=None, **kwargs): """ Upgrade the index to the latest format. Any additional keyword arguments will be passed to ``Elasticsearch.indices.upgrade`` unchanged. """ return self._get_connection(using).indices.upgrade(index=self._name, **kwargs)
[ "def", "upgrade", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "upgrade", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "kwarg...
Upgrade the index to the latest format. Any additional keyword arguments will be passed to ``Elasticsearch.indices.upgrade`` unchanged.
[ "Upgrade", "the", "index", "to", "the", "latest", "format", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L519-L526
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.get_upgrade
def get_upgrade(self, using=None, **kwargs): """ Monitor how much of the index is upgraded. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_upgrade`` unchanged. """ return self._get_connection(using).indices.get_upgrade(index=self._name, **kwargs)
python
def get_upgrade(self, using=None, **kwargs): """ Monitor how much of the index is upgraded. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_upgrade`` unchanged. """ return self._get_connection(using).indices.get_upgrade(index=self._name, **kwargs)
[ "def", "get_upgrade", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "get_upgrade", "(", "index", "=", "self", ".", "_name", ",", "*", "*", ...
Monitor how much of the index is upgraded. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_upgrade`` unchanged.
[ "Monitor", "how", "much", "of", "the", "index", "is", "upgraded", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L528-L535
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.flush_synced
def flush_synced(self, using=None, **kwargs): """ Perform a normal flush, then add a generated unique marker (sync_id) to all shards. Any additional keyword arguments will be passed to ``Elasticsearch.indices.flush_synced`` unchanged. """ return self._get_connection(using).indices.flush_synced(index=self._name, **kwargs)
python
def flush_synced(self, using=None, **kwargs): """ Perform a normal flush, then add a generated unique marker (sync_id) to all shards. Any additional keyword arguments will be passed to ``Elasticsearch.indices.flush_synced`` unchanged. """ return self._get_connection(using).indices.flush_synced(index=self._name, **kwargs)
[ "def", "flush_synced", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "flush_synced", "(", "index", "=", "self", ".", "_name", ",", "*", "*"...
Perform a normal flush, then add a generated unique marker (sync_id) to all shards. Any additional keyword arguments will be passed to ``Elasticsearch.indices.flush_synced`` unchanged.
[ "Perform", "a", "normal", "flush", "then", "add", "a", "generated", "unique", "marker", "(", "sync_id", ")", "to", "all", "shards", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L537-L545
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.shard_stores
def shard_stores(self, using=None, **kwargs): """ Provides store information for shard copies of the index. Store information reports on which nodes shard copies exist, the shard copy version, indicating how recent they are, and any exceptions encountered while opening the shard index or from earlier engine failure. Any additional keyword arguments will be passed to ``Elasticsearch.indices.shard_stores`` unchanged. """ return self._get_connection(using).indices.shard_stores(index=self._name, **kwargs)
python
def shard_stores(self, using=None, **kwargs): """ Provides store information for shard copies of the index. Store information reports on which nodes shard copies exist, the shard copy version, indicating how recent they are, and any exceptions encountered while opening the shard index or from earlier engine failure. Any additional keyword arguments will be passed to ``Elasticsearch.indices.shard_stores`` unchanged. """ return self._get_connection(using).indices.shard_stores(index=self._name, **kwargs)
[ "def", "shard_stores", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "shard_stores", "(", "index", "=", "self", ".", "_name", ",", "*", "*"...
Provides store information for shard copies of the index. Store information reports on which nodes shard copies exist, the shard copy version, indicating how recent they are, and any exceptions encountered while opening the shard index or from earlier engine failure. Any additional keyword arguments will be passed to ``Elasticsearch.indices.shard_stores`` unchanged.
[ "Provides", "store", "information", "for", "shard", "copies", "of", "the", "index", ".", "Store", "information", "reports", "on", "which", "nodes", "shard", "copies", "exist", "the", "shard", "copy", "version", "indicating", "how", "recent", "they", "are", "an...
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L547-L557
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.forcemerge
def forcemerge(self, using=None, **kwargs): """ The force merge API allows to force merging of the index through an API. The merge relates to the number of segments a Lucene index holds within each shard. The force merge operation allows to reduce the number of segments by merging them. This call will block until the merge is complete. If the http connection is lost, the request will continue in the background, and any new requests will block until the previous force merge is complete. Any additional keyword arguments will be passed to ``Elasticsearch.indices.forcemerge`` unchanged. """ return self._get_connection(using).indices.forcemerge(index=self._name, **kwargs)
python
def forcemerge(self, using=None, **kwargs): """ The force merge API allows to force merging of the index through an API. The merge relates to the number of segments a Lucene index holds within each shard. The force merge operation allows to reduce the number of segments by merging them. This call will block until the merge is complete. If the http connection is lost, the request will continue in the background, and any new requests will block until the previous force merge is complete. Any additional keyword arguments will be passed to ``Elasticsearch.indices.forcemerge`` unchanged. """ return self._get_connection(using).indices.forcemerge(index=self._name, **kwargs)
[ "def", "forcemerge", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "forcemerge", "(", "index", "=", "self", ".", "_name", ",", "*", "*", ...
The force merge API allows to force merging of the index through an API. The merge relates to the number of segments a Lucene index holds within each shard. The force merge operation allows to reduce the number of segments by merging them. This call will block until the merge is complete. If the http connection is lost, the request will continue in the background, and any new requests will block until the previous force merge is complete. Any additional keyword arguments will be passed to ``Elasticsearch.indices.forcemerge`` unchanged.
[ "The", "force", "merge", "API", "allows", "to", "force", "merging", "of", "the", "index", "through", "an", "API", ".", "The", "merge", "relates", "to", "the", "number", "of", "segments", "a", "Lucene", "index", "holds", "within", "each", "shard", ".", "T...
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L559-L573
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/index.py
Index.shrink
def shrink(self, using=None, **kwargs): """ The shrink index API allows you to shrink an existing index into a new index with fewer primary shards. The number of primary shards in the target index must be a factor of the shards in the source index. For example an index with 8 primary shards can be shrunk into 4, 2 or 1 primary shards or an index with 15 primary shards can be shrunk into 5, 3 or 1. If the number of shards in the index is a prime number it can only be shrunk into a single primary shard. Before shrinking, a (primary or replica) copy of every shard in the index must be present on the same node. Any additional keyword arguments will be passed to ``Elasticsearch.indices.shrink`` unchanged. """ return self._get_connection(using).indices.shrink(index=self._name, **kwargs)
python
def shrink(self, using=None, **kwargs): """ The shrink index API allows you to shrink an existing index into a new index with fewer primary shards. The number of primary shards in the target index must be a factor of the shards in the source index. For example an index with 8 primary shards can be shrunk into 4, 2 or 1 primary shards or an index with 15 primary shards can be shrunk into 5, 3 or 1. If the number of shards in the index is a prime number it can only be shrunk into a single primary shard. Before shrinking, a (primary or replica) copy of every shard in the index must be present on the same node. Any additional keyword arguments will be passed to ``Elasticsearch.indices.shrink`` unchanged. """ return self._get_connection(using).indices.shrink(index=self._name, **kwargs)
[ "def", "shrink", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "shrink", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "kwargs"...
The shrink index API allows you to shrink an existing index into a new index with fewer primary shards. The number of primary shards in the target index must be a factor of the shards in the source index. For example an index with 8 primary shards can be shrunk into 4, 2 or 1 primary shards or an index with 15 primary shards can be shrunk into 5, 3 or 1. If the number of shards in the index is a prime number it can only be shrunk into a single primary shard. Before shrinking, a (primary or replica) copy of every shard in the index must be present on the same node. Any additional keyword arguments will be passed to ``Elasticsearch.indices.shrink`` unchanged.
[ "The", "shrink", "index", "API", "allows", "you", "to", "shrink", "an", "existing", "index", "into", "a", "new", "index", "with", "fewer", "primary", "shards", ".", "The", "number", "of", "primary", "shards", "in", "the", "target", "index", "must", "be", ...
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/index.py#L575-L590
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/connections.py
Connections.configure
def configure(self, **kwargs): """ Configure multiple connections at once, useful for passing in config dictionaries obtained from other sources, like Django's settings or a configuration management tool. Example:: connections.configure( default={'hosts': 'localhost'}, dev={'hosts': ['esdev1.example.com:9200'], sniff_on_start=True} ) Connections will only be constructed lazily when requested through ``get_connection``. """ for k in list(self._conns): # try and preserve existing client to keep the persistent connections alive if k in self._kwargs and kwargs.get(k, None) == self._kwargs[k]: continue del self._conns[k] self._kwargs = kwargs
python
def configure(self, **kwargs): """ Configure multiple connections at once, useful for passing in config dictionaries obtained from other sources, like Django's settings or a configuration management tool. Example:: connections.configure( default={'hosts': 'localhost'}, dev={'hosts': ['esdev1.example.com:9200'], sniff_on_start=True} ) Connections will only be constructed lazily when requested through ``get_connection``. """ for k in list(self._conns): # try and preserve existing client to keep the persistent connections alive if k in self._kwargs and kwargs.get(k, None) == self._kwargs[k]: continue del self._conns[k] self._kwargs = kwargs
[ "def", "configure", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", "in", "list", "(", "self", ".", "_conns", ")", ":", "# try and preserve existing client to keep the persistent connections alive", "if", "k", "in", "self", ".", "_kwargs", "and", "...
Configure multiple connections at once, useful for passing in config dictionaries obtained from other sources, like Django's settings or a configuration management tool. Example:: connections.configure( default={'hosts': 'localhost'}, dev={'hosts': ['esdev1.example.com:9200'], sniff_on_start=True} ) Connections will only be constructed lazily when requested through ``get_connection``.
[ "Configure", "multiple", "connections", "at", "once", "useful", "for", "passing", "in", "config", "dictionaries", "obtained", "from", "other", "sources", "like", "Django", "s", "settings", "or", "a", "configuration", "management", "tool", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/connections.py#L16-L37
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/connections.py
Connections.remove_connection
def remove_connection(self, alias): """ Remove connection from the registry. Raises ``KeyError`` if connection wasn't found. """ errors = 0 for d in (self._conns, self._kwargs): try: del d[alias] except KeyError: errors += 1 if errors == 2: raise KeyError('There is no connection with alias %r.' % alias)
python
def remove_connection(self, alias): """ Remove connection from the registry. Raises ``KeyError`` if connection wasn't found. """ errors = 0 for d in (self._conns, self._kwargs): try: del d[alias] except KeyError: errors += 1 if errors == 2: raise KeyError('There is no connection with alias %r.' % alias)
[ "def", "remove_connection", "(", "self", ",", "alias", ")", ":", "errors", "=", "0", "for", "d", "in", "(", "self", ".", "_conns", ",", "self", ".", "_kwargs", ")", ":", "try", ":", "del", "d", "[", "alias", "]", "except", "KeyError", ":", "errors"...
Remove connection from the registry. Raises ``KeyError`` if connection wasn't found.
[ "Remove", "connection", "from", "the", "registry", ".", "Raises", "KeyError", "if", "connection", "wasn", "t", "found", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/connections.py#L45-L58
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/connections.py
Connections.create_connection
def create_connection(self, alias='default', **kwargs): """ Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias. """ kwargs.setdefault('serializer', serializer) conn = self._conns[alias] = Elasticsearch(**kwargs) return conn
python
def create_connection(self, alias='default', **kwargs): """ Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias. """ kwargs.setdefault('serializer', serializer) conn = self._conns[alias] = Elasticsearch(**kwargs) return conn
[ "def", "create_connection", "(", "self", ",", "alias", "=", "'default'", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'serializer'", ",", "serializer", ")", "conn", "=", "self", ".", "_conns", "[", "alias", "]", "=", "Elasticsear...
Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias.
[ "Construct", "an", "instance", "of", "elasticsearch", ".", "Elasticsearch", "and", "register", "it", "under", "given", "alias", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/connections.py#L60-L67
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/connections.py
Connections.get_connection
def get_connection(self, alias='default'): """ Retrieve a connection, construct it if necessary (only configuration was passed to us). If a non-string alias has been passed through we assume it's already a client instance and will just return it as-is. Raises ``KeyError`` if no client (or its definition) is registered under the alias. """ # do not check isinstance(Elasticsearch) so that people can wrap their # clients if not isinstance(alias, string_types): return alias # connection already established try: return self._conns[alias] except KeyError: pass # if not, try to create it try: return self.create_connection(alias, **self._kwargs[alias]) except KeyError: # no connection and no kwargs to set one up raise KeyError('There is no connection with alias %r.' % alias)
python
def get_connection(self, alias='default'): """ Retrieve a connection, construct it if necessary (only configuration was passed to us). If a non-string alias has been passed through we assume it's already a client instance and will just return it as-is. Raises ``KeyError`` if no client (or its definition) is registered under the alias. """ # do not check isinstance(Elasticsearch) so that people can wrap their # clients if not isinstance(alias, string_types): return alias # connection already established try: return self._conns[alias] except KeyError: pass # if not, try to create it try: return self.create_connection(alias, **self._kwargs[alias]) except KeyError: # no connection and no kwargs to set one up raise KeyError('There is no connection with alias %r.' % alias)
[ "def", "get_connection", "(", "self", ",", "alias", "=", "'default'", ")", ":", "# do not check isinstance(Elasticsearch) so that people can wrap their", "# clients", "if", "not", "isinstance", "(", "alias", ",", "string_types", ")", ":", "return", "alias", "# connectio...
Retrieve a connection, construct it if necessary (only configuration was passed to us). If a non-string alias has been passed through we assume it's already a client instance and will just return it as-is. Raises ``KeyError`` if no client (or its definition) is registered under the alias.
[ "Retrieve", "a", "connection", "construct", "it", "if", "necessary", "(", "only", "configuration", "was", "passed", "to", "us", ")", ".", "If", "a", "non", "-", "string", "alias", "has", "been", "passed", "through", "we", "assume", "it", "s", "already", ...
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/connections.py#L69-L94
train
elastic/elasticsearch-dsl-py
examples/alias_migration.py
setup
def setup(): """ Create the index template in elasticsearch specifying the mappings and any settings to be used. This can be run at any time, ideally at every new code deploy. """ # create an index template index_template = BlogPost._index.as_template(ALIAS, PATTERN) # upload the template into elasticsearch # potentially overriding the one already there index_template.save() # create the first index if it doesn't exist if not BlogPost._index.exists(): migrate(move_data=False)
python
def setup(): """ Create the index template in elasticsearch specifying the mappings and any settings to be used. This can be run at any time, ideally at every new code deploy. """ # create an index template index_template = BlogPost._index.as_template(ALIAS, PATTERN) # upload the template into elasticsearch # potentially overriding the one already there index_template.save() # create the first index if it doesn't exist if not BlogPost._index.exists(): migrate(move_data=False)
[ "def", "setup", "(", ")", ":", "# create an index template", "index_template", "=", "BlogPost", ".", "_index", ".", "as_template", "(", "ALIAS", ",", "PATTERN", ")", "# upload the template into elasticsearch", "# potentially overriding the one already there", "index_template"...
Create the index template in elasticsearch specifying the mappings and any settings to be used. This can be run at any time, ideally at every new code deploy.
[ "Create", "the", "index", "template", "in", "elasticsearch", "specifying", "the", "mappings", "and", "any", "settings", "to", "be", "used", ".", "This", "can", "be", "run", "at", "any", "time", "ideally", "at", "every", "new", "code", "deploy", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/examples/alias_migration.py#L54-L68
train
elastic/elasticsearch-dsl-py
examples/alias_migration.py
migrate
def migrate(move_data=True, update_alias=True): """ Upgrade function that creates a new index for the data. Optionally it also can (and by default will) reindex previous copy of the data into the new index (specify ``move_data=False`` to skip this step) and update the alias to point to the latest index (set ``update_alias=False`` to skip). Note that while this function is running the application can still perform any and all searches without any loss of functionality. It should, however, not perform any writes at this time as those might be lost. """ # construct a new index name by appending current timestamp next_index = PATTERN.replace('*', datetime.now().strftime('%Y%m%d%H%M%S%f')) # get the low level connection es = connections.get_connection() # create new index, it will use the settings from the template es.indices.create(index=next_index) if move_data: # move data from current alias to the new index es.reindex( body={"source": {"index": ALIAS}, "dest": {"index": next_index}}, request_timeout=3600 ) # refresh the index to make the changes visible es.indices.refresh(index=next_index) if update_alias: # repoint the alias to point to the newly created index es.indices.update_aliases(body={ 'actions': [ {"remove": {"alias": ALIAS, "index": PATTERN}}, {"add": {"alias": ALIAS, "index": next_index}}, ] })
python
def migrate(move_data=True, update_alias=True): """ Upgrade function that creates a new index for the data. Optionally it also can (and by default will) reindex previous copy of the data into the new index (specify ``move_data=False`` to skip this step) and update the alias to point to the latest index (set ``update_alias=False`` to skip). Note that while this function is running the application can still perform any and all searches without any loss of functionality. It should, however, not perform any writes at this time as those might be lost. """ # construct a new index name by appending current timestamp next_index = PATTERN.replace('*', datetime.now().strftime('%Y%m%d%H%M%S%f')) # get the low level connection es = connections.get_connection() # create new index, it will use the settings from the template es.indices.create(index=next_index) if move_data: # move data from current alias to the new index es.reindex( body={"source": {"index": ALIAS}, "dest": {"index": next_index}}, request_timeout=3600 ) # refresh the index to make the changes visible es.indices.refresh(index=next_index) if update_alias: # repoint the alias to point to the newly created index es.indices.update_aliases(body={ 'actions': [ {"remove": {"alias": ALIAS, "index": PATTERN}}, {"add": {"alias": ALIAS, "index": next_index}}, ] })
[ "def", "migrate", "(", "move_data", "=", "True", ",", "update_alias", "=", "True", ")", ":", "# construct a new index name by appending current timestamp", "next_index", "=", "PATTERN", ".", "replace", "(", "'*'", ",", "datetime", ".", "now", "(", ")", ".", "str...
Upgrade function that creates a new index for the data. Optionally it also can (and by default will) reindex previous copy of the data into the new index (specify ``move_data=False`` to skip this step) and update the alias to point to the latest index (set ``update_alias=False`` to skip). Note that while this function is running the application can still perform any and all searches without any loss of functionality. It should, however, not perform any writes at this time as those might be lost.
[ "Upgrade", "function", "that", "creates", "a", "new", "index", "for", "the", "data", ".", "Optionally", "it", "also", "can", "(", "and", "by", "default", "will", ")", "reindex", "previous", "copy", "of", "the", "data", "into", "the", "new", "index", "(",...
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/examples/alias_migration.py#L70-L106
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/analysis.py
CustomAnalyzer.simulate
def simulate(self, text, using='default', explain=False, attributes=None): """ Use the Analyze API of elasticsearch to test the outcome of this analyzer. :arg text: Text to be analyzed :arg using: connection alias to use, defaults to ``'default'`` :arg explain: will output all token attributes for each token. You can filter token attributes you want to output by setting ``attributes`` option. :arg attributes: if ``explain`` is specified, filter the token attributes to return. """ es = connections.get_connection(using) body = {'text': text, 'explain': explain} if attributes: body['attributes'] = attributes definition = self.get_analysis_definition() analyzer_def = self.get_definition() for section in ('tokenizer', 'char_filter', 'filter'): if section not in analyzer_def: continue sec_def = definition.get(section, {}) sec_names = analyzer_def[section] if isinstance(sec_names, six.string_types): body[section] = sec_def.get(sec_names, sec_names) else: body[section] = [sec_def.get(sec_name, sec_name) for sec_name in sec_names] if self._builtin_type != 'custom': body['analyzer'] = self._builtin_type return AttrDict(es.indices.analyze(body=body))
python
def simulate(self, text, using='default', explain=False, attributes=None): """ Use the Analyze API of elasticsearch to test the outcome of this analyzer. :arg text: Text to be analyzed :arg using: connection alias to use, defaults to ``'default'`` :arg explain: will output all token attributes for each token. You can filter token attributes you want to output by setting ``attributes`` option. :arg attributes: if ``explain`` is specified, filter the token attributes to return. """ es = connections.get_connection(using) body = {'text': text, 'explain': explain} if attributes: body['attributes'] = attributes definition = self.get_analysis_definition() analyzer_def = self.get_definition() for section in ('tokenizer', 'char_filter', 'filter'): if section not in analyzer_def: continue sec_def = definition.get(section, {}) sec_names = analyzer_def[section] if isinstance(sec_names, six.string_types): body[section] = sec_def.get(sec_names, sec_names) else: body[section] = [sec_def.get(sec_name, sec_name) for sec_name in sec_names] if self._builtin_type != 'custom': body['analyzer'] = self._builtin_type return AttrDict(es.indices.analyze(body=body))
[ "def", "simulate", "(", "self", ",", "text", ",", "using", "=", "'default'", ",", "explain", "=", "False", ",", "attributes", "=", "None", ")", ":", "es", "=", "connections", ".", "get_connection", "(", "using", ")", "body", "=", "{", "'text'", ":", ...
Use the Analyze API of elasticsearch to test the outcome of this analyzer. :arg text: Text to be analyzed :arg using: connection alias to use, defaults to ``'default'`` :arg explain: will output all token attributes for each token. You can filter token attributes you want to output by setting ``attributes`` option. :arg attributes: if ``explain`` is specified, filter the token attributes to return.
[ "Use", "the", "Analyze", "API", "of", "elasticsearch", "to", "test", "the", "outcome", "of", "this", "analyzer", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/analysis.py#L85-L120
train
elastic/elasticsearch-dsl-py
examples/parent_child.py
Question.get_answers
def get_answers(self): """ Get answers either from inner_hits already present or by searching elasticsearch. """ if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits: return self.meta.inner_hits.answer.hits return list(self.search_answers())
python
def get_answers(self): """ Get answers either from inner_hits already present or by searching elasticsearch. """ if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits: return self.meta.inner_hits.answer.hits return list(self.search_answers())
[ "def", "get_answers", "(", "self", ")", ":", "if", "'inner_hits'", "in", "self", ".", "meta", "and", "'answer'", "in", "self", ".", "meta", ".", "inner_hits", ":", "return", "self", ".", "meta", ".", "inner_hits", ".", "answer", ".", "hits", "return", ...
Get answers either from inner_hits already present or by searching elasticsearch.
[ "Get", "answers", "either", "from", "inner_hits", "already", "present", "or", "by", "searching", "elasticsearch", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/examples/parent_child.py#L130-L137
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
Facet.get_aggregation
def get_aggregation(self): """ Return the aggregation object. """ agg = A(self.agg_type, **self._params) if self._metric: agg.metric('metric', self._metric) return agg
python
def get_aggregation(self): """ Return the aggregation object. """ agg = A(self.agg_type, **self._params) if self._metric: agg.metric('metric', self._metric) return agg
[ "def", "get_aggregation", "(", "self", ")", ":", "agg", "=", "A", "(", "self", ".", "agg_type", ",", "*", "*", "self", ".", "_params", ")", "if", "self", ".", "_metric", ":", "agg", ".", "metric", "(", "'metric'", ",", "self", ".", "_metric", ")", ...
Return the aggregation object.
[ "Return", "the", "aggregation", "object", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L30-L37
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
Facet.add_filter
def add_filter(self, filter_values): """ Construct a filter. """ if not filter_values: return f = self.get_value_filter(filter_values[0]) for v in filter_values[1:]: f |= self.get_value_filter(v) return f
python
def add_filter(self, filter_values): """ Construct a filter. """ if not filter_values: return f = self.get_value_filter(filter_values[0]) for v in filter_values[1:]: f |= self.get_value_filter(v) return f
[ "def", "add_filter", "(", "self", ",", "filter_values", ")", ":", "if", "not", "filter_values", ":", "return", "f", "=", "self", ".", "get_value_filter", "(", "filter_values", "[", "0", "]", ")", "for", "v", "in", "filter_values", "[", "1", ":", "]", "...
Construct a filter.
[ "Construct", "a", "filter", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L39-L49
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
Facet.get_values
def get_values(self, data, filter_values): """ Turn the raw bucket data into a list of tuples containing the key, number of documents and a flag indicating whether this value has been selected or not. """ out = [] for bucket in data.buckets: key = self.get_value(bucket) out.append(( key, self.get_metric(bucket), self.is_filtered(key, filter_values) )) return out
python
def get_values(self, data, filter_values): """ Turn the raw bucket data into a list of tuples containing the key, number of documents and a flag indicating whether this value has been selected or not. """ out = [] for bucket in data.buckets: key = self.get_value(bucket) out.append(( key, self.get_metric(bucket), self.is_filtered(key, filter_values) )) return out
[ "def", "get_values", "(", "self", ",", "data", ",", "filter_values", ")", ":", "out", "=", "[", "]", "for", "bucket", "in", "data", ".", "buckets", ":", "key", "=", "self", ".", "get_value", "(", "bucket", ")", "out", ".", "append", "(", "(", "key"...
Turn the raw bucket data into a list of tuples containing the key, number of documents and a flag indicating whether this value has been selected or not.
[ "Turn", "the", "raw", "bucket", "data", "into", "a", "list", "of", "tuples", "containing", "the", "key", "number", "of", "documents", "and", "a", "flag", "indicating", "whether", "this", "value", "has", "been", "selected", "or", "not", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L77-L91
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.add_filter
def add_filter(self, name, filter_values): """ Add a filter for a facet. """ # normalize the value into a list if not isinstance(filter_values, (tuple, list)): if filter_values is None: return filter_values = [filter_values, ] # remember the filter values for use in FacetedResponse self.filter_values[name] = filter_values # get the filter from the facet f = self.facets[name].add_filter(filter_values) if f is None: return self._filters[name] = f
python
def add_filter(self, name, filter_values): """ Add a filter for a facet. """ # normalize the value into a list if not isinstance(filter_values, (tuple, list)): if filter_values is None: return filter_values = [filter_values, ] # remember the filter values for use in FacetedResponse self.filter_values[name] = filter_values # get the filter from the facet f = self.facets[name].add_filter(filter_values) if f is None: return self._filters[name] = f
[ "def", "add_filter", "(", "self", ",", "name", ",", "filter_values", ")", ":", "# normalize the value into a list", "if", "not", "isinstance", "(", "filter_values", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "filter_values", "is", "None", ":", "ret...
Add a filter for a facet.
[ "Add", "a", "filter", "for", "a", "facet", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L283-L301
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.search
def search(self): """ Returns the base Search object to which the facets are added. You can customize the query by overriding this method and returning a modified search object. """ s = Search(doc_type=self.doc_types, index=self.index, using=self.using) return s.response_class(FacetedResponse)
python
def search(self): """ Returns the base Search object to which the facets are added. You can customize the query by overriding this method and returning a modified search object. """ s = Search(doc_type=self.doc_types, index=self.index, using=self.using) return s.response_class(FacetedResponse)
[ "def", "search", "(", "self", ")", ":", "s", "=", "Search", "(", "doc_type", "=", "self", ".", "doc_types", ",", "index", "=", "self", ".", "index", ",", "using", "=", "self", ".", "using", ")", "return", "s", ".", "response_class", "(", "FacetedResp...
Returns the base Search object to which the facets are added. You can customize the query by overriding this method and returning a modified search object.
[ "Returns", "the", "base", "Search", "object", "to", "which", "the", "facets", "are", "added", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L303-L311
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.query
def query(self, search, query): """ Add query part to ``search``. Override this if you wish to customize the query used. """ if query: if self.fields: return search.query('multi_match', fields=self.fields, query=query) else: return search.query('multi_match', query=query) return search
python
def query(self, search, query): """ Add query part to ``search``. Override this if you wish to customize the query used. """ if query: if self.fields: return search.query('multi_match', fields=self.fields, query=query) else: return search.query('multi_match', query=query) return search
[ "def", "query", "(", "self", ",", "search", ",", "query", ")", ":", "if", "query", ":", "if", "self", ".", "fields", ":", "return", "search", ".", "query", "(", "'multi_match'", ",", "fields", "=", "self", ".", "fields", ",", "query", "=", "query", ...
Add query part to ``search``. Override this if you wish to customize the query used.
[ "Add", "query", "part", "to", "search", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L313-L324
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.aggregate
def aggregate(self, search): """ Add aggregations representing the facets selected, including potential filters. """ for f, facet in iteritems(self.facets): agg = facet.get_aggregation() agg_filter = MatchAll() for field, filter in iteritems(self._filters): if f == field: continue agg_filter &= filter search.aggs.bucket( '_filter_' + f, 'filter', filter=agg_filter ).bucket(f, agg)
python
def aggregate(self, search): """ Add aggregations representing the facets selected, including potential filters. """ for f, facet in iteritems(self.facets): agg = facet.get_aggregation() agg_filter = MatchAll() for field, filter in iteritems(self._filters): if f == field: continue agg_filter &= filter search.aggs.bucket( '_filter_' + f, 'filter', filter=agg_filter ).bucket(f, agg)
[ "def", "aggregate", "(", "self", ",", "search", ")", ":", "for", "f", ",", "facet", "in", "iteritems", "(", "self", ".", "facets", ")", ":", "agg", "=", "facet", ".", "get_aggregation", "(", ")", "agg_filter", "=", "MatchAll", "(", ")", "for", "field...
Add aggregations representing the facets selected, including potential filters.
[ "Add", "aggregations", "representing", "the", "facets", "selected", "including", "potential", "filters", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L326-L342
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.filter
def filter(self, search): """ Add a ``post_filter`` to the search request narrowing the results based on the facet filters. """ if not self._filters: return search post_filter = MatchAll() for f in itervalues(self._filters): post_filter &= f return search.post_filter(post_filter)
python
def filter(self, search): """ Add a ``post_filter`` to the search request narrowing the results based on the facet filters. """ if not self._filters: return search post_filter = MatchAll() for f in itervalues(self._filters): post_filter &= f return search.post_filter(post_filter)
[ "def", "filter", "(", "self", ",", "search", ")", ":", "if", "not", "self", ".", "_filters", ":", "return", "search", "post_filter", "=", "MatchAll", "(", ")", "for", "f", "in", "itervalues", "(", "self", ".", "_filters", ")", ":", "post_filter", "&=",...
Add a ``post_filter`` to the search request narrowing the results based on the facet filters.
[ "Add", "a", "post_filter", "to", "the", "search", "request", "narrowing", "the", "results", "based", "on", "the", "facet", "filters", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L344-L355
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.highlight
def highlight(self, search): """ Add highlighting for all the fields """ return search.highlight(*(f if '^' not in f else f.split('^', 1)[0] for f in self.fields))
python
def highlight(self, search): """ Add highlighting for all the fields """ return search.highlight(*(f if '^' not in f else f.split('^', 1)[0] for f in self.fields))
[ "def", "highlight", "(", "self", ",", "search", ")", ":", "return", "search", ".", "highlight", "(", "*", "(", "f", "if", "'^'", "not", "in", "f", "else", "f", ".", "split", "(", "'^'", ",", "1", ")", "[", "0", "]", "for", "f", "in", "self", ...
Add highlighting for all the fields
[ "Add", "highlighting", "for", "all", "the", "fields" ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L357-L362
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.sort
def sort(self, search): """ Add sorting information to the request. """ if self._sort: search = search.sort(*self._sort) return search
python
def sort(self, search): """ Add sorting information to the request. """ if self._sort: search = search.sort(*self._sort) return search
[ "def", "sort", "(", "self", ",", "search", ")", ":", "if", "self", ".", "_sort", ":", "search", "=", "search", ".", "sort", "(", "*", "self", ".", "_sort", ")", "return", "search" ]
Add sorting information to the request.
[ "Add", "sorting", "information", "to", "the", "request", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L364-L370
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.build_search
def build_search(self): """ Construct the ``Search`` object. """ s = self.search() s = self.query(s, self._query) s = self.filter(s) if self.fields: s = self.highlight(s) s = self.sort(s) self.aggregate(s) return s
python
def build_search(self): """ Construct the ``Search`` object. """ s = self.search() s = self.query(s, self._query) s = self.filter(s) if self.fields: s = self.highlight(s) s = self.sort(s) self.aggregate(s) return s
[ "def", "build_search", "(", "self", ")", ":", "s", "=", "self", ".", "search", "(", ")", "s", "=", "self", ".", "query", "(", "s", ",", "self", ".", "_query", ")", "s", "=", "self", ".", "filter", "(", "s", ")", "if", "self", ".", "fields", "...
Construct the ``Search`` object.
[ "Construct", "the", "Search", "object", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L372-L383
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/faceted_search.py
FacetedSearch.execute
def execute(self): """ Execute the search and return the response. """ r = self._s.execute() r._faceted_search = self return r
python
def execute(self): """ Execute the search and return the response. """ r = self._s.execute() r._faceted_search = self return r
[ "def", "execute", "(", "self", ")", ":", "r", "=", "self", ".", "_s", ".", "execute", "(", ")", "r", ".", "_faceted_search", "=", "self", "return", "r" ]
Execute the search and return the response.
[ "Execute", "the", "search", "and", "return", "the", "response", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L385-L391
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Request.params
def params(self, **kwargs): """ Specify query params to be used when executing the search. All the keyword arguments will override the current values. See https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search for all available parameters. Example:: s = Search() s = s.params(routing='user-1', preference='local') """ s = self._clone() s._params.update(kwargs) return s
python
def params(self, **kwargs): """ Specify query params to be used when executing the search. All the keyword arguments will override the current values. See https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search for all available parameters. Example:: s = Search() s = s.params(routing='user-1', preference='local') """ s = self._clone() s._params.update(kwargs) return s
[ "def", "params", "(", "self", ",", "*", "*", "kwargs", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "s", ".", "_params", ".", "update", "(", "kwargs", ")", "return", "s" ]
Specify query params to be used when executing the search. All the keyword arguments will override the current values. See https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search for all available parameters. Example:: s = Search() s = s.params(routing='user-1', preference='local')
[ "Specify", "query", "params", "to", "be", "used", "when", "executing", "the", "search", ".", "All", "the", "keyword", "arguments", "will", "override", "the", "current", "values", ".", "See", "https", ":", "//", "elasticsearch", "-", "py", ".", "readthedocs",...
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L131-L145
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Request.index
def index(self, *index): """ Set the index for the search. If called empty it will remove all information. Example: s = Search() s = s.index('twitter-2015.01.01', 'twitter-2015.01.02') s = s.index(['twitter-2015.01.01', 'twitter-2015.01.02']) """ # .index() resets s = self._clone() if not index: s._index = None else: indexes = [] for i in index: if isinstance(i, string_types): indexes.append(i) elif isinstance(i, list): indexes += i elif isinstance(i, tuple): indexes += list(i) s._index = (self._index or []) + indexes return s
python
def index(self, *index): """ Set the index for the search. If called empty it will remove all information. Example: s = Search() s = s.index('twitter-2015.01.01', 'twitter-2015.01.02') s = s.index(['twitter-2015.01.01', 'twitter-2015.01.02']) """ # .index() resets s = self._clone() if not index: s._index = None else: indexes = [] for i in index: if isinstance(i, string_types): indexes.append(i) elif isinstance(i, list): indexes += i elif isinstance(i, tuple): indexes += list(i) s._index = (self._index or []) + indexes return s
[ "def", "index", "(", "self", ",", "*", "index", ")", ":", "# .index() resets", "s", "=", "self", ".", "_clone", "(", ")", "if", "not", "index", ":", "s", ".", "_index", "=", "None", "else", ":", "indexes", "=", "[", "]", "for", "i", "in", "index"...
Set the index for the search. If called empty it will remove all information. Example: s = Search() s = s.index('twitter-2015.01.01', 'twitter-2015.01.02') s = s.index(['twitter-2015.01.01', 'twitter-2015.01.02'])
[ "Set", "the", "index", "for", "the", "search", ".", "If", "called", "empty", "it", "will", "remove", "all", "information", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L147-L173
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Request.doc_type
def doc_type(self, *doc_type, **kwargs): """ Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of ``Document``. You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used instead of the Hit class. If no doc_type is supplied any information stored on the instance will be erased. Example: s = Search().doc_type('product', 'store', User, custom=my_callback) """ # .doc_type() resets s = self._clone() if not doc_type and not kwargs: s._doc_type = [] s._doc_type_map = {} else: s._doc_type.extend(doc_type) s._doc_type.extend(kwargs.keys()) s._doc_type_map.update(kwargs) return s
python
def doc_type(self, *doc_type, **kwargs): """ Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of ``Document``. You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used instead of the Hit class. If no doc_type is supplied any information stored on the instance will be erased. Example: s = Search().doc_type('product', 'store', User, custom=my_callback) """ # .doc_type() resets s = self._clone() if not doc_type and not kwargs: s._doc_type = [] s._doc_type_map = {} else: s._doc_type.extend(doc_type) s._doc_type.extend(kwargs.keys()) s._doc_type_map.update(kwargs) return s
[ "def", "doc_type", "(", "self", ",", "*", "doc_type", ",", "*", "*", "kwargs", ")", ":", "# .doc_type() resets", "s", "=", "self", ".", "_clone", "(", ")", "if", "not", "doc_type", "and", "not", "kwargs", ":", "s", ".", "_doc_type", "=", "[", "]", ...
Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of ``Document``. You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used instead of the Hit class. If no doc_type is supplied any information stored on the instance will be erased. Example: s = Search().doc_type('product', 'store', User, custom=my_callback)
[ "Set", "the", "type", "to", "search", "through", ".", "You", "can", "supply", "a", "single", "value", "or", "multiple", ".", "Values", "can", "be", "strings", "or", "subclasses", "of", "Document", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L225-L249
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Request.using
def using(self, client): """ Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged. :arg client: an instance of ``elasticsearch.Elasticsearch`` to use or an alias to look up in ``elasticsearch_dsl.connections`` """ s = self._clone() s._using = client return s
python
def using(self, client): """ Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged. :arg client: an instance of ``elasticsearch.Elasticsearch`` to use or an alias to look up in ``elasticsearch_dsl.connections`` """ s = self._clone() s._using = client return s
[ "def", "using", "(", "self", ",", "client", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "s", ".", "_using", "=", "client", "return", "s" ]
Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged. :arg client: an instance of ``elasticsearch.Elasticsearch`` to use or an alias to look up in ``elasticsearch_dsl.connections``
[ "Associate", "the", "search", "request", "with", "an", "elasticsearch", "client", ".", "A", "fresh", "copy", "will", "be", "returned", "with", "current", "instance", "remaining", "unchanged", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L251-L262
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Request.extra
def extra(self, **kwargs): """ Add extra keys to the request body. Mostly here for backwards compatibility. """ s = self._clone() if 'from_' in kwargs: kwargs['from'] = kwargs.pop('from_') s._extra.update(kwargs) return s
python
def extra(self, **kwargs): """ Add extra keys to the request body. Mostly here for backwards compatibility. """ s = self._clone() if 'from_' in kwargs: kwargs['from'] = kwargs.pop('from_') s._extra.update(kwargs) return s
[ "def", "extra", "(", "self", ",", "*", "*", "kwargs", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "if", "'from_'", "in", "kwargs", ":", "kwargs", "[", "'from'", "]", "=", "kwargs", ".", "pop", "(", "'from_'", ")", "s", ".", "_extra", "...
Add extra keys to the request body. Mostly here for backwards compatibility.
[ "Add", "extra", "keys", "to", "the", "request", "body", ".", "Mostly", "here", "for", "backwards", "compatibility", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L264-L273
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search._clone
def _clone(self): """ Return a clone of the current search request. Performs a shallow copy of all the underlying objects. Used internally by most state modifying APIs. """ s = super(Search, self)._clone() s._response_class = self._response_class s._sort = self._sort[:] s._source = copy.copy(self._source) \ if self._source is not None else None s._highlight = self._highlight.copy() s._highlight_opts = self._highlight_opts.copy() s._suggest = self._suggest.copy() s._script_fields = self._script_fields.copy() for x in ('query', 'post_filter'): getattr(s, x)._proxied = getattr(self, x)._proxied # copy top-level bucket definitions if self.aggs._params.get('aggs'): s.aggs._params = {'aggs': self.aggs._params['aggs'].copy()} return s
python
def _clone(self): """ Return a clone of the current search request. Performs a shallow copy of all the underlying objects. Used internally by most state modifying APIs. """ s = super(Search, self)._clone() s._response_class = self._response_class s._sort = self._sort[:] s._source = copy.copy(self._source) \ if self._source is not None else None s._highlight = self._highlight.copy() s._highlight_opts = self._highlight_opts.copy() s._suggest = self._suggest.copy() s._script_fields = self._script_fields.copy() for x in ('query', 'post_filter'): getattr(s, x)._proxied = getattr(self, x)._proxied # copy top-level bucket definitions if self.aggs._params.get('aggs'): s.aggs._params = {'aggs': self.aggs._params['aggs'].copy()} return s
[ "def", "_clone", "(", "self", ")", ":", "s", "=", "super", "(", "Search", ",", "self", ")", ".", "_clone", "(", ")", "s", ".", "_response_class", "=", "self", ".", "_response_class", "s", ".", "_sort", "=", "self", ".", "_sort", "[", ":", "]", "s...
Return a clone of the current search request. Performs a shallow copy of all the underlying objects. Used internally by most state modifying APIs.
[ "Return", "a", "clone", "of", "the", "current", "search", "request", ".", "Performs", "a", "shallow", "copy", "of", "all", "the", "underlying", "objects", ".", "Used", "internally", "by", "most", "state", "modifying", "APIs", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L379-L401
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.response_class
def response_class(self, cls): """ Override the default wrapper used for the response. """ s = self._clone() s._response_class = cls return s
python
def response_class(self, cls): """ Override the default wrapper used for the response. """ s = self._clone() s._response_class = cls return s
[ "def", "response_class", "(", "self", ",", "cls", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "s", ".", "_response_class", "=", "cls", "return", "s" ]
Override the default wrapper used for the response.
[ "Override", "the", "default", "wrapper", "used", "for", "the", "response", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L403-L409
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.update_from_dict
def update_from_dict(self, d): """ Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by ``from_dict``. """ d = d.copy() if 'query' in d: self.query._proxied = Q(d.pop('query')) if 'post_filter' in d: self.post_filter._proxied = Q(d.pop('post_filter')) aggs = d.pop('aggs', d.pop('aggregations', {})) if aggs: self.aggs._params = { 'aggs': { name: A(value) for (name, value) in iteritems(aggs)} } if 'sort' in d: self._sort = d.pop('sort') if '_source' in d: self._source = d.pop('_source') if 'highlight' in d: high = d.pop('highlight').copy() self._highlight = high.pop('fields') self._highlight_opts = high if 'suggest' in d: self._suggest = d.pop('suggest') if 'text' in self._suggest: text = self._suggest.pop('text') for s in self._suggest.values(): s.setdefault('text', text) if 'script_fields' in d: self._script_fields = d.pop('script_fields') self._extra = d return self
python
def update_from_dict(self, d): """ Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by ``from_dict``. """ d = d.copy() if 'query' in d: self.query._proxied = Q(d.pop('query')) if 'post_filter' in d: self.post_filter._proxied = Q(d.pop('post_filter')) aggs = d.pop('aggs', d.pop('aggregations', {})) if aggs: self.aggs._params = { 'aggs': { name: A(value) for (name, value) in iteritems(aggs)} } if 'sort' in d: self._sort = d.pop('sort') if '_source' in d: self._source = d.pop('_source') if 'highlight' in d: high = d.pop('highlight').copy() self._highlight = high.pop('fields') self._highlight_opts = high if 'suggest' in d: self._suggest = d.pop('suggest') if 'text' in self._suggest: text = self._suggest.pop('text') for s in self._suggest.values(): s.setdefault('text', text) if 'script_fields' in d: self._script_fields = d.pop('script_fields') self._extra = d return self
[ "def", "update_from_dict", "(", "self", ",", "d", ")", ":", "d", "=", "d", ".", "copy", "(", ")", "if", "'query'", "in", "d", ":", "self", ".", "query", ".", "_proxied", "=", "Q", "(", "d", ".", "pop", "(", "'query'", ")", ")", "if", "'post_fil...
Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by ``from_dict``.
[ "Apply", "options", "from", "a", "serialized", "body", "to", "the", "current", "instance", ".", "Modifies", "the", "object", "in", "-", "place", ".", "Used", "mostly", "by", "from_dict", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L411-L445
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.script_fields
def script_fields(self, **kwargs): """ Define script fields to be calculated on hits. See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html for more details. Example:: s = Search() s = s.script_fields(times_two="doc['field'].value * 2") s = s.script_fields( times_three={ 'script': { 'inline': "doc['field'].value * params.n", 'params': {'n': 3} } } ) """ s = self._clone() for name in kwargs: if isinstance(kwargs[name], string_types): kwargs[name] = {'script': kwargs[name]} s._script_fields.update(kwargs) return s
python
def script_fields(self, **kwargs): """ Define script fields to be calculated on hits. See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html for more details. Example:: s = Search() s = s.script_fields(times_two="doc['field'].value * 2") s = s.script_fields( times_three={ 'script': { 'inline': "doc['field'].value * params.n", 'params': {'n': 3} } } ) """ s = self._clone() for name in kwargs: if isinstance(kwargs[name], string_types): kwargs[name] = {'script': kwargs[name]} s._script_fields.update(kwargs) return s
[ "def", "script_fields", "(", "self", ",", "*", "*", "kwargs", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "for", "name", "in", "kwargs", ":", "if", "isinstance", "(", "kwargs", "[", "name", "]", ",", "string_types", ")", ":", "kwargs", "["...
Define script fields to be calculated on hits. See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html for more details. Example:: s = Search() s = s.script_fields(times_two="doc['field'].value * 2") s = s.script_fields( times_three={ 'script': { 'inline': "doc['field'].value * params.n", 'params': {'n': 3} } } )
[ "Define", "script", "fields", "to", "be", "calculated", "on", "hits", ".", "See", "https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "search", "-", "request", "-",...
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L447-L472
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.source
def source(self, fields=None, **kwargs): """ Selectively control how the _source field is returned. :arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes If ``fields`` is None, the entire document will be returned for each hit. If fields is a dictionary with keys of 'include' and/or 'exclude' the fields will be either included or excluded appropriately. Calling this multiple times with the same named parameter will override the previous values with the new ones. Example:: s = Search() s = s.source(include=['obj1.*'], exclude=["*.description"]) s = Search() s = s.source(include=['obj1.*']).source(exclude=["*.description"]) """ s = self._clone() if fields and kwargs: raise ValueError("You cannot specify fields and kwargs at the same time.") if fields is not None: s._source = fields return s if kwargs and not isinstance(s._source, dict): s._source = {} for key, value in kwargs.items(): if value is None: try: del s._source[key] except KeyError: pass else: s._source[key] = value return s
python
def source(self, fields=None, **kwargs): """ Selectively control how the _source field is returned. :arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes If ``fields`` is None, the entire document will be returned for each hit. If fields is a dictionary with keys of 'include' and/or 'exclude' the fields will be either included or excluded appropriately. Calling this multiple times with the same named parameter will override the previous values with the new ones. Example:: s = Search() s = s.source(include=['obj1.*'], exclude=["*.description"]) s = Search() s = s.source(include=['obj1.*']).source(exclude=["*.description"]) """ s = self._clone() if fields and kwargs: raise ValueError("You cannot specify fields and kwargs at the same time.") if fields is not None: s._source = fields return s if kwargs and not isinstance(s._source, dict): s._source = {} for key, value in kwargs.items(): if value is None: try: del s._source[key] except KeyError: pass else: s._source[key] = value return s
[ "def", "source", "(", "self", ",", "fields", "=", "None", ",", "*", "*", "kwargs", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "if", "fields", "and", "kwargs", ":", "raise", "ValueError", "(", "\"You cannot specify fields and kwargs at the same time...
Selectively control how the _source field is returned. :arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes If ``fields`` is None, the entire document will be returned for each hit. If fields is a dictionary with keys of 'include' and/or 'exclude' the fields will be either included or excluded appropriately. Calling this multiple times with the same named parameter will override the previous values with the new ones. Example:: s = Search() s = s.source(include=['obj1.*'], exclude=["*.description"]) s = Search() s = s.source(include=['obj1.*']).source(exclude=["*.description"])
[ "Selectively", "control", "how", "the", "_source", "field", "is", "returned", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L474-L517
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.sort
def sort(self, *keys): """ Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are:: 'some.field' '-some.other.field' {'different.field': {'any': 'dict'}} so for example:: s = Search().sort( 'category', '-title', {"price" : {"order" : "asc", "mode" : "avg"}} ) will sort by ``category``, ``title`` (in descending order) and ``price`` in ascending order using the ``avg`` mode. The API returns a copy of the Search object and can thus be chained. """ s = self._clone() s._sort = [] for k in keys: if isinstance(k, string_types) and k.startswith('-'): if k[1:] == '_score': raise IllegalOperation('Sorting by `-_score` is not allowed.') k = {k[1:]: {"order": "desc"}} s._sort.append(k) return s
python
def sort(self, *keys): """ Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are:: 'some.field' '-some.other.field' {'different.field': {'any': 'dict'}} so for example:: s = Search().sort( 'category', '-title', {"price" : {"order" : "asc", "mode" : "avg"}} ) will sort by ``category``, ``title`` (in descending order) and ``price`` in ascending order using the ``avg`` mode. The API returns a copy of the Search object and can thus be chained. """ s = self._clone() s._sort = [] for k in keys: if isinstance(k, string_types) and k.startswith('-'): if k[1:] == '_score': raise IllegalOperation('Sorting by `-_score` is not allowed.') k = {k[1:]: {"order": "desc"}} s._sort.append(k) return s
[ "def", "sort", "(", "self", ",", "*", "keys", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "s", ".", "_sort", "=", "[", "]", "for", "k", "in", "keys", ":", "if", "isinstance", "(", "k", ",", "string_types", ")", "and", "k", ".", "star...
Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are:: 'some.field' '-some.other.field' {'different.field': {'any': 'dict'}} so for example:: s = Search().sort( 'category', '-title', {"price" : {"order" : "asc", "mode" : "avg"}} ) will sort by ``category``, ``title`` (in descending order) and ``price`` in ascending order using the ``avg`` mode. The API returns a copy of the Search object and can thus be chained.
[ "Add", "sorting", "information", "to", "the", "search", "request", ".", "If", "called", "without", "arguments", "it", "will", "remove", "all", "sort", "requirements", ".", "Otherwise", "it", "will", "replace", "them", ".", "Acceptable", "arguments", "are", "::...
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L519-L550
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.highlight_options
def highlight_options(self, **kwargs): """ Update the global highlighting options used for this request. For example:: s = Search() s = s.highlight_options(order='score') """ s = self._clone() s._highlight_opts.update(kwargs) return s
python
def highlight_options(self, **kwargs): """ Update the global highlighting options used for this request. For example:: s = Search() s = s.highlight_options(order='score') """ s = self._clone() s._highlight_opts.update(kwargs) return s
[ "def", "highlight_options", "(", "self", ",", "*", "*", "kwargs", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "s", ".", "_highlight_opts", ".", "update", "(", "kwargs", ")", "return", "s" ]
Update the global highlighting options used for this request. For example:: s = Search() s = s.highlight_options(order='score')
[ "Update", "the", "global", "highlighting", "options", "used", "for", "this", "request", ".", "For", "example", "::" ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L552-L562
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.highlight
def highlight(self, *fields, **kwargs): """ Request highlighting of some fields. All keyword arguments passed in will be used as parameters for all the fields in the ``fields`` parameter. Example:: Search().highlight('title', 'body', fragment_size=50) will produce the equivalent of:: { "highlight": { "fields": { "body": {"fragment_size": 50}, "title": {"fragment_size": 50} } } } If you want to have different options for different fields you can call ``highlight`` twice:: Search().highlight('title', fragment_size=50).highlight('body', fragment_size=100) which will produce:: { "highlight": { "fields": { "body": {"fragment_size": 100}, "title": {"fragment_size": 50} } } } """ s = self._clone() for f in fields: s._highlight[f] = kwargs return s
python
def highlight(self, *fields, **kwargs): """ Request highlighting of some fields. All keyword arguments passed in will be used as parameters for all the fields in the ``fields`` parameter. Example:: Search().highlight('title', 'body', fragment_size=50) will produce the equivalent of:: { "highlight": { "fields": { "body": {"fragment_size": 50}, "title": {"fragment_size": 50} } } } If you want to have different options for different fields you can call ``highlight`` twice:: Search().highlight('title', fragment_size=50).highlight('body', fragment_size=100) which will produce:: { "highlight": { "fields": { "body": {"fragment_size": 100}, "title": {"fragment_size": 50} } } } """ s = self._clone() for f in fields: s._highlight[f] = kwargs return s
[ "def", "highlight", "(", "self", ",", "*", "fields", ",", "*", "*", "kwargs", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "for", "f", "in", "fields", ":", "s", ".", "_highlight", "[", "f", "]", "=", "kwargs", "return", "s" ]
Request highlighting of some fields. All keyword arguments passed in will be used as parameters for all the fields in the ``fields`` parameter. Example:: Search().highlight('title', 'body', fragment_size=50) will produce the equivalent of:: { "highlight": { "fields": { "body": {"fragment_size": 50}, "title": {"fragment_size": 50} } } } If you want to have different options for different fields you can call ``highlight`` twice:: Search().highlight('title', fragment_size=50).highlight('body', fragment_size=100) which will produce:: { "highlight": { "fields": { "body": {"fragment_size": 100}, "title": {"fragment_size": 50} } } }
[ "Request", "highlighting", "of", "some", "fields", ".", "All", "keyword", "arguments", "passed", "in", "will", "be", "used", "as", "parameters", "for", "all", "the", "fields", "in", "the", "fields", "parameter", ".", "Example", "::" ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L564-L601
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.suggest
def suggest(self, name, text, **kwargs): """ Add a suggestions request to the search. :arg name: name of the suggestion :arg text: text to suggest on All keyword arguments will be added to the suggestions body. For example:: s = Search() s = s.suggest('suggestion-1', 'Elasticsearch', term={'field': 'body'}) """ s = self._clone() s._suggest[name] = {'text': text} s._suggest[name].update(kwargs) return s
python
def suggest(self, name, text, **kwargs): """ Add a suggestions request to the search. :arg name: name of the suggestion :arg text: text to suggest on All keyword arguments will be added to the suggestions body. For example:: s = Search() s = s.suggest('suggestion-1', 'Elasticsearch', term={'field': 'body'}) """ s = self._clone() s._suggest[name] = {'text': text} s._suggest[name].update(kwargs) return s
[ "def", "suggest", "(", "self", ",", "name", ",", "text", ",", "*", "*", "kwargs", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "s", ".", "_suggest", "[", "name", "]", "=", "{", "'text'", ":", "text", "}", "s", ".", "_suggest", "[", "n...
Add a suggestions request to the search. :arg name: name of the suggestion :arg text: text to suggest on All keyword arguments will be added to the suggestions body. For example:: s = Search() s = s.suggest('suggestion-1', 'Elasticsearch', term={'field': 'body'})
[ "Add", "a", "suggestions", "request", "to", "the", "search", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L603-L618
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.to_dict
def to_dict(self, count=False, **kwargs): """ Serialize the search into the dictionary that will be sent over as the request's body. :arg count: a flag to specify if we are interested in a body for count - no aggregations, no pagination bounds etc. All additional keyword arguments will be included into the dictionary. """ d = {} if self.query: d["query"] = self.query.to_dict() # count request doesn't care for sorting and other things if not count: if self.post_filter: d['post_filter'] = self.post_filter.to_dict() if self.aggs.aggs: d.update(self.aggs.to_dict()) if self._sort: d['sort'] = self._sort d.update(self._extra) if self._source not in (None, {}): d['_source'] = self._source if self._highlight: d['highlight'] = {'fields': self._highlight} d['highlight'].update(self._highlight_opts) if self._suggest: d['suggest'] = self._suggest if self._script_fields: d['script_fields'] = self._script_fields d.update(kwargs) return d
python
def to_dict(self, count=False, **kwargs): """ Serialize the search into the dictionary that will be sent over as the request's body. :arg count: a flag to specify if we are interested in a body for count - no aggregations, no pagination bounds etc. All additional keyword arguments will be included into the dictionary. """ d = {} if self.query: d["query"] = self.query.to_dict() # count request doesn't care for sorting and other things if not count: if self.post_filter: d['post_filter'] = self.post_filter.to_dict() if self.aggs.aggs: d.update(self.aggs.to_dict()) if self._sort: d['sort'] = self._sort d.update(self._extra) if self._source not in (None, {}): d['_source'] = self._source if self._highlight: d['highlight'] = {'fields': self._highlight} d['highlight'].update(self._highlight_opts) if self._suggest: d['suggest'] = self._suggest if self._script_fields: d['script_fields'] = self._script_fields d.update(kwargs) return d
[ "def", "to_dict", "(", "self", ",", "count", "=", "False", ",", "*", "*", "kwargs", ")", ":", "d", "=", "{", "}", "if", "self", ".", "query", ":", "d", "[", "\"query\"", "]", "=", "self", ".", "query", ".", "to_dict", "(", ")", "# count request d...
Serialize the search into the dictionary that will be sent over as the request's body. :arg count: a flag to specify if we are interested in a body for count - no aggregations, no pagination bounds etc. All additional keyword arguments will be included into the dictionary.
[ "Serialize", "the", "search", "into", "the", "dictionary", "that", "will", "be", "sent", "over", "as", "the", "request", "s", "body", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L620-L662
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.count
def count(self): """ Return the number of hits matching the query and filters. Note that only the actual number is returned. """ if hasattr(self, '_response'): return self._response.hits.total es = connections.get_connection(self._using) d = self.to_dict(count=True) # TODO: failed shards detection return es.count( index=self._index, body=d, **self._params )['count']
python
def count(self): """ Return the number of hits matching the query and filters. Note that only the actual number is returned. """ if hasattr(self, '_response'): return self._response.hits.total es = connections.get_connection(self._using) d = self.to_dict(count=True) # TODO: failed shards detection return es.count( index=self._index, body=d, **self._params )['count']
[ "def", "count", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_response'", ")", ":", "return", "self", ".", "_response", ".", "hits", ".", "total", "es", "=", "connections", ".", "get_connection", "(", "self", ".", "_using", ")", "d", "...
Return the number of hits matching the query and filters. Note that only the actual number is returned.
[ "Return", "the", "number", "of", "hits", "matching", "the", "query", "and", "filters", ".", "Note", "that", "only", "the", "actual", "number", "is", "returned", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L664-L680
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.execute
def execute(self, ignore_cache=False): """ Execute the search and return an instance of ``Response`` wrapping all the data. :arg ignore_cache: if set to ``True``, consecutive calls will hit ES, while cached result will be ignored. Defaults to `False` """ if ignore_cache or not hasattr(self, '_response'): es = connections.get_connection(self._using) self._response = self._response_class( self, es.search( index=self._index, body=self.to_dict(), **self._params ) ) return self._response
python
def execute(self, ignore_cache=False): """ Execute the search and return an instance of ``Response`` wrapping all the data. :arg ignore_cache: if set to ``True``, consecutive calls will hit ES, while cached result will be ignored. Defaults to `False` """ if ignore_cache or not hasattr(self, '_response'): es = connections.get_connection(self._using) self._response = self._response_class( self, es.search( index=self._index, body=self.to_dict(), **self._params ) ) return self._response
[ "def", "execute", "(", "self", ",", "ignore_cache", "=", "False", ")", ":", "if", "ignore_cache", "or", "not", "hasattr", "(", "self", ",", "'_response'", ")", ":", "es", "=", "connections", ".", "get_connection", "(", "self", ".", "_using", ")", "self",...
Execute the search and return an instance of ``Response`` wrapping all the data. :arg ignore_cache: if set to ``True``, consecutive calls will hit ES, while cached result will be ignored. Defaults to `False`
[ "Execute", "the", "search", "and", "return", "an", "instance", "of", "Response", "wrapping", "all", "the", "data", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L682-L701
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.scan
def scan(self): """ Turn the search into a scan search and return a generator that will iterate over all the documents matching the query. Use ``params`` method to specify any additional arguments you with to pass to the underlying ``scan`` helper from ``elasticsearch-py`` - https://elasticsearch-py.readthedocs.io/en/master/helpers.html#elasticsearch.helpers.scan """ es = connections.get_connection(self._using) for hit in scan( es, query=self.to_dict(), index=self._index, **self._params ): yield self._get_result(hit)
python
def scan(self): """ Turn the search into a scan search and return a generator that will iterate over all the documents matching the query. Use ``params`` method to specify any additional arguments you with to pass to the underlying ``scan`` helper from ``elasticsearch-py`` - https://elasticsearch-py.readthedocs.io/en/master/helpers.html#elasticsearch.helpers.scan """ es = connections.get_connection(self._using) for hit in scan( es, query=self.to_dict(), index=self._index, **self._params ): yield self._get_result(hit)
[ "def", "scan", "(", "self", ")", ":", "es", "=", "connections", ".", "get_connection", "(", "self", ".", "_using", ")", "for", "hit", "in", "scan", "(", "es", ",", "query", "=", "self", ".", "to_dict", "(", ")", ",", "index", "=", "self", ".", "_...
Turn the search into a scan search and return a generator that will iterate over all the documents matching the query. Use ``params`` method to specify any additional arguments you with to pass to the underlying ``scan`` helper from ``elasticsearch-py`` - https://elasticsearch-py.readthedocs.io/en/master/helpers.html#elasticsearch.helpers.scan
[ "Turn", "the", "search", "into", "a", "scan", "search", "and", "return", "a", "generator", "that", "will", "iterate", "over", "all", "the", "documents", "matching", "the", "query", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L703-L721
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
Search.delete
def delete(self): """ delete() executes the query by delegating to delete_by_query() """ es = connections.get_connection(self._using) return AttrDict( es.delete_by_query( index=self._index, body=self.to_dict(), **self._params ) )
python
def delete(self): """ delete() executes the query by delegating to delete_by_query() """ es = connections.get_connection(self._using) return AttrDict( es.delete_by_query( index=self._index, body=self.to_dict(), **self._params ) )
[ "def", "delete", "(", "self", ")", ":", "es", "=", "connections", ".", "get_connection", "(", "self", ".", "_using", ")", "return", "AttrDict", "(", "es", ".", "delete_by_query", "(", "index", "=", "self", ".", "_index", ",", "body", "=", "self", ".", ...
delete() executes the query by delegating to delete_by_query()
[ "delete", "()", "executes", "the", "query", "by", "delegating", "to", "delete_by_query", "()" ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L723-L736
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
MultiSearch.add
def add(self, search): """ Adds a new :class:`~elasticsearch_dsl.Search` object to the request:: ms = MultiSearch(index='my-index') ms = ms.add(Search(doc_type=Category).filter('term', category='python')) ms = ms.add(Search(doc_type=Blog)) """ ms = self._clone() ms._searches.append(search) return ms
python
def add(self, search): """ Adds a new :class:`~elasticsearch_dsl.Search` object to the request:: ms = MultiSearch(index='my-index') ms = ms.add(Search(doc_type=Category).filter('term', category='python')) ms = ms.add(Search(doc_type=Blog)) """ ms = self._clone() ms._searches.append(search) return ms
[ "def", "add", "(", "self", ",", "search", ")", ":", "ms", "=", "self", ".", "_clone", "(", ")", "ms", ".", "_searches", ".", "append", "(", "search", ")", "return", "ms" ]
Adds a new :class:`~elasticsearch_dsl.Search` object to the request:: ms = MultiSearch(index='my-index') ms = ms.add(Search(doc_type=Category).filter('term', category='python')) ms = ms.add(Search(doc_type=Blog))
[ "Adds", "a", "new", ":", "class", ":", "~elasticsearch_dsl", ".", "Search", "object", "to", "the", "request", "::" ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L759-L769
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
MultiSearch.execute
def execute(self, ignore_cache=False, raise_on_error=True): """ Execute the multi search request and return a list of search results. """ if ignore_cache or not hasattr(self, '_response'): es = connections.get_connection(self._using) responses = es.msearch( index=self._index, body=self.to_dict(), **self._params ) out = [] for s, r in zip(self._searches, responses['responses']): if r.get('error', False): if raise_on_error: raise TransportError('N/A', r['error']['type'], r['error']) r = None else: r = Response(s, r) out.append(r) self._response = out return self._response
python
def execute(self, ignore_cache=False, raise_on_error=True): """ Execute the multi search request and return a list of search results. """ if ignore_cache or not hasattr(self, '_response'): es = connections.get_connection(self._using) responses = es.msearch( index=self._index, body=self.to_dict(), **self._params ) out = [] for s, r in zip(self._searches, responses['responses']): if r.get('error', False): if raise_on_error: raise TransportError('N/A', r['error']['type'], r['error']) r = None else: r = Response(s, r) out.append(r) self._response = out return self._response
[ "def", "execute", "(", "self", ",", "ignore_cache", "=", "False", ",", "raise_on_error", "=", "True", ")", ":", "if", "ignore_cache", "or", "not", "hasattr", "(", "self", ",", "'_response'", ")", ":", "es", "=", "connections", ".", "get_connection", "(", ...
Execute the multi search request and return a list of search results.
[ "Execute", "the", "multi", "search", "request", "and", "return", "a", "list", "of", "search", "results", "." ]
874b52472fc47b601de0e5fa0e4300e21aff0085
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L784-L809
train
paramiko/paramiko
setup_helper.py
make_tarball
def make_tarball( base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, ): """Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip' and 'bzip2' the internal tarfile module will be used. For 'compress' the .tar will be created using tarfile, and then we will spawn 'compress' afterwards. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", ".bz2" or ".Z"). Return the output filename. """ # XXX GNU tar 1.13 has a nifty option to add a prefix directory. # It's pretty new, though, so we certainly can't require it -- # but it would be nice to take advantage of it to skip the # "create a tree of hardlinks" step! (Would also be nice to # detect GNU tar to use its 'z' option and save a step.) compress_ext = {"gzip": ".gz", "bzip2": ".bz2", "compress": ".Z"} # flags for compression program, each element of list will be an argument tarfile_compress_flag = {"gzip": "gz", "bzip2": "bz2"} compress_flags = {"compress": ["-f"]} if compress is not None and compress not in compress_ext.keys(): raise ValueError( "bad value for 'compress': must be None, 'gzip'," "'bzip2' or 'compress'" ) archive_name = base_name + ".tar" if compress and compress in tarfile_compress_flag: archive_name += compress_ext[compress] mode = "w:" + tarfile_compress_flag.get(compress, "") mkpath(os.path.dirname(archive_name), dry_run=dry_run) log.info("Creating tar file %s with mode %s" % (archive_name, mode)) uid = _get_uid(owner) gid = _get_gid(group) def _set_uid_gid(tarinfo): if gid is not None: tarinfo.gid = gid tarinfo.gname = group if uid is not None: tarinfo.uid = uid tarinfo.uname = owner return tarinfo if not dry_run: tar = tarfile.open(archive_name, mode=mode) # This recursively adds everything underneath base_dir try: try: # Support for the `filter' parameter was added in Python 2.7, # earlier versions will raise TypeError. tar.add(base_dir, filter=_set_uid_gid) except TypeError: tar.add(base_dir) finally: tar.close() if compress and compress not in tarfile_compress_flag: spawn( [compress] + compress_flags[compress] + [archive_name], dry_run=dry_run, ) return archive_name + compress_ext[compress] else: return archive_name
python
def make_tarball( base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, ): """Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip' and 'bzip2' the internal tarfile module will be used. For 'compress' the .tar will be created using tarfile, and then we will spawn 'compress' afterwards. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", ".bz2" or ".Z"). Return the output filename. """ # XXX GNU tar 1.13 has a nifty option to add a prefix directory. # It's pretty new, though, so we certainly can't require it -- # but it would be nice to take advantage of it to skip the # "create a tree of hardlinks" step! (Would also be nice to # detect GNU tar to use its 'z' option and save a step.) compress_ext = {"gzip": ".gz", "bzip2": ".bz2", "compress": ".Z"} # flags for compression program, each element of list will be an argument tarfile_compress_flag = {"gzip": "gz", "bzip2": "bz2"} compress_flags = {"compress": ["-f"]} if compress is not None and compress not in compress_ext.keys(): raise ValueError( "bad value for 'compress': must be None, 'gzip'," "'bzip2' or 'compress'" ) archive_name = base_name + ".tar" if compress and compress in tarfile_compress_flag: archive_name += compress_ext[compress] mode = "w:" + tarfile_compress_flag.get(compress, "") mkpath(os.path.dirname(archive_name), dry_run=dry_run) log.info("Creating tar file %s with mode %s" % (archive_name, mode)) uid = _get_uid(owner) gid = _get_gid(group) def _set_uid_gid(tarinfo): if gid is not None: tarinfo.gid = gid tarinfo.gname = group if uid is not None: tarinfo.uid = uid tarinfo.uname = owner return tarinfo if not dry_run: tar = tarfile.open(archive_name, mode=mode) # This recursively adds everything underneath base_dir try: try: # Support for the `filter' parameter was added in Python 2.7, # earlier versions will raise TypeError. tar.add(base_dir, filter=_set_uid_gid) except TypeError: tar.add(base_dir) finally: tar.close() if compress and compress not in tarfile_compress_flag: spawn( [compress] + compress_flags[compress] + [archive_name], dry_run=dry_run, ) return archive_name + compress_ext[compress] else: return archive_name
[ "def", "make_tarball", "(", "base_name", ",", "base_dir", ",", "compress", "=", "\"gzip\"", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "owner", "=", "None", ",", "group", "=", "None", ",", ")", ":", "# XXX GNU tar 1.13 has a nifty option to add...
Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip' and 'bzip2' the internal tarfile module will be used. For 'compress' the .tar will be created using tarfile, and then we will spawn 'compress' afterwards. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", ".bz2" or ".Z"). Return the output filename.
[ "Create", "a", "tar", "file", "from", "all", "the", "files", "under", "base_dir", ".", "This", "file", "may", "be", "compressed", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/setup_helper.py#L70-L153
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGroup1.start_kex
def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange. """ self._generate_x() if self.transport.server_mode: # compute f = g^x mod p, but don't send it yet self.f = pow(self.G, self.x, self.P) self.transport._expect_packet(MSG_KEXGSS_INIT) return # compute e = g^x mod p (where g=2), and send it self.e = pow(self.G, self.x, self.P) # Initialize GSS-API Key Exchange self.gss_host = self.transport.gss_host m = Message() m.add_byte(c_MSG_KEXGSS_INIT) m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host)) m.add_mpint(self.e) self.transport._send_message(m) self.transport._expect_packet( MSG_KEXGSS_HOSTKEY, MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR, )
python
def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange. """ self._generate_x() if self.transport.server_mode: # compute f = g^x mod p, but don't send it yet self.f = pow(self.G, self.x, self.P) self.transport._expect_packet(MSG_KEXGSS_INIT) return # compute e = g^x mod p (where g=2), and send it self.e = pow(self.G, self.x, self.P) # Initialize GSS-API Key Exchange self.gss_host = self.transport.gss_host m = Message() m.add_byte(c_MSG_KEXGSS_INIT) m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host)) m.add_mpint(self.e) self.transport._send_message(m) self.transport._expect_packet( MSG_KEXGSS_HOSTKEY, MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR, )
[ "def", "start_kex", "(", "self", ")", ":", "self", ".", "_generate_x", "(", ")", "if", "self", ".", "transport", ".", "server_mode", ":", "# compute f = g^x mod p, but don't send it yet", "self", ".", "f", "=", "pow", "(", "self", ".", "G", ",", "self", "....
Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange.
[ "Start", "the", "GSS", "-", "API", "/", "SSPI", "Authenticated", "Diffie", "-", "Hellman", "Key", "Exchange", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L91-L115
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGroup1.parse_next
def parse_next(self, ptype, m): """ Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content """ if self.transport.server_mode and (ptype == MSG_KEXGSS_INIT): return self._parse_kexgss_init(m) elif not self.transport.server_mode and (ptype == MSG_KEXGSS_HOSTKEY): return self._parse_kexgss_hostkey(m) elif self.transport.server_mode and (ptype == MSG_KEXGSS_CONTINUE): return self._parse_kexgss_continue(m) elif not self.transport.server_mode and (ptype == MSG_KEXGSS_COMPLETE): return self._parse_kexgss_complete(m) elif ptype == MSG_KEXGSS_ERROR: return self._parse_kexgss_error(m) msg = "GSS KexGroup1 asked to handle packet type {:d}" raise SSHException(msg.format(ptype))
python
def parse_next(self, ptype, m): """ Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content """ if self.transport.server_mode and (ptype == MSG_KEXGSS_INIT): return self._parse_kexgss_init(m) elif not self.transport.server_mode and (ptype == MSG_KEXGSS_HOSTKEY): return self._parse_kexgss_hostkey(m) elif self.transport.server_mode and (ptype == MSG_KEXGSS_CONTINUE): return self._parse_kexgss_continue(m) elif not self.transport.server_mode and (ptype == MSG_KEXGSS_COMPLETE): return self._parse_kexgss_complete(m) elif ptype == MSG_KEXGSS_ERROR: return self._parse_kexgss_error(m) msg = "GSS KexGroup1 asked to handle packet type {:d}" raise SSHException(msg.format(ptype))
[ "def", "parse_next", "(", "self", ",", "ptype", ",", "m", ")", ":", "if", "self", ".", "transport", ".", "server_mode", "and", "(", "ptype", "==", "MSG_KEXGSS_INIT", ")", ":", "return", "self", ".", "_parse_kexgss_init", "(", "m", ")", "elif", "not", "...
Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content
[ "Parse", "the", "next", "packet", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L117-L135
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGroup1._parse_kexgss_hostkey
def _parse_kexgss_hostkey(self, m): """ Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message """ # client mode host_key = m.get_string() self.transport.host_key = host_key sig = m.get_string() self.transport._verify_key(host_key, sig) self.transport._expect_packet(MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE)
python
def _parse_kexgss_hostkey(self, m): """ Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message """ # client mode host_key = m.get_string() self.transport.host_key = host_key sig = m.get_string() self.transport._verify_key(host_key, sig) self.transport._expect_packet(MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE)
[ "def", "_parse_kexgss_hostkey", "(", "self", ",", "m", ")", ":", "# client mode", "host_key", "=", "m", ".", "get_string", "(", ")", "self", ".", "transport", ".", "host_key", "=", "host_key", "sig", "=", "m", ".", "get_string", "(", ")", "self", ".", ...
Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message
[ "Parse", "the", "SSH2_MSG_KEXGSS_HOSTKEY", "message", "(", "client", "mode", ")", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L155-L166
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGroup1._parse_kexgss_continue
def _parse_kexgss_continue(self, m): """ Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE message """ if not self.transport.server_mode: srv_token = m.get_string() m = Message() m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string( self.kexgss.ssh_init_sec_context( target=self.gss_host, recv_token=srv_token ) ) self.transport.send_message(m) self.transport._expect_packet( MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR ) else: pass
python
def _parse_kexgss_continue(self, m): """ Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE message """ if not self.transport.server_mode: srv_token = m.get_string() m = Message() m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string( self.kexgss.ssh_init_sec_context( target=self.gss_host, recv_token=srv_token ) ) self.transport.send_message(m) self.transport._expect_packet( MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR ) else: pass
[ "def", "_parse_kexgss_continue", "(", "self", ",", "m", ")", ":", "if", "not", "self", ".", "transport", ".", "server_mode", ":", "srv_token", "=", "m", ".", "get_string", "(", ")", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "c_MSG_KEXGS...
Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE message
[ "Parse", "the", "SSH2_MSG_KEXGSS_CONTINUE", "message", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L168-L189
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGroup1._parse_kexgss_complete
def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message """ # client mode if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f = m.get_mpint() if (self.f < 1) or (self.f > self.P - 1): raise SSHException('Server kex "f" is out of range') mic_token = m.get_string() # This must be TRUE, if there is a GSS-API token in this message. bool = m.get_boolean() srv_token = None if bool: srv_token = m.get_string() K = pow(self.f, self.x, self.P) # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add( self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init, ) hm.add_string(self.transport.host_key.__str__()) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(str(hm)).digest() self.transport._set_K_H(K, H) if srv_token is not None: self.kexgss.ssh_init_sec_context( target=self.gss_host, recv_token=srv_token ) self.kexgss.ssh_check_mic(mic_token, H) else: self.kexgss.ssh_check_mic(mic_token, H) self.transport.gss_kex_used = True self.transport._activate_outbound()
python
def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message """ # client mode if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f = m.get_mpint() if (self.f < 1) or (self.f > self.P - 1): raise SSHException('Server kex "f" is out of range') mic_token = m.get_string() # This must be TRUE, if there is a GSS-API token in this message. bool = m.get_boolean() srv_token = None if bool: srv_token = m.get_string() K = pow(self.f, self.x, self.P) # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add( self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init, ) hm.add_string(self.transport.host_key.__str__()) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(str(hm)).digest() self.transport._set_K_H(K, H) if srv_token is not None: self.kexgss.ssh_init_sec_context( target=self.gss_host, recv_token=srv_token ) self.kexgss.ssh_check_mic(mic_token, H) else: self.kexgss.ssh_check_mic(mic_token, H) self.transport.gss_kex_used = True self.transport._activate_outbound()
[ "def", "_parse_kexgss_complete", "(", "self", ",", "m", ")", ":", "# client mode", "if", "self", ".", "transport", ".", "host_key", "is", "None", ":", "self", ".", "transport", ".", "host_key", "=", "NullHostKey", "(", ")", "self", ".", "f", "=", "m", ...
Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message
[ "Parse", "the", "SSH2_MSG_KEXGSS_COMPLETE", "message", "(", "client", "mode", ")", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L191-L234
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGroup1._parse_kexgss_init
def _parse_kexgss_init(self, m): """ Parse the SSH2_MSG_KEXGSS_INIT message (server mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_INIT message """ # server mode client_token = m.get_string() self.e = m.get_mpint() if (self.e < 1) or (self.e > self.P - 1): raise SSHException('Client kex "e" is out of range') K = pow(self.e, self.x, self.P) self.transport.host_key = NullHostKey() key = self.transport.host_key.__str__() # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add( self.transport.remote_version, self.transport.local_version, self.transport.remote_kex_init, self.transport.local_kex_init, ) hm.add_string(key) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(hm.asbytes()).digest() self.transport._set_K_H(K, H) srv_token = self.kexgss.ssh_accept_sec_context( self.gss_host, client_token ) m = Message() if self.kexgss._gss_srv_ctxt_status: mic_token = self.kexgss.ssh_get_mic( self.transport.session_id, gss_kex=True ) m.add_byte(c_MSG_KEXGSS_COMPLETE) m.add_mpint(self.f) m.add_string(mic_token) if srv_token is not None: m.add_boolean(True) m.add_string(srv_token) else: m.add_boolean(False) self.transport._send_message(m) self.transport.gss_kex_used = True self.transport._activate_outbound() else: m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string(srv_token) self.transport._send_message(m) self.transport._expect_packet( MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR )
python
def _parse_kexgss_init(self, m): """ Parse the SSH2_MSG_KEXGSS_INIT message (server mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_INIT message """ # server mode client_token = m.get_string() self.e = m.get_mpint() if (self.e < 1) or (self.e > self.P - 1): raise SSHException('Client kex "e" is out of range') K = pow(self.e, self.x, self.P) self.transport.host_key = NullHostKey() key = self.transport.host_key.__str__() # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add( self.transport.remote_version, self.transport.local_version, self.transport.remote_kex_init, self.transport.local_kex_init, ) hm.add_string(key) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(hm.asbytes()).digest() self.transport._set_K_H(K, H) srv_token = self.kexgss.ssh_accept_sec_context( self.gss_host, client_token ) m = Message() if self.kexgss._gss_srv_ctxt_status: mic_token = self.kexgss.ssh_get_mic( self.transport.session_id, gss_kex=True ) m.add_byte(c_MSG_KEXGSS_COMPLETE) m.add_mpint(self.f) m.add_string(mic_token) if srv_token is not None: m.add_boolean(True) m.add_string(srv_token) else: m.add_boolean(False) self.transport._send_message(m) self.transport.gss_kex_used = True self.transport._activate_outbound() else: m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string(srv_token) self.transport._send_message(m) self.transport._expect_packet( MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR )
[ "def", "_parse_kexgss_init", "(", "self", ",", "m", ")", ":", "# server mode", "client_token", "=", "m", ".", "get_string", "(", ")", "self", ".", "e", "=", "m", ".", "get_mpint", "(", ")", "if", "(", "self", ".", "e", "<", "1", ")", "or", "(", "...
Parse the SSH2_MSG_KEXGSS_INIT message (server mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_INIT message
[ "Parse", "the", "SSH2_MSG_KEXGSS_INIT", "message", "(", "server", "mode", ")", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L236-L290
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGex.start_kex
def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange """ if self.transport.server_mode: self.transport._expect_packet(MSG_KEXGSS_GROUPREQ) return # request a bit range: we accept (min_bits) to (max_bits), but prefer # (preferred_bits). according to the spec, we shouldn't pull the # minimum up above 1024. self.gss_host = self.transport.gss_host m = Message() m.add_byte(c_MSG_KEXGSS_GROUPREQ) m.add_int(self.min_bits) m.add_int(self.preferred_bits) m.add_int(self.max_bits) self.transport._send_message(m) self.transport._expect_packet(MSG_KEXGSS_GROUP)
python
def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange """ if self.transport.server_mode: self.transport._expect_packet(MSG_KEXGSS_GROUPREQ) return # request a bit range: we accept (min_bits) to (max_bits), but prefer # (preferred_bits). according to the spec, we shouldn't pull the # minimum up above 1024. self.gss_host = self.transport.gss_host m = Message() m.add_byte(c_MSG_KEXGSS_GROUPREQ) m.add_int(self.min_bits) m.add_int(self.preferred_bits) m.add_int(self.max_bits) self.transport._send_message(m) self.transport._expect_packet(MSG_KEXGSS_GROUP)
[ "def", "start_kex", "(", "self", ")", ":", "if", "self", ".", "transport", ".", "server_mode", ":", "self", ".", "transport", ".", "_expect_packet", "(", "MSG_KEXGSS_GROUPREQ", ")", "return", "# request a bit range: we accept (min_bits) to (max_bits), but prefer", "# (p...
Start the GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange
[ "Start", "the", "GSS", "-", "API", "/", "SSPI", "Authenticated", "Diffie", "-", "Hellman", "Group", "Exchange" ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L353-L370
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGex.parse_next
def parse_next(self, ptype, m): """ Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content """ if ptype == MSG_KEXGSS_GROUPREQ: return self._parse_kexgss_groupreq(m) elif ptype == MSG_KEXGSS_GROUP: return self._parse_kexgss_group(m) elif ptype == MSG_KEXGSS_INIT: return self._parse_kexgss_gex_init(m) elif ptype == MSG_KEXGSS_HOSTKEY: return self._parse_kexgss_hostkey(m) elif ptype == MSG_KEXGSS_CONTINUE: return self._parse_kexgss_continue(m) elif ptype == MSG_KEXGSS_COMPLETE: return self._parse_kexgss_complete(m) elif ptype == MSG_KEXGSS_ERROR: return self._parse_kexgss_error(m) msg = "KexGex asked to handle packet type {:d}" raise SSHException(msg.format(ptype))
python
def parse_next(self, ptype, m): """ Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content """ if ptype == MSG_KEXGSS_GROUPREQ: return self._parse_kexgss_groupreq(m) elif ptype == MSG_KEXGSS_GROUP: return self._parse_kexgss_group(m) elif ptype == MSG_KEXGSS_INIT: return self._parse_kexgss_gex_init(m) elif ptype == MSG_KEXGSS_HOSTKEY: return self._parse_kexgss_hostkey(m) elif ptype == MSG_KEXGSS_CONTINUE: return self._parse_kexgss_continue(m) elif ptype == MSG_KEXGSS_COMPLETE: return self._parse_kexgss_complete(m) elif ptype == MSG_KEXGSS_ERROR: return self._parse_kexgss_error(m) msg = "KexGex asked to handle packet type {:d}" raise SSHException(msg.format(ptype))
[ "def", "parse_next", "(", "self", ",", "ptype", ",", "m", ")", ":", "if", "ptype", "==", "MSG_KEXGSS_GROUPREQ", ":", "return", "self", ".", "_parse_kexgss_groupreq", "(", "m", ")", "elif", "ptype", "==", "MSG_KEXGSS_GROUP", ":", "return", "self", ".", "_pa...
Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content
[ "Parse", "the", "next", "packet", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L372-L394
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGex._parse_kexgss_group
def _parse_kexgss_group(self, m): """ Parse the SSH2_MSG_KEXGSS_GROUP message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message """ self.p = m.get_mpint() self.g = m.get_mpint() # reject if p's bit length < 1024 or > 8192 bitlen = util.bit_length(self.p) if (bitlen < 1024) or (bitlen > 8192): raise SSHException( "Server-generated gex p (don't ask) is out of range " "({} bits)".format(bitlen) ) self.transport._log( DEBUG, "Got server p ({} bits)".format(bitlen) ) # noqa self._generate_x() # now compute e = g^x mod p self.e = pow(self.g, self.x, self.p) m = Message() m.add_byte(c_MSG_KEXGSS_INIT) m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host)) m.add_mpint(self.e) self.transport._send_message(m) self.transport._expect_packet( MSG_KEXGSS_HOSTKEY, MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR, )
python
def _parse_kexgss_group(self, m): """ Parse the SSH2_MSG_KEXGSS_GROUP message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message """ self.p = m.get_mpint() self.g = m.get_mpint() # reject if p's bit length < 1024 or > 8192 bitlen = util.bit_length(self.p) if (bitlen < 1024) or (bitlen > 8192): raise SSHException( "Server-generated gex p (don't ask) is out of range " "({} bits)".format(bitlen) ) self.transport._log( DEBUG, "Got server p ({} bits)".format(bitlen) ) # noqa self._generate_x() # now compute e = g^x mod p self.e = pow(self.g, self.x, self.p) m = Message() m.add_byte(c_MSG_KEXGSS_INIT) m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host)) m.add_mpint(self.e) self.transport._send_message(m) self.transport._expect_packet( MSG_KEXGSS_HOSTKEY, MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR, )
[ "def", "_parse_kexgss_group", "(", "self", ",", "m", ")", ":", "self", ".", "p", "=", "m", ".", "get_mpint", "(", ")", "self", ".", "g", "=", "m", ".", "get_mpint", "(", ")", "# reject if p's bit length < 1024 or > 8192", "bitlen", "=", "util", ".", "bit...
Parse the SSH2_MSG_KEXGSS_GROUP message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message
[ "Parse", "the", "SSH2_MSG_KEXGSS_GROUP", "message", "(", "client", "mode", ")", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L460-L491
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGex._parse_kexgss_complete
def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message """ if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f = m.get_mpint() mic_token = m.get_string() # This must be TRUE, if there is a GSS-API token in this message. bool = m.get_boolean() srv_token = None if bool: srv_token = m.get_string() if (self.f < 1) or (self.f > self.p - 1): raise SSHException('Server kex "f" is out of range') K = pow(self.f, self.x, self.p) # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K) # noqa hm = Message() hm.add( self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init, self.transport.host_key.__str__(), ) if not self.old_style: hm.add_int(self.min_bits) hm.add_int(self.preferred_bits) if not self.old_style: hm.add_int(self.max_bits) hm.add_mpint(self.p) hm.add_mpint(self.g) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(hm.asbytes()).digest() self.transport._set_K_H(K, H) if srv_token is not None: self.kexgss.ssh_init_sec_context( target=self.gss_host, recv_token=srv_token ) self.kexgss.ssh_check_mic(mic_token, H) else: self.kexgss.ssh_check_mic(mic_token, H) self.transport.gss_kex_used = True self.transport._activate_outbound()
python
def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message """ if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f = m.get_mpint() mic_token = m.get_string() # This must be TRUE, if there is a GSS-API token in this message. bool = m.get_boolean() srv_token = None if bool: srv_token = m.get_string() if (self.f < 1) or (self.f > self.p - 1): raise SSHException('Server kex "f" is out of range') K = pow(self.f, self.x, self.p) # okay, build up the hash H of # (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K) # noqa hm = Message() hm.add( self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init, self.transport.host_key.__str__(), ) if not self.old_style: hm.add_int(self.min_bits) hm.add_int(self.preferred_bits) if not self.old_style: hm.add_int(self.max_bits) hm.add_mpint(self.p) hm.add_mpint(self.g) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) H = sha1(hm.asbytes()).digest() self.transport._set_K_H(K, H) if srv_token is not None: self.kexgss.ssh_init_sec_context( target=self.gss_host, recv_token=srv_token ) self.kexgss.ssh_check_mic(mic_token, H) else: self.kexgss.ssh_check_mic(mic_token, H) self.transport.gss_kex_used = True self.transport._activate_outbound()
[ "def", "_parse_kexgss_complete", "(", "self", ",", "m", ")", ":", "if", "self", ".", "transport", ".", "host_key", "is", "None", ":", "self", ".", "transport", ".", "host_key", "=", "NullHostKey", "(", ")", "self", ".", "f", "=", "m", ".", "get_mpint",...
Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message
[ "Parse", "the", "SSH2_MSG_KEXGSS_COMPLETE", "message", "(", "client", "mode", ")", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L590-L638
train
paramiko/paramiko
paramiko/kex_gss.py
KexGSSGex._parse_kexgss_error
def _parse_kexgss_error(self, m): """ Parse the SSH2_MSG_KEXGSS_ERROR message (client mode). The server may send a GSS-API error message. if it does, we display the error by throwing an exception (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_ERROR message :raise SSHException: Contains GSS-API major and minor status as well as the error message and the language tag of the message """ maj_status = m.get_int() min_status = m.get_int() err_msg = m.get_string() m.get_string() # we don't care about the language (lang_tag)! raise SSHException( """GSS-API Error: Major Status: {} Minor Status: {} Error Message: {} """.format( maj_status, min_status, err_msg ) )
python
def _parse_kexgss_error(self, m): """ Parse the SSH2_MSG_KEXGSS_ERROR message (client mode). The server may send a GSS-API error message. if it does, we display the error by throwing an exception (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_ERROR message :raise SSHException: Contains GSS-API major and minor status as well as the error message and the language tag of the message """ maj_status = m.get_int() min_status = m.get_int() err_msg = m.get_string() m.get_string() # we don't care about the language (lang_tag)! raise SSHException( """GSS-API Error: Major Status: {} Minor Status: {} Error Message: {} """.format( maj_status, min_status, err_msg ) )
[ "def", "_parse_kexgss_error", "(", "self", ",", "m", ")", ":", "maj_status", "=", "m", ".", "get_int", "(", ")", "min_status", "=", "m", ".", "get_int", "(", ")", "err_msg", "=", "m", ".", "get_string", "(", ")", "m", ".", "get_string", "(", ")", "...
Parse the SSH2_MSG_KEXGSS_ERROR message (client mode). The server may send a GSS-API error message. if it does, we display the error by throwing an exception (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_ERROR message :raise SSHException: Contains GSS-API major and minor status as well as the error message and the language tag of the message
[ "Parse", "the", "SSH2_MSG_KEXGSS_ERROR", "message", "(", "client", "mode", ")", ".", "The", "server", "may", "send", "a", "GSS", "-", "API", "error", "message", ".", "if", "it", "does", "we", "display", "the", "error", "by", "throwing", "an", "exception", ...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L640-L663
train
paramiko/paramiko
paramiko/sftp_attr.py
SFTPAttributes.from_stat
def from_stat(cls, obj, filename=None): """ Create an `.SFTPAttributes` object from an existing ``stat`` object (an object returned by `os.stat`). :param object obj: an object returned by `os.stat` (or equivalent). :param str filename: the filename associated with this file. :return: new `.SFTPAttributes` object with the same attribute fields. """ attr = cls() attr.st_size = obj.st_size attr.st_uid = obj.st_uid attr.st_gid = obj.st_gid attr.st_mode = obj.st_mode attr.st_atime = obj.st_atime attr.st_mtime = obj.st_mtime if filename is not None: attr.filename = filename return attr
python
def from_stat(cls, obj, filename=None): """ Create an `.SFTPAttributes` object from an existing ``stat`` object (an object returned by `os.stat`). :param object obj: an object returned by `os.stat` (or equivalent). :param str filename: the filename associated with this file. :return: new `.SFTPAttributes` object with the same attribute fields. """ attr = cls() attr.st_size = obj.st_size attr.st_uid = obj.st_uid attr.st_gid = obj.st_gid attr.st_mode = obj.st_mode attr.st_atime = obj.st_atime attr.st_mtime = obj.st_mtime if filename is not None: attr.filename = filename return attr
[ "def", "from_stat", "(", "cls", ",", "obj", ",", "filename", "=", "None", ")", ":", "attr", "=", "cls", "(", ")", "attr", ".", "st_size", "=", "obj", ".", "st_size", "attr", ".", "st_uid", "=", "obj", ".", "st_uid", "attr", ".", "st_gid", "=", "o...
Create an `.SFTPAttributes` object from an existing ``stat`` object (an object returned by `os.stat`). :param object obj: an object returned by `os.stat` (or equivalent). :param str filename: the filename associated with this file. :return: new `.SFTPAttributes` object with the same attribute fields.
[ "Create", "an", ".", "SFTPAttributes", "object", "from", "an", "existing", "stat", "object", "(", "an", "object", "returned", "by", "os", ".", "stat", ")", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_attr.py#L64-L82
train
paramiko/paramiko
paramiko/rsakey.py
RSAKey.generate
def generate(bits, progress_func=None): """ Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param progress_func: Unused :return: new `.RSAKey` private key """ key = rsa.generate_private_key( public_exponent=65537, key_size=bits, backend=default_backend() ) return RSAKey(key=key)
python
def generate(bits, progress_func=None): """ Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param progress_func: Unused :return: new `.RSAKey` private key """ key = rsa.generate_private_key( public_exponent=65537, key_size=bits, backend=default_backend() ) return RSAKey(key=key)
[ "def", "generate", "(", "bits", ",", "progress_func", "=", "None", ")", ":", "key", "=", "rsa", ".", "generate_private_key", "(", "public_exponent", "=", "65537", ",", "key_size", "=", "bits", ",", "backend", "=", "default_backend", "(", ")", ")", "return"...
Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param progress_func: Unused :return: new `.RSAKey` private key
[ "Generate", "a", "new", "private", "RSA", "key", ".", "This", "factory", "function", "can", "be", "used", "to", "generate", "a", "new", "host", "key", "or", "authentication", "key", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/rsakey.py#L158-L170
train
paramiko/paramiko
paramiko/sftp_file.py
SFTPFile._data_in_prefetch_buffers
def _data_in_prefetch_buffers(self, offset): """ if a block of data is present in the prefetch buffers, at the given offset, return the offset of the relevant prefetch buffer. otherwise, return None. this guarantees nothing about the number of bytes collected in the prefetch buffer so far. """ k = [i for i in self._prefetch_data.keys() if i <= offset] if len(k) == 0: return None index = max(k) buf_offset = offset - index if buf_offset >= len(self._prefetch_data[index]): # it's not here return None return index
python
def _data_in_prefetch_buffers(self, offset): """ if a block of data is present in the prefetch buffers, at the given offset, return the offset of the relevant prefetch buffer. otherwise, return None. this guarantees nothing about the number of bytes collected in the prefetch buffer so far. """ k = [i for i in self._prefetch_data.keys() if i <= offset] if len(k) == 0: return None index = max(k) buf_offset = offset - index if buf_offset >= len(self._prefetch_data[index]): # it's not here return None return index
[ "def", "_data_in_prefetch_buffers", "(", "self", ",", "offset", ")", ":", "k", "=", "[", "i", "for", "i", "in", "self", ".", "_prefetch_data", ".", "keys", "(", ")", "if", "i", "<=", "offset", "]", "if", "len", "(", "k", ")", "==", "0", ":", "ret...
if a block of data is present in the prefetch buffers, at the given offset, return the offset of the relevant prefetch buffer. otherwise, return None. this guarantees nothing about the number of bytes collected in the prefetch buffer so far.
[ "if", "a", "block", "of", "data", "is", "present", "in", "the", "prefetch", "buffers", "at", "the", "given", "offset", "return", "the", "offset", "of", "the", "relevant", "prefetch", "buffer", ".", "otherwise", "return", "None", ".", "this", "guarantees", ...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L132-L147
train
paramiko/paramiko
paramiko/sftp_file.py
SFTPFile.seek
def seek(self, offset, whence=0): """ Set the file's current position. See `file.seek` for details. """ self.flush() if whence == self.SEEK_SET: self._realpos = self._pos = offset elif whence == self.SEEK_CUR: self._pos += offset self._realpos = self._pos else: self._realpos = self._pos = self._get_size() + offset self._rbuffer = bytes()
python
def seek(self, offset, whence=0): """ Set the file's current position. See `file.seek` for details. """ self.flush() if whence == self.SEEK_SET: self._realpos = self._pos = offset elif whence == self.SEEK_CUR: self._pos += offset self._realpos = self._pos else: self._realpos = self._pos = self._get_size() + offset self._rbuffer = bytes()
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "self", ".", "flush", "(", ")", "if", "whence", "==", "self", ".", "SEEK_SET", ":", "self", ".", "_realpos", "=", "self", ".", "_pos", "=", "offset", "elif", "whence", ...
Set the file's current position. See `file.seek` for details.
[ "Set", "the", "file", "s", "current", "position", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L258-L272
train
paramiko/paramiko
paramiko/sftp_file.py
SFTPFile.stat
def stat(self): """ Retrieve information about this file from the remote system. This is exactly like `.SFTPClient.stat`, except that it operates on an already-open file. :returns: an `.SFTPAttributes` object containing attributes about this file. """ t, msg = self.sftp._request(CMD_FSTAT, self.handle) if t != CMD_ATTRS: raise SFTPError("Expected attributes") return SFTPAttributes._from_msg(msg)
python
def stat(self): """ Retrieve information about this file from the remote system. This is exactly like `.SFTPClient.stat`, except that it operates on an already-open file. :returns: an `.SFTPAttributes` object containing attributes about this file. """ t, msg = self.sftp._request(CMD_FSTAT, self.handle) if t != CMD_ATTRS: raise SFTPError("Expected attributes") return SFTPAttributes._from_msg(msg)
[ "def", "stat", "(", "self", ")", ":", "t", ",", "msg", "=", "self", ".", "sftp", ".", "_request", "(", "CMD_FSTAT", ",", "self", ".", "handle", ")", "if", "t", "!=", "CMD_ATTRS", ":", "raise", "SFTPError", "(", "\"Expected attributes\"", ")", "return",...
Retrieve information about this file from the remote system. This is exactly like `.SFTPClient.stat`, except that it operates on an already-open file. :returns: an `.SFTPAttributes` object containing attributes about this file.
[ "Retrieve", "information", "about", "this", "file", "from", "the", "remote", "system", ".", "This", "is", "exactly", "like", ".", "SFTPClient", ".", "stat", "except", "that", "it", "operates", "on", "an", "already", "-", "open", "file", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L274-L286
train
paramiko/paramiko
paramiko/sftp_file.py
SFTPFile.truncate
def truncate(self, size): """ Change the size of this file. This usually extends or shrinks the size of the file, just like the ``truncate()`` method on Python file objects. :param size: the new size of the file """ self.sftp._log( DEBUG, "truncate({}, {!r})".format(hexlify(self.handle), size) ) attr = SFTPAttributes() attr.st_size = size self.sftp._request(CMD_FSETSTAT, self.handle, attr)
python
def truncate(self, size): """ Change the size of this file. This usually extends or shrinks the size of the file, just like the ``truncate()`` method on Python file objects. :param size: the new size of the file """ self.sftp._log( DEBUG, "truncate({}, {!r})".format(hexlify(self.handle), size) ) attr = SFTPAttributes() attr.st_size = size self.sftp._request(CMD_FSETSTAT, self.handle, attr)
[ "def", "truncate", "(", "self", ",", "size", ")", ":", "self", ".", "sftp", ".", "_log", "(", "DEBUG", ",", "\"truncate({}, {!r})\"", ".", "format", "(", "hexlify", "(", "self", ".", "handle", ")", ",", "size", ")", ")", "attr", "=", "SFTPAttributes", ...
Change the size of this file. This usually extends or shrinks the size of the file, just like the ``truncate()`` method on Python file objects. :param size: the new size of the file
[ "Change", "the", "size", "of", "this", "file", ".", "This", "usually", "extends", "or", "shrinks", "the", "size", "of", "the", "file", "just", "like", "the", "truncate", "()", "method", "on", "Python", "file", "objects", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L343-L356
train
paramiko/paramiko
paramiko/sftp_file.py
SFTPFile.check
def check(self, hash_algorithm, offset=0, length=0, block_size=0): """ Ask the server for a hash of a section of this file. This can be used to verify a successful upload or download, or for various rsync-like operations. The file is hashed from ``offset``, for ``length`` bytes. If ``length`` is 0, the remainder of the file is hashed. Thus, if both ``offset`` and ``length`` are zero, the entire file is hashed. Normally, ``block_size`` will be 0 (the default), and this method will return a byte string representing the requested hash (for example, a string of length 16 for MD5, or 20 for SHA-1). If a non-zero ``block_size`` is given, each chunk of the file (from ``offset`` to ``offset + length``) of ``block_size`` bytes is computed as a separate hash. The hash results are all concatenated and returned as a single string. For example, ``check('sha1', 0, 1024, 512)`` will return a string of length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes of the file, and the last 20 bytes will be the SHA-1 of the next 512 bytes. :param str hash_algorithm: the name of the hash algorithm to use (normally ``"sha1"`` or ``"md5"``) :param offset: offset into the file to begin hashing (0 means to start from the beginning) :param length: number of bytes to hash (0 means continue to the end of the file) :param int block_size: number of bytes to hash per result (must not be less than 256; 0 means to compute only one hash of the entire segment) :return: `str` of bytes representing the hash of each block, concatenated together :raises: ``IOError`` -- if the server doesn't support the "check-file" extension, or possibly doesn't support the hash algorithm requested .. note:: Many (most?) servers don't support this extension yet. .. versionadded:: 1.4 """ t, msg = self.sftp._request( CMD_EXTENDED, "check-file", self.handle, hash_algorithm, long(offset), long(length), block_size, ) msg.get_text() # ext msg.get_text() # alg data = msg.get_remainder() return data
python
def check(self, hash_algorithm, offset=0, length=0, block_size=0): """ Ask the server for a hash of a section of this file. This can be used to verify a successful upload or download, or for various rsync-like operations. The file is hashed from ``offset``, for ``length`` bytes. If ``length`` is 0, the remainder of the file is hashed. Thus, if both ``offset`` and ``length`` are zero, the entire file is hashed. Normally, ``block_size`` will be 0 (the default), and this method will return a byte string representing the requested hash (for example, a string of length 16 for MD5, or 20 for SHA-1). If a non-zero ``block_size`` is given, each chunk of the file (from ``offset`` to ``offset + length``) of ``block_size`` bytes is computed as a separate hash. The hash results are all concatenated and returned as a single string. For example, ``check('sha1', 0, 1024, 512)`` will return a string of length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes of the file, and the last 20 bytes will be the SHA-1 of the next 512 bytes. :param str hash_algorithm: the name of the hash algorithm to use (normally ``"sha1"`` or ``"md5"``) :param offset: offset into the file to begin hashing (0 means to start from the beginning) :param length: number of bytes to hash (0 means continue to the end of the file) :param int block_size: number of bytes to hash per result (must not be less than 256; 0 means to compute only one hash of the entire segment) :return: `str` of bytes representing the hash of each block, concatenated together :raises: ``IOError`` -- if the server doesn't support the "check-file" extension, or possibly doesn't support the hash algorithm requested .. note:: Many (most?) servers don't support this extension yet. .. versionadded:: 1.4 """ t, msg = self.sftp._request( CMD_EXTENDED, "check-file", self.handle, hash_algorithm, long(offset), long(length), block_size, ) msg.get_text() # ext msg.get_text() # alg data = msg.get_remainder() return data
[ "def", "check", "(", "self", ",", "hash_algorithm", ",", "offset", "=", "0", ",", "length", "=", "0", ",", "block_size", "=", "0", ")", ":", "t", ",", "msg", "=", "self", ".", "sftp", ".", "_request", "(", "CMD_EXTENDED", ",", "\"check-file\"", ",", ...
Ask the server for a hash of a section of this file. This can be used to verify a successful upload or download, or for various rsync-like operations. The file is hashed from ``offset``, for ``length`` bytes. If ``length`` is 0, the remainder of the file is hashed. Thus, if both ``offset`` and ``length`` are zero, the entire file is hashed. Normally, ``block_size`` will be 0 (the default), and this method will return a byte string representing the requested hash (for example, a string of length 16 for MD5, or 20 for SHA-1). If a non-zero ``block_size`` is given, each chunk of the file (from ``offset`` to ``offset + length``) of ``block_size`` bytes is computed as a separate hash. The hash results are all concatenated and returned as a single string. For example, ``check('sha1', 0, 1024, 512)`` will return a string of length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes of the file, and the last 20 bytes will be the SHA-1 of the next 512 bytes. :param str hash_algorithm: the name of the hash algorithm to use (normally ``"sha1"`` or ``"md5"``) :param offset: offset into the file to begin hashing (0 means to start from the beginning) :param length: number of bytes to hash (0 means continue to the end of the file) :param int block_size: number of bytes to hash per result (must not be less than 256; 0 means to compute only one hash of the entire segment) :return: `str` of bytes representing the hash of each block, concatenated together :raises: ``IOError`` -- if the server doesn't support the "check-file" extension, or possibly doesn't support the hash algorithm requested .. note:: Many (most?) servers don't support this extension yet. .. versionadded:: 1.4
[ "Ask", "the", "server", "for", "a", "hash", "of", "a", "section", "of", "this", "file", ".", "This", "can", "be", "used", "to", "verify", "a", "successful", "upload", "or", "download", "or", "for", "various", "rsync", "-", "like", "operations", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L358-L416
train
paramiko/paramiko
paramiko/sftp_file.py
SFTPFile.prefetch
def prefetch(self, file_size=None): """ Pre-fetch the remaining contents of this file in anticipation of future `.read` calls. If reading the entire file, pre-fetching can dramatically improve the download speed by avoiding roundtrip latency. The file's contents are incrementally buffered in a background thread. The prefetched data is stored in a buffer until read via the `.read` method. Once data has been read, it's removed from the buffer. The data may be read in a random order (using `.seek`); chunks of the buffer that haven't been read will continue to be buffered. :param int file_size: When this is ``None`` (the default), this method calls `stat` to determine the remote file size. In some situations, doing so can cause exceptions or hangs (see `#562 <https://github.com/paramiko/paramiko/pull/562>`_); as a workaround, one may call `stat` explicitly and pass its value in via this parameter. .. versionadded:: 1.5.1 .. versionchanged:: 1.16.0 The ``file_size`` parameter was added (with no default value). .. versionchanged:: 1.16.1 The ``file_size`` parameter was made optional for backwards compatibility. """ if file_size is None: file_size = self.stat().st_size # queue up async reads for the rest of the file chunks = [] n = self._realpos while n < file_size: chunk = min(self.MAX_REQUEST_SIZE, file_size - n) chunks.append((n, chunk)) n += chunk if len(chunks) > 0: self._start_prefetch(chunks)
python
def prefetch(self, file_size=None): """ Pre-fetch the remaining contents of this file in anticipation of future `.read` calls. If reading the entire file, pre-fetching can dramatically improve the download speed by avoiding roundtrip latency. The file's contents are incrementally buffered in a background thread. The prefetched data is stored in a buffer until read via the `.read` method. Once data has been read, it's removed from the buffer. The data may be read in a random order (using `.seek`); chunks of the buffer that haven't been read will continue to be buffered. :param int file_size: When this is ``None`` (the default), this method calls `stat` to determine the remote file size. In some situations, doing so can cause exceptions or hangs (see `#562 <https://github.com/paramiko/paramiko/pull/562>`_); as a workaround, one may call `stat` explicitly and pass its value in via this parameter. .. versionadded:: 1.5.1 .. versionchanged:: 1.16.0 The ``file_size`` parameter was added (with no default value). .. versionchanged:: 1.16.1 The ``file_size`` parameter was made optional for backwards compatibility. """ if file_size is None: file_size = self.stat().st_size # queue up async reads for the rest of the file chunks = [] n = self._realpos while n < file_size: chunk = min(self.MAX_REQUEST_SIZE, file_size - n) chunks.append((n, chunk)) n += chunk if len(chunks) > 0: self._start_prefetch(chunks)
[ "def", "prefetch", "(", "self", ",", "file_size", "=", "None", ")", ":", "if", "file_size", "is", "None", ":", "file_size", "=", "self", ".", "stat", "(", ")", ".", "st_size", "# queue up async reads for the rest of the file", "chunks", "=", "[", "]", "n", ...
Pre-fetch the remaining contents of this file in anticipation of future `.read` calls. If reading the entire file, pre-fetching can dramatically improve the download speed by avoiding roundtrip latency. The file's contents are incrementally buffered in a background thread. The prefetched data is stored in a buffer until read via the `.read` method. Once data has been read, it's removed from the buffer. The data may be read in a random order (using `.seek`); chunks of the buffer that haven't been read will continue to be buffered. :param int file_size: When this is ``None`` (the default), this method calls `stat` to determine the remote file size. In some situations, doing so can cause exceptions or hangs (see `#562 <https://github.com/paramiko/paramiko/pull/562>`_); as a workaround, one may call `stat` explicitly and pass its value in via this parameter. .. versionadded:: 1.5.1 .. versionchanged:: 1.16.0 The ``file_size`` parameter was added (with no default value). .. versionchanged:: 1.16.1 The ``file_size`` parameter was made optional for backwards compatibility.
[ "Pre", "-", "fetch", "the", "remaining", "contents", "of", "this", "file", "in", "anticipation", "of", "future", ".", "read", "calls", ".", "If", "reading", "the", "entire", "file", "pre", "-", "fetching", "can", "dramatically", "improve", "the", "download",...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L438-L476
train
paramiko/paramiko
paramiko/sftp_file.py
SFTPFile.readv
def readv(self, chunks): """ Read a set of blocks from the file by (offset, length). This is more efficient than doing a series of `.seek` and `.read` calls, since the prefetch machinery is used to retrieve all the requested blocks at once. :param chunks: a list of ``(offset, length)`` tuples indicating which sections of the file to read :return: a list of blocks read, in the same order as in ``chunks`` .. versionadded:: 1.5.4 """ self.sftp._log( DEBUG, "readv({}, {!r})".format(hexlify(self.handle), chunks) ) read_chunks = [] for offset, size in chunks: # don't fetch data that's already in the prefetch buffer if self._data_in_prefetch_buffers( offset ) or self._data_in_prefetch_requests(offset, size): continue # break up anything larger than the max read size while size > 0: chunk_size = min(size, self.MAX_REQUEST_SIZE) read_chunks.append((offset, chunk_size)) offset += chunk_size size -= chunk_size self._start_prefetch(read_chunks) # now we can just devolve to a bunch of read()s :) for x in chunks: self.seek(x[0]) yield self.read(x[1])
python
def readv(self, chunks): """ Read a set of blocks from the file by (offset, length). This is more efficient than doing a series of `.seek` and `.read` calls, since the prefetch machinery is used to retrieve all the requested blocks at once. :param chunks: a list of ``(offset, length)`` tuples indicating which sections of the file to read :return: a list of blocks read, in the same order as in ``chunks`` .. versionadded:: 1.5.4 """ self.sftp._log( DEBUG, "readv({}, {!r})".format(hexlify(self.handle), chunks) ) read_chunks = [] for offset, size in chunks: # don't fetch data that's already in the prefetch buffer if self._data_in_prefetch_buffers( offset ) or self._data_in_prefetch_requests(offset, size): continue # break up anything larger than the max read size while size > 0: chunk_size = min(size, self.MAX_REQUEST_SIZE) read_chunks.append((offset, chunk_size)) offset += chunk_size size -= chunk_size self._start_prefetch(read_chunks) # now we can just devolve to a bunch of read()s :) for x in chunks: self.seek(x[0]) yield self.read(x[1])
[ "def", "readv", "(", "self", ",", "chunks", ")", ":", "self", ".", "sftp", ".", "_log", "(", "DEBUG", ",", "\"readv({}, {!r})\"", ".", "format", "(", "hexlify", "(", "self", ".", "handle", ")", ",", "chunks", ")", ")", "read_chunks", "=", "[", "]", ...
Read a set of blocks from the file by (offset, length). This is more efficient than doing a series of `.seek` and `.read` calls, since the prefetch machinery is used to retrieve all the requested blocks at once. :param chunks: a list of ``(offset, length)`` tuples indicating which sections of the file to read :return: a list of blocks read, in the same order as in ``chunks`` .. versionadded:: 1.5.4
[ "Read", "a", "set", "of", "blocks", "from", "the", "file", "by", "(", "offset", "length", ")", ".", "This", "is", "more", "efficient", "than", "doing", "a", "series", "of", ".", "seek", "and", ".", "read", "calls", "since", "the", "prefetch", "machiner...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L478-L515
train
paramiko/paramiko
paramiko/sftp_file.py
SFTPFile._check_exception
def _check_exception(self): """if there's a saved exception, raise & clear it""" if self._saved_exception is not None: x = self._saved_exception self._saved_exception = None raise x
python
def _check_exception(self): """if there's a saved exception, raise & clear it""" if self._saved_exception is not None: x = self._saved_exception self._saved_exception = None raise x
[ "def", "_check_exception", "(", "self", ")", ":", "if", "self", ".", "_saved_exception", "is", "not", "None", ":", "x", "=", "self", ".", "_saved_exception", "self", ".", "_saved_exception", "=", "None", "raise", "x" ]
if there's a saved exception, raise & clear it
[ "if", "there", "s", "a", "saved", "exception", "raise", "&", "clear", "it" ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L565-L570
train
paramiko/paramiko
paramiko/channel.py
open_only
def open_only(func): """ Decorator for `.Channel` methods which performs an openness check. :raises: `.SSHException` -- If the wrapped method is called on an unopened `.Channel`. """ @wraps(func) def _check(self, *args, **kwds): if ( self.closed or self.eof_received or self.eof_sent or not self.active ): raise SSHException("Channel is not open") return func(self, *args, **kwds) return _check
python
def open_only(func): """ Decorator for `.Channel` methods which performs an openness check. :raises: `.SSHException` -- If the wrapped method is called on an unopened `.Channel`. """ @wraps(func) def _check(self, *args, **kwds): if ( self.closed or self.eof_received or self.eof_sent or not self.active ): raise SSHException("Channel is not open") return func(self, *args, **kwds) return _check
[ "def", "open_only", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_check", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "(", "self", ".", "closed", "or", "self", ".", "eof_received", "or", "self", ".", ...
Decorator for `.Channel` methods which performs an openness check. :raises: `.SSHException` -- If the wrapped method is called on an unopened `.Channel`.
[ "Decorator", "for", ".", "Channel", "methods", "which", "performs", "an", "openness", "check", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L54-L74
train
paramiko/paramiko
paramiko/channel.py
Channel.exec_command
def exec_command(self, command): """ Execute a command on the server. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the command being executed. When the command finishes executing, the channel will be closed and can't be reused. You must open a new channel if you wish to execute another command. :param str command: a shell command to execute. :raises: `.SSHException` -- if the request was rejected or the channel was closed """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("exec") m.add_boolean(True) m.add_string(command) self._event_pending() self.transport._send_user_message(m) self._wait_for_event()
python
def exec_command(self, command): """ Execute a command on the server. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the command being executed. When the command finishes executing, the channel will be closed and can't be reused. You must open a new channel if you wish to execute another command. :param str command: a shell command to execute. :raises: `.SSHException` -- if the request was rejected or the channel was closed """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("exec") m.add_boolean(True) m.add_string(command) self._event_pending() self.transport._send_user_message(m) self._wait_for_event()
[ "def", "exec_command", "(", "self", ",", "command", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_CHANNEL_REQUEST", ")", "m", ".", "add_int", "(", "self", ".", "remote_chanid", ")", "m", ".", "add_string", "(", "\"exec\"", "...
Execute a command on the server. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the command being executed. When the command finishes executing, the channel will be closed and can't be reused. You must open a new channel if you wish to execute another command. :param str command: a shell command to execute. :raises: `.SSHException` -- if the request was rejected or the channel was closed
[ "Execute", "a", "command", "on", "the", "server", ".", "If", "the", "server", "allows", "it", "the", "channel", "will", "then", "be", "directly", "connected", "to", "the", "stdin", "stdout", "and", "stderr", "of", "the", "command", "being", "executed", "."...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L233-L257
train
paramiko/paramiko
paramiko/channel.py
Channel.resize_pty
def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0): """ Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen :param int height: new height (in characters) of the terminal screen :param int width_pixels: new width (in pixels) of the terminal screen :param int height_pixels: new height (in pixels) of the terminal screen :raises: `.SSHException` -- if the request was rejected or the channel was closed """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("window-change") m.add_boolean(False) m.add_int(width) m.add_int(height) m.add_int(width_pixels) m.add_int(height_pixels) self.transport._send_user_message(m)
python
def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0): """ Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen :param int height: new height (in characters) of the terminal screen :param int width_pixels: new width (in pixels) of the terminal screen :param int height_pixels: new height (in pixels) of the terminal screen :raises: `.SSHException` -- if the request was rejected or the channel was closed """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("window-change") m.add_boolean(False) m.add_int(width) m.add_int(height) m.add_int(width_pixels) m.add_int(height_pixels) self.transport._send_user_message(m)
[ "def", "resize_pty", "(", "self", ",", "width", "=", "80", ",", "height", "=", "24", ",", "width_pixels", "=", "0", ",", "height_pixels", "=", "0", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_CHANNEL_REQUEST", ")", "m", ...
Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen :param int height: new height (in characters) of the terminal screen :param int width_pixels: new width (in pixels) of the terminal screen :param int height_pixels: new height (in pixels) of the terminal screen :raises: `.SSHException` -- if the request was rejected or the channel was closed
[ "Resize", "the", "pseudo", "-", "terminal", ".", "This", "can", "be", "used", "to", "change", "the", "width", "and", "height", "of", "the", "terminal", "emulation", "created", "in", "a", "previous", "get_pty", "call", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L286-L309
train
paramiko/paramiko
paramiko/channel.py
Channel.update_environment
def update_environment(self, environment): """ Updates this channel's remote shell environment. .. note:: This operation is additive - i.e. the current environment is not reset before the given environment variables are set. .. warning:: Servers may silently reject some environment variables; see the warning in `set_environment_variable` for details. :param dict environment: a dictionary containing the name and respective values to set :raises: `.SSHException` -- if any of the environment variables was rejected by the server or the channel was closed """ for name, value in environment.items(): try: self.set_environment_variable(name, value) except SSHException as e: err = 'Failed to set environment variable "{}".' raise SSHException(err.format(name), e)
python
def update_environment(self, environment): """ Updates this channel's remote shell environment. .. note:: This operation is additive - i.e. the current environment is not reset before the given environment variables are set. .. warning:: Servers may silently reject some environment variables; see the warning in `set_environment_variable` for details. :param dict environment: a dictionary containing the name and respective values to set :raises: `.SSHException` -- if any of the environment variables was rejected by the server or the channel was closed """ for name, value in environment.items(): try: self.set_environment_variable(name, value) except SSHException as e: err = 'Failed to set environment variable "{}".' raise SSHException(err.format(name), e)
[ "def", "update_environment", "(", "self", ",", "environment", ")", ":", "for", "name", ",", "value", "in", "environment", ".", "items", "(", ")", ":", "try", ":", "self", ".", "set_environment_variable", "(", "name", ",", "value", ")", "except", "SSHExcept...
Updates this channel's remote shell environment. .. note:: This operation is additive - i.e. the current environment is not reset before the given environment variables are set. .. warning:: Servers may silently reject some environment variables; see the warning in `set_environment_variable` for details. :param dict environment: a dictionary containing the name and respective values to set :raises: `.SSHException` -- if any of the environment variables was rejected by the server or the channel was closed
[ "Updates", "this", "channel", "s", "remote", "shell", "environment", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L312-L335
train
paramiko/paramiko
paramiko/channel.py
Channel.set_environment_variable
def set_environment_variable(self, name, value): """ Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this particular request type). Make sure you understand your server's configuration before using! :param str name: name of the environment variable :param str value: value of the environment variable :raises: `.SSHException` -- if the request was rejected or the channel was closed """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("env") m.add_boolean(False) m.add_string(name) m.add_string(value) self.transport._send_user_message(m)
python
def set_environment_variable(self, name, value): """ Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this particular request type). Make sure you understand your server's configuration before using! :param str name: name of the environment variable :param str value: value of the environment variable :raises: `.SSHException` -- if the request was rejected or the channel was closed """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("env") m.add_boolean(False) m.add_string(name) m.add_string(value) self.transport._send_user_message(m)
[ "def", "set_environment_variable", "(", "self", ",", "name", ",", "value", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_CHANNEL_REQUEST", ")", "m", ".", "add_int", "(", "self", ".", "remote_chanid", ")", "m", ".", "add_string...
Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this particular request type). Make sure you understand your server's configuration before using! :param str name: name of the environment variable :param str value: value of the environment variable :raises: `.SSHException` -- if the request was rejected or the channel was closed
[ "Set", "the", "value", "of", "an", "environment", "variable", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L338-L362
train
paramiko/paramiko
paramiko/channel.py
Channel.recv_exit_status
def recv_exit_status(self): """ Return the exit status from the process on the server. This is mostly useful for retrieving the results of an `exec_command`. If the command hasn't finished yet, this method will wait until it does, or until the channel is closed. If no exit status is provided by the server, -1 is returned. .. warning:: In some situations, receiving remote output larger than the current `.Transport` or session's ``window_size`` (e.g. that set by the ``default_window_size`` kwarg for `.Transport.__init__`) will cause `.recv_exit_status` to hang indefinitely if it is called prior to a sufficiently large `.Channel.recv` (or if there are no threads calling `.Channel.recv` in the background). In these cases, ensuring that `.recv_exit_status` is called *after* `.Channel.recv` (or, again, using threads) can avoid the hang. :return: the exit code (as an `int`) of the process on the server. .. versionadded:: 1.2 """ self.status_event.wait() assert self.status_event.is_set() return self.exit_status
python
def recv_exit_status(self): """ Return the exit status from the process on the server. This is mostly useful for retrieving the results of an `exec_command`. If the command hasn't finished yet, this method will wait until it does, or until the channel is closed. If no exit status is provided by the server, -1 is returned. .. warning:: In some situations, receiving remote output larger than the current `.Transport` or session's ``window_size`` (e.g. that set by the ``default_window_size`` kwarg for `.Transport.__init__`) will cause `.recv_exit_status` to hang indefinitely if it is called prior to a sufficiently large `.Channel.recv` (or if there are no threads calling `.Channel.recv` in the background). In these cases, ensuring that `.recv_exit_status` is called *after* `.Channel.recv` (or, again, using threads) can avoid the hang. :return: the exit code (as an `int`) of the process on the server. .. versionadded:: 1.2 """ self.status_event.wait() assert self.status_event.is_set() return self.exit_status
[ "def", "recv_exit_status", "(", "self", ")", ":", "self", ".", "status_event", ".", "wait", "(", ")", "assert", "self", ".", "status_event", ".", "is_set", "(", ")", "return", "self", ".", "exit_status" ]
Return the exit status from the process on the server. This is mostly useful for retrieving the results of an `exec_command`. If the command hasn't finished yet, this method will wait until it does, or until the channel is closed. If no exit status is provided by the server, -1 is returned. .. warning:: In some situations, receiving remote output larger than the current `.Transport` or session's ``window_size`` (e.g. that set by the ``default_window_size`` kwarg for `.Transport.__init__`) will cause `.recv_exit_status` to hang indefinitely if it is called prior to a sufficiently large `.Channel.recv` (or if there are no threads calling `.Channel.recv` in the background). In these cases, ensuring that `.recv_exit_status` is called *after* `.Channel.recv` (or, again, using threads) can avoid the hang. :return: the exit code (as an `int`) of the process on the server. .. versionadded:: 1.2
[ "Return", "the", "exit", "status", "from", "the", "process", "on", "the", "server", ".", "This", "is", "mostly", "useful", "for", "retrieving", "the", "results", "of", "an", "exec_command", ".", "If", "the", "command", "hasn", "t", "finished", "yet", "this...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L379-L404
train
paramiko/paramiko
paramiko/channel.py
Channel.request_x11
def request_x11( self, screen_number=0, auth_protocol=None, auth_cookie=None, single_connection=False, handler=None, ): """ Request an x11 session on this channel. If the server allows it, further x11 requests can be made from the server to the client, when an x11 application is run in a shell session. From :rfc:`4254`:: It is RECOMMENDED that the 'x11 authentication cookie' that is sent be a fake, random cookie, and that the cookie be checked and replaced by the real cookie when a connection request is received. If you omit the auth_cookie, a new secure random 128-bit value will be generated, used, and returned. You will need to use this value to verify incoming x11 requests and replace them with the actual local x11 cookie (which requires some knowledge of the x11 protocol). If a handler is passed in, the handler is called from another thread whenever a new x11 connection arrives. The default handler queues up incoming x11 connections, which may be retrieved using `.Transport.accept`. The handler's calling signature is:: handler(channel: Channel, (address: str, port: int)) :param int screen_number: the x11 screen number (0, 10, etc.) :param str auth_protocol: the name of the X11 authentication method used; if none is given, ``"MIT-MAGIC-COOKIE-1"`` is used :param str auth_cookie: hexadecimal string containing the x11 auth cookie; if none is given, a secure random 128-bit value is generated :param bool single_connection: if True, only a single x11 connection will be forwarded (by default, any number of x11 connections can arrive over this session) :param handler: an optional callable handler to use for incoming X11 connections :return: the auth_cookie used """ if auth_protocol is None: auth_protocol = "MIT-MAGIC-COOKIE-1" if auth_cookie is None: auth_cookie = binascii.hexlify(os.urandom(16)) m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("x11-req") m.add_boolean(True) m.add_boolean(single_connection) m.add_string(auth_protocol) m.add_string(auth_cookie) m.add_int(screen_number) self._event_pending() self.transport._send_user_message(m) self._wait_for_event() self.transport._set_x11_handler(handler) return auth_cookie
python
def request_x11( self, screen_number=0, auth_protocol=None, auth_cookie=None, single_connection=False, handler=None, ): """ Request an x11 session on this channel. If the server allows it, further x11 requests can be made from the server to the client, when an x11 application is run in a shell session. From :rfc:`4254`:: It is RECOMMENDED that the 'x11 authentication cookie' that is sent be a fake, random cookie, and that the cookie be checked and replaced by the real cookie when a connection request is received. If you omit the auth_cookie, a new secure random 128-bit value will be generated, used, and returned. You will need to use this value to verify incoming x11 requests and replace them with the actual local x11 cookie (which requires some knowledge of the x11 protocol). If a handler is passed in, the handler is called from another thread whenever a new x11 connection arrives. The default handler queues up incoming x11 connections, which may be retrieved using `.Transport.accept`. The handler's calling signature is:: handler(channel: Channel, (address: str, port: int)) :param int screen_number: the x11 screen number (0, 10, etc.) :param str auth_protocol: the name of the X11 authentication method used; if none is given, ``"MIT-MAGIC-COOKIE-1"`` is used :param str auth_cookie: hexadecimal string containing the x11 auth cookie; if none is given, a secure random 128-bit value is generated :param bool single_connection: if True, only a single x11 connection will be forwarded (by default, any number of x11 connections can arrive over this session) :param handler: an optional callable handler to use for incoming X11 connections :return: the auth_cookie used """ if auth_protocol is None: auth_protocol = "MIT-MAGIC-COOKIE-1" if auth_cookie is None: auth_cookie = binascii.hexlify(os.urandom(16)) m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("x11-req") m.add_boolean(True) m.add_boolean(single_connection) m.add_string(auth_protocol) m.add_string(auth_cookie) m.add_int(screen_number) self._event_pending() self.transport._send_user_message(m) self._wait_for_event() self.transport._set_x11_handler(handler) return auth_cookie
[ "def", "request_x11", "(", "self", ",", "screen_number", "=", "0", ",", "auth_protocol", "=", "None", ",", "auth_cookie", "=", "None", ",", "single_connection", "=", "False", ",", "handler", "=", "None", ",", ")", ":", "if", "auth_protocol", "is", "None", ...
Request an x11 session on this channel. If the server allows it, further x11 requests can be made from the server to the client, when an x11 application is run in a shell session. From :rfc:`4254`:: It is RECOMMENDED that the 'x11 authentication cookie' that is sent be a fake, random cookie, and that the cookie be checked and replaced by the real cookie when a connection request is received. If you omit the auth_cookie, a new secure random 128-bit value will be generated, used, and returned. You will need to use this value to verify incoming x11 requests and replace them with the actual local x11 cookie (which requires some knowledge of the x11 protocol). If a handler is passed in, the handler is called from another thread whenever a new x11 connection arrives. The default handler queues up incoming x11 connections, which may be retrieved using `.Transport.accept`. The handler's calling signature is:: handler(channel: Channel, (address: str, port: int)) :param int screen_number: the x11 screen number (0, 10, etc.) :param str auth_protocol: the name of the X11 authentication method used; if none is given, ``"MIT-MAGIC-COOKIE-1"`` is used :param str auth_cookie: hexadecimal string containing the x11 auth cookie; if none is given, a secure random 128-bit value is generated :param bool single_connection: if True, only a single x11 connection will be forwarded (by default, any number of x11 connections can arrive over this session) :param handler: an optional callable handler to use for incoming X11 connections :return: the auth_cookie used
[ "Request", "an", "x11", "session", "on", "this", "channel", ".", "If", "the", "server", "allows", "it", "further", "x11", "requests", "can", "be", "made", "from", "the", "server", "to", "the", "client", "when", "an", "x11", "application", "is", "run", "i...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L428-L492
train
paramiko/paramiko
paramiko/channel.py
Channel.request_forward_agent
def request_forward_agent(self, handler): """ Request for a forward SSH Agent on this channel. This is only valid for an ssh-agent from OpenSSH !!! :param handler: a required callable handler to use for incoming SSH Agent connections :return: True if we are ok, else False (at that time we always return ok) :raises: SSHException in case of channel problem. """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("auth-agent-req@openssh.com") m.add_boolean(False) self.transport._send_user_message(m) self.transport._set_forward_agent_handler(handler) return True
python
def request_forward_agent(self, handler): """ Request for a forward SSH Agent on this channel. This is only valid for an ssh-agent from OpenSSH !!! :param handler: a required callable handler to use for incoming SSH Agent connections :return: True if we are ok, else False (at that time we always return ok) :raises: SSHException in case of channel problem. """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string("auth-agent-req@openssh.com") m.add_boolean(False) self.transport._send_user_message(m) self.transport._set_forward_agent_handler(handler) return True
[ "def", "request_forward_agent", "(", "self", ",", "handler", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_CHANNEL_REQUEST", ")", "m", ".", "add_int", "(", "self", ".", "remote_chanid", ")", "m", ".", "add_string", "(", "\"aut...
Request for a forward SSH Agent on this channel. This is only valid for an ssh-agent from OpenSSH !!! :param handler: a required callable handler to use for incoming SSH Agent connections :return: True if we are ok, else False (at that time we always return ok) :raises: SSHException in case of channel problem.
[ "Request", "for", "a", "forward", "SSH", "Agent", "on", "this", "channel", ".", "This", "is", "only", "valid", "for", "an", "ssh", "-", "agent", "from", "OpenSSH", "!!!" ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L495-L516
train
paramiko/paramiko
paramiko/channel.py
Channel.set_combine_stderr
def set_combine_stderr(self, combine): """ Set whether stderr should be combined into stdout on this channel. The default is ``False``, but in some cases it may be convenient to have both streams combined. If this is ``False``, and `exec_command` is called (or ``invoke_shell`` with no pty), output to stderr will not show up through the `recv` and `recv_ready` calls. You will have to use `recv_stderr` and `recv_stderr_ready` to get stderr output. If this is ``True``, data will never show up via `recv_stderr` or `recv_stderr_ready`. :param bool combine: ``True`` if stderr output should be combined into stdout on this channel. :return: the previous setting (a `bool`). .. versionadded:: 1.1 """ data = bytes() self.lock.acquire() try: old = self.combine_stderr self.combine_stderr = combine if combine and not old: # copy old stderr buffer into primary buffer data = self.in_stderr_buffer.empty() finally: self.lock.release() if len(data) > 0: self._feed(data) return old
python
def set_combine_stderr(self, combine): """ Set whether stderr should be combined into stdout on this channel. The default is ``False``, but in some cases it may be convenient to have both streams combined. If this is ``False``, and `exec_command` is called (or ``invoke_shell`` with no pty), output to stderr will not show up through the `recv` and `recv_ready` calls. You will have to use `recv_stderr` and `recv_stderr_ready` to get stderr output. If this is ``True``, data will never show up via `recv_stderr` or `recv_stderr_ready`. :param bool combine: ``True`` if stderr output should be combined into stdout on this channel. :return: the previous setting (a `bool`). .. versionadded:: 1.1 """ data = bytes() self.lock.acquire() try: old = self.combine_stderr self.combine_stderr = combine if combine and not old: # copy old stderr buffer into primary buffer data = self.in_stderr_buffer.empty() finally: self.lock.release() if len(data) > 0: self._feed(data) return old
[ "def", "set_combine_stderr", "(", "self", ",", "combine", ")", ":", "data", "=", "bytes", "(", ")", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "old", "=", "self", ".", "combine_stderr", "self", ".", "combine_stderr", "=", "combine", "if...
Set whether stderr should be combined into stdout on this channel. The default is ``False``, but in some cases it may be convenient to have both streams combined. If this is ``False``, and `exec_command` is called (or ``invoke_shell`` with no pty), output to stderr will not show up through the `recv` and `recv_ready` calls. You will have to use `recv_stderr` and `recv_stderr_ready` to get stderr output. If this is ``True``, data will never show up via `recv_stderr` or `recv_stderr_ready`. :param bool combine: ``True`` if stderr output should be combined into stdout on this channel. :return: the previous setting (a `bool`). .. versionadded:: 1.1
[ "Set", "whether", "stderr", "should", "be", "combined", "into", "stdout", "on", "this", "channel", ".", "The", "default", "is", "False", "but", "in", "some", "cases", "it", "may", "be", "convenient", "to", "have", "both", "streams", "combined", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L551-L584
train
paramiko/paramiko
paramiko/channel.py
Channel.close
def close(self): """ Close the channel. All future read/write operations on the channel will fail. The remote end will receive no more data (after queued data is flushed). Channels are automatically closed when their `.Transport` is closed or when they are garbage collected. """ self.lock.acquire() try: # only close the pipe when the user explicitly closes the channel. # otherwise they will get unpleasant surprises. (and do it before # checking self.closed, since the remote host may have already # closed the connection.) if self._pipe is not None: self._pipe.close() self._pipe = None if not self.active or self.closed: return msgs = self._close_internal() finally: self.lock.release() for m in msgs: if m is not None: self.transport._send_user_message(m)
python
def close(self): """ Close the channel. All future read/write operations on the channel will fail. The remote end will receive no more data (after queued data is flushed). Channels are automatically closed when their `.Transport` is closed or when they are garbage collected. """ self.lock.acquire() try: # only close the pipe when the user explicitly closes the channel. # otherwise they will get unpleasant surprises. (and do it before # checking self.closed, since the remote host may have already # closed the connection.) if self._pipe is not None: self._pipe.close() self._pipe = None if not self.active or self.closed: return msgs = self._close_internal() finally: self.lock.release() for m in msgs: if m is not None: self.transport._send_user_message(m)
[ "def", "close", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "# only close the pipe when the user explicitly closes the channel.", "# otherwise they will get unpleasant surprises. (and do it before", "# checking self.closed, since the remote ho...
Close the channel. All future read/write operations on the channel will fail. The remote end will receive no more data (after queued data is flushed). Channels are automatically closed when their `.Transport` is closed or when they are garbage collected.
[ "Close", "the", "channel", ".", "All", "future", "read", "/", "write", "operations", "on", "the", "channel", "will", "fail", ".", "The", "remote", "end", "will", "receive", "no", "more", "data", "(", "after", "queued", "data", "is", "flushed", ")", ".", ...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L647-L671
train
paramiko/paramiko
paramiko/channel.py
Channel.send_ready
def send_ready(self): """ Returns true if data can be written to this channel without blocking. This means the channel is either closed (so any write attempt would return immediately) or there is at least one byte of space in the outbound buffer. If there is at least one byte of space in the outbound buffer, a `send` call will succeed immediately and return the number of bytes actually written. :return: ``True`` if a `send` call on this channel would immediately succeed or fail """ self.lock.acquire() try: if self.closed or self.eof_sent: return True return self.out_window_size > 0 finally: self.lock.release()
python
def send_ready(self): """ Returns true if data can be written to this channel without blocking. This means the channel is either closed (so any write attempt would return immediately) or there is at least one byte of space in the outbound buffer. If there is at least one byte of space in the outbound buffer, a `send` call will succeed immediately and return the number of bytes actually written. :return: ``True`` if a `send` call on this channel would immediately succeed or fail """ self.lock.acquire() try: if self.closed or self.eof_sent: return True return self.out_window_size > 0 finally: self.lock.release()
[ "def", "send_ready", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "closed", "or", "self", ".", "eof_sent", ":", "return", "True", "return", "self", ".", "out_window_size", ">", "0", "finally", "...
Returns true if data can be written to this channel without blocking. This means the channel is either closed (so any write attempt would return immediately) or there is at least one byte of space in the outbound buffer. If there is at least one byte of space in the outbound buffer, a `send` call will succeed immediately and return the number of bytes actually written. :return: ``True`` if a `send` call on this channel would immediately succeed or fail
[ "Returns", "true", "if", "data", "can", "be", "written", "to", "this", "channel", "without", "blocking", ".", "This", "means", "the", "channel", "is", "either", "closed", "(", "so", "any", "write", "attempt", "would", "return", "immediately", ")", "or", "t...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L762-L781
train
paramiko/paramiko
paramiko/channel.py
Channel.send
def send(self, s): """ Send data to the channel. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. :param str s: data to send :return: number of bytes actually sent, as an `int` :raises socket.timeout: if no data could be sent before the timeout set by `settimeout`. """ m = Message() m.add_byte(cMSG_CHANNEL_DATA) m.add_int(self.remote_chanid) return self._send(s, m)
python
def send(self, s): """ Send data to the channel. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. :param str s: data to send :return: number of bytes actually sent, as an `int` :raises socket.timeout: if no data could be sent before the timeout set by `settimeout`. """ m = Message() m.add_byte(cMSG_CHANNEL_DATA) m.add_int(self.remote_chanid) return self._send(s, m)
[ "def", "send", "(", "self", ",", "s", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_CHANNEL_DATA", ")", "m", ".", "add_int", "(", "self", ".", "remote_chanid", ")", "return", "self", ".", "_send", "(", "s", ",", "m", "...
Send data to the channel. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. :param str s: data to send :return: number of bytes actually sent, as an `int` :raises socket.timeout: if no data could be sent before the timeout set by `settimeout`.
[ "Send", "data", "to", "the", "channel", ".", "Returns", "the", "number", "of", "bytes", "sent", "or", "0", "if", "the", "channel", "stream", "is", "closed", ".", "Applications", "are", "responsible", "for", "checking", "that", "all", "data", "has", "been",...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L783-L801
train
paramiko/paramiko
paramiko/channel.py
Channel.send_stderr
def send_stderr(self, s): """ Send data to the channel on the "stderr" stream. This is normally only used by servers to send output from shell commands -- clients won't use this. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. :param str s: data to send. :return: number of bytes actually sent, as an `int`. :raises socket.timeout: if no data could be sent before the timeout set by `settimeout`. .. versionadded:: 1.1 """ m = Message() m.add_byte(cMSG_CHANNEL_EXTENDED_DATA) m.add_int(self.remote_chanid) m.add_int(1) return self._send(s, m)
python
def send_stderr(self, s): """ Send data to the channel on the "stderr" stream. This is normally only used by servers to send output from shell commands -- clients won't use this. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. :param str s: data to send. :return: number of bytes actually sent, as an `int`. :raises socket.timeout: if no data could be sent before the timeout set by `settimeout`. .. versionadded:: 1.1 """ m = Message() m.add_byte(cMSG_CHANNEL_EXTENDED_DATA) m.add_int(self.remote_chanid) m.add_int(1) return self._send(s, m)
[ "def", "send_stderr", "(", "self", ",", "s", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_CHANNEL_EXTENDED_DATA", ")", "m", ".", "add_int", "(", "self", ".", "remote_chanid", ")", "m", ".", "add_int", "(", "1", ")", "retu...
Send data to the channel on the "stderr" stream. This is normally only used by servers to send output from shell commands -- clients won't use this. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. :param str s: data to send. :return: number of bytes actually sent, as an `int`. :raises socket.timeout: if no data could be sent before the timeout set by `settimeout`. .. versionadded:: 1.1
[ "Send", "data", "to", "the", "channel", "on", "the", "stderr", "stream", ".", "This", "is", "normally", "only", "used", "by", "servers", "to", "send", "output", "from", "shell", "commands", "--", "clients", "won", "t", "use", "this", ".", "Returns", "the...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L803-L825
train
paramiko/paramiko
paramiko/channel.py
Channel.sendall
def sendall(self, s): """ Send data to the channel, without allowing partial results. Unlike `send`, this method continues to send data from the given string until either all data has been sent or an error occurs. Nothing is returned. :param str s: data to send. :raises socket.timeout: if sending stalled for longer than the timeout set by `settimeout`. :raises socket.error: if an error occurred before the entire string was sent. .. note:: If the channel is closed while only part of the data has been sent, there is no way to determine how much data (if any) was sent. This is irritating, but identically follows Python's API. """ while s: sent = self.send(s) s = s[sent:] return None
python
def sendall(self, s): """ Send data to the channel, without allowing partial results. Unlike `send`, this method continues to send data from the given string until either all data has been sent or an error occurs. Nothing is returned. :param str s: data to send. :raises socket.timeout: if sending stalled for longer than the timeout set by `settimeout`. :raises socket.error: if an error occurred before the entire string was sent. .. note:: If the channel is closed while only part of the data has been sent, there is no way to determine how much data (if any) was sent. This is irritating, but identically follows Python's API. """ while s: sent = self.send(s) s = s[sent:] return None
[ "def", "sendall", "(", "self", ",", "s", ")", ":", "while", "s", ":", "sent", "=", "self", ".", "send", "(", "s", ")", "s", "=", "s", "[", "sent", ":", "]", "return", "None" ]
Send data to the channel, without allowing partial results. Unlike `send`, this method continues to send data from the given string until either all data has been sent or an error occurs. Nothing is returned. :param str s: data to send. :raises socket.timeout: if sending stalled for longer than the timeout set by `settimeout`. :raises socket.error: if an error occurred before the entire string was sent. .. note:: If the channel is closed while only part of the data has been sent, there is no way to determine how much data (if any) was sent. This is irritating, but identically follows Python's API.
[ "Send", "data", "to", "the", "channel", "without", "allowing", "partial", "results", ".", "Unlike", "send", "this", "method", "continues", "to", "send", "data", "from", "the", "given", "string", "until", "either", "all", "data", "has", "been", "sent", "or", ...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L827-L848
train
paramiko/paramiko
paramiko/channel.py
Channel.sendall_stderr
def sendall_stderr(self, s): """ Send data to the channel's "stderr" stream, without allowing partial results. Unlike `send_stderr`, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. :param str s: data to send to the client as "stderr" output. :raises socket.timeout: if sending stalled for longer than the timeout set by `settimeout`. :raises socket.error: if an error occurred before the entire string was sent. .. versionadded:: 1.1 """ while s: sent = self.send_stderr(s) s = s[sent:] return None
python
def sendall_stderr(self, s): """ Send data to the channel's "stderr" stream, without allowing partial results. Unlike `send_stderr`, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. :param str s: data to send to the client as "stderr" output. :raises socket.timeout: if sending stalled for longer than the timeout set by `settimeout`. :raises socket.error: if an error occurred before the entire string was sent. .. versionadded:: 1.1 """ while s: sent = self.send_stderr(s) s = s[sent:] return None
[ "def", "sendall_stderr", "(", "self", ",", "s", ")", ":", "while", "s", ":", "sent", "=", "self", ".", "send_stderr", "(", "s", ")", "s", "=", "s", "[", "sent", ":", "]", "return", "None" ]
Send data to the channel's "stderr" stream, without allowing partial results. Unlike `send_stderr`, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. :param str s: data to send to the client as "stderr" output. :raises socket.timeout: if sending stalled for longer than the timeout set by `settimeout`. :raises socket.error: if an error occurred before the entire string was sent. .. versionadded:: 1.1
[ "Send", "data", "to", "the", "channel", "s", "stderr", "stream", "without", "allowing", "partial", "results", ".", "Unlike", "send_stderr", "this", "method", "continues", "to", "send", "data", "from", "the", "given", "string", "until", "all", "data", "has", ...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L850-L869
train
paramiko/paramiko
paramiko/channel.py
Channel.fileno
def fileno(self): """ Returns an OS-level file descriptor which can be used for polling, but but not for reading or writing. This is primarily to allow Python's ``select`` module to work. The first time ``fileno`` is called on a channel, a pipe is created to simulate real OS-level file descriptor (FD) behavior. Because of this, two OS-level FDs are created, which will use up FDs faster than normal. (You won't notice this effect unless you have hundreds of channels open at the same time.) :return: an OS-level file descriptor (`int`) .. warning:: This method causes channel reads to be slightly less efficient. """ self.lock.acquire() try: if self._pipe is not None: return self._pipe.fileno() # create the pipe and feed in any existing data self._pipe = pipe.make_pipe() p1, p2 = pipe.make_or_pipe(self._pipe) self.in_buffer.set_event(p1) self.in_stderr_buffer.set_event(p2) return self._pipe.fileno() finally: self.lock.release()
python
def fileno(self): """ Returns an OS-level file descriptor which can be used for polling, but but not for reading or writing. This is primarily to allow Python's ``select`` module to work. The first time ``fileno`` is called on a channel, a pipe is created to simulate real OS-level file descriptor (FD) behavior. Because of this, two OS-level FDs are created, which will use up FDs faster than normal. (You won't notice this effect unless you have hundreds of channels open at the same time.) :return: an OS-level file descriptor (`int`) .. warning:: This method causes channel reads to be slightly less efficient. """ self.lock.acquire() try: if self._pipe is not None: return self._pipe.fileno() # create the pipe and feed in any existing data self._pipe = pipe.make_pipe() p1, p2 = pipe.make_or_pipe(self._pipe) self.in_buffer.set_event(p1) self.in_stderr_buffer.set_event(p2) return self._pipe.fileno() finally: self.lock.release()
[ "def", "fileno", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "_pipe", "is", "not", "None", ":", "return", "self", ".", "_pipe", ".", "fileno", "(", ")", "# create the pipe and feed in any existing ...
Returns an OS-level file descriptor which can be used for polling, but but not for reading or writing. This is primarily to allow Python's ``select`` module to work. The first time ``fileno`` is called on a channel, a pipe is created to simulate real OS-level file descriptor (FD) behavior. Because of this, two OS-level FDs are created, which will use up FDs faster than normal. (You won't notice this effect unless you have hundreds of channels open at the same time.) :return: an OS-level file descriptor (`int`) .. warning:: This method causes channel reads to be slightly less efficient.
[ "Returns", "an", "OS", "-", "level", "file", "descriptor", "which", "can", "be", "used", "for", "polling", "but", "but", "not", "for", "reading", "or", "writing", ".", "This", "is", "primarily", "to", "allow", "Python", "s", "select", "module", "to", "wo...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L898-L926
train
paramiko/paramiko
paramiko/channel.py
Channel.shutdown
def shutdown(self, how): """ Shut down one or both halves of the connection. If ``how`` is 0, further receives are disallowed. If ``how`` is 1, further sends are disallowed. If ``how`` is 2, further sends and receives are disallowed. This closes the stream in one or both directions. :param int how: 0 (stop receiving), 1 (stop sending), or 2 (stop receiving and sending). """ if (how == 0) or (how == 2): # feign "read" shutdown self.eof_received = 1 if (how == 1) or (how == 2): self.lock.acquire() try: m = self._send_eof() finally: self.lock.release() if m is not None: self.transport._send_user_message(m)
python
def shutdown(self, how): """ Shut down one or both halves of the connection. If ``how`` is 0, further receives are disallowed. If ``how`` is 1, further sends are disallowed. If ``how`` is 2, further sends and receives are disallowed. This closes the stream in one or both directions. :param int how: 0 (stop receiving), 1 (stop sending), or 2 (stop receiving and sending). """ if (how == 0) or (how == 2): # feign "read" shutdown self.eof_received = 1 if (how == 1) or (how == 2): self.lock.acquire() try: m = self._send_eof() finally: self.lock.release() if m is not None: self.transport._send_user_message(m)
[ "def", "shutdown", "(", "self", ",", "how", ")", ":", "if", "(", "how", "==", "0", ")", "or", "(", "how", "==", "2", ")", ":", "# feign \"read\" shutdown", "self", ".", "eof_received", "=", "1", "if", "(", "how", "==", "1", ")", "or", "(", "how",...
Shut down one or both halves of the connection. If ``how`` is 0, further receives are disallowed. If ``how`` is 1, further sends are disallowed. If ``how`` is 2, further sends and receives are disallowed. This closes the stream in one or both directions. :param int how: 0 (stop receiving), 1 (stop sending), or 2 (stop receiving and sending).
[ "Shut", "down", "one", "or", "both", "halves", "of", "the", "connection", ".", "If", "how", "is", "0", "further", "receives", "are", "disallowed", ".", "If", "how", "is", "1", "further", "sends", "are", "disallowed", ".", "If", "how", "is", "2", "furth...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L928-L949
train
paramiko/paramiko
paramiko/channel.py
Channel._wait_for_send_window
def _wait_for_send_window(self, size): """ (You are already holding the lock.) Wait for the send window to open up, and allocate up to ``size`` bytes for transmission. If no space opens up before the timeout, a timeout exception is raised. Returns the number of bytes available to send (may be less than requested). """ # you are already holding the lock if self.closed or self.eof_sent: return 0 if self.out_window_size == 0: # should we block? if self.timeout == 0.0: raise socket.timeout() # loop here in case we get woken up but a different thread has # filled the buffer timeout = self.timeout while self.out_window_size == 0: if self.closed or self.eof_sent: return 0 then = time.time() self.out_buffer_cv.wait(timeout) if timeout is not None: timeout -= time.time() - then if timeout <= 0.0: raise socket.timeout() # we have some window to squeeze into if self.closed or self.eof_sent: return 0 if self.out_window_size < size: size = self.out_window_size if self.out_max_packet_size - 64 < size: size = self.out_max_packet_size - 64 self.out_window_size -= size if self.ultra_debug: self._log(DEBUG, "window down to {}".format(self.out_window_size)) return size
python
def _wait_for_send_window(self, size): """ (You are already holding the lock.) Wait for the send window to open up, and allocate up to ``size`` bytes for transmission. If no space opens up before the timeout, a timeout exception is raised. Returns the number of bytes available to send (may be less than requested). """ # you are already holding the lock if self.closed or self.eof_sent: return 0 if self.out_window_size == 0: # should we block? if self.timeout == 0.0: raise socket.timeout() # loop here in case we get woken up but a different thread has # filled the buffer timeout = self.timeout while self.out_window_size == 0: if self.closed or self.eof_sent: return 0 then = time.time() self.out_buffer_cv.wait(timeout) if timeout is not None: timeout -= time.time() - then if timeout <= 0.0: raise socket.timeout() # we have some window to squeeze into if self.closed or self.eof_sent: return 0 if self.out_window_size < size: size = self.out_window_size if self.out_max_packet_size - 64 < size: size = self.out_max_packet_size - 64 self.out_window_size -= size if self.ultra_debug: self._log(DEBUG, "window down to {}".format(self.out_window_size)) return size
[ "def", "_wait_for_send_window", "(", "self", ",", "size", ")", ":", "# you are already holding the lock", "if", "self", ".", "closed", "or", "self", ".", "eof_sent", ":", "return", "0", "if", "self", ".", "out_window_size", "==", "0", ":", "# should we block?", ...
(You are already holding the lock.) Wait for the send window to open up, and allocate up to ``size`` bytes for transmission. If no space opens up before the timeout, a timeout exception is raised. Returns the number of bytes available to send (may be less than requested).
[ "(", "You", "are", "already", "holding", "the", "lock", ".", ")", "Wait", "for", "the", "send", "window", "to", "open", "up", "and", "allocate", "up", "to", "size", "bytes", "for", "transmission", ".", "If", "no", "space", "opens", "up", "before", "the...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L1278-L1315
train
paramiko/paramiko
paramiko/sftp_server.py
SFTPServer.convert_errno
def convert_errno(e): """ Convert an errno value (as from an ``OSError`` or ``IOError``) into a standard SFTP result code. This is a convenience function for trapping exceptions in server code and returning an appropriate result. :param int e: an errno code, as from ``OSError.errno``. :return: an `int` SFTP error code like ``SFTP_NO_SUCH_FILE``. """ if e == errno.EACCES: # permission denied return SFTP_PERMISSION_DENIED elif (e == errno.ENOENT) or (e == errno.ENOTDIR): # no such file return SFTP_NO_SUCH_FILE else: return SFTP_FAILURE
python
def convert_errno(e): """ Convert an errno value (as from an ``OSError`` or ``IOError``) into a standard SFTP result code. This is a convenience function for trapping exceptions in server code and returning an appropriate result. :param int e: an errno code, as from ``OSError.errno``. :return: an `int` SFTP error code like ``SFTP_NO_SUCH_FILE``. """ if e == errno.EACCES: # permission denied return SFTP_PERMISSION_DENIED elif (e == errno.ENOENT) or (e == errno.ENOTDIR): # no such file return SFTP_NO_SUCH_FILE else: return SFTP_FAILURE
[ "def", "convert_errno", "(", "e", ")", ":", "if", "e", "==", "errno", ".", "EACCES", ":", "# permission denied", "return", "SFTP_PERMISSION_DENIED", "elif", "(", "e", "==", "errno", ".", "ENOENT", ")", "or", "(", "e", "==", "errno", ".", "ENOTDIR", ")", ...
Convert an errno value (as from an ``OSError`` or ``IOError``) into a standard SFTP result code. This is a convenience function for trapping exceptions in server code and returning an appropriate result. :param int e: an errno code, as from ``OSError.errno``. :return: an `int` SFTP error code like ``SFTP_NO_SUCH_FILE``.
[ "Convert", "an", "errno", "value", "(", "as", "from", "an", "OSError", "or", "IOError", ")", "into", "a", "standard", "SFTP", "result", "code", ".", "This", "is", "a", "convenience", "function", "for", "trapping", "exceptions", "in", "server", "code", "and...
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_server.py#L180-L196
train
paramiko/paramiko
paramiko/sftp_server.py
SFTPServer._convert_pflags
def _convert_pflags(self, pflags): """convert SFTP-style open() flags to Python's os.open() flags""" if (pflags & SFTP_FLAG_READ) and (pflags & SFTP_FLAG_WRITE): flags = os.O_RDWR elif pflags & SFTP_FLAG_WRITE: flags = os.O_WRONLY else: flags = os.O_RDONLY if pflags & SFTP_FLAG_APPEND: flags |= os.O_APPEND if pflags & SFTP_FLAG_CREATE: flags |= os.O_CREAT if pflags & SFTP_FLAG_TRUNC: flags |= os.O_TRUNC if pflags & SFTP_FLAG_EXCL: flags |= os.O_EXCL return flags
python
def _convert_pflags(self, pflags): """convert SFTP-style open() flags to Python's os.open() flags""" if (pflags & SFTP_FLAG_READ) and (pflags & SFTP_FLAG_WRITE): flags = os.O_RDWR elif pflags & SFTP_FLAG_WRITE: flags = os.O_WRONLY else: flags = os.O_RDONLY if pflags & SFTP_FLAG_APPEND: flags |= os.O_APPEND if pflags & SFTP_FLAG_CREATE: flags |= os.O_CREAT if pflags & SFTP_FLAG_TRUNC: flags |= os.O_TRUNC if pflags & SFTP_FLAG_EXCL: flags |= os.O_EXCL return flags
[ "def", "_convert_pflags", "(", "self", ",", "pflags", ")", ":", "if", "(", "pflags", "&", "SFTP_FLAG_READ", ")", "and", "(", "pflags", "&", "SFTP_FLAG_WRITE", ")", ":", "flags", "=", "os", ".", "O_RDWR", "elif", "pflags", "&", "SFTP_FLAG_WRITE", ":", "fl...
convert SFTP-style open() flags to Python's os.open() flags
[ "convert", "SFTP", "-", "style", "open", "()", "flags", "to", "Python", "s", "os", ".", "open", "()", "flags" ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_server.py#L360-L376
train