id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
19,300
apache/spark
python/pyspark/mllib/random.py
RandomRDDs.gammaRDD
def gammaRDD(sc, shape, scale, size, numPartitions=None, seed=None): """ Generates an RDD comprised of i.i.d. samples from the Gamma distribution with the input shape and scale. :param sc: SparkContext used to create the RDD. :param shape: shape (> 0) parameter for the Gamma dis...
python
def gammaRDD(sc, shape, scale, size, numPartitions=None, seed=None): """ Generates an RDD comprised of i.i.d. samples from the Gamma distribution with the input shape and scale. :param sc: SparkContext used to create the RDD. :param shape: shape (> 0) parameter for the Gamma dis...
[ "def", "gammaRDD", "(", "sc", ",", "shape", ",", "scale", ",", "size", ",", "numPartitions", "=", "None", ",", "seed", "=", "None", ")", ":", "return", "callMLlibFunc", "(", "\"gammaRDD\"", ",", "sc", ".", "_jsc", ",", "float", "(", "shape", ")", ","...
Generates an RDD comprised of i.i.d. samples from the Gamma distribution with the input shape and scale. :param sc: SparkContext used to create the RDD. :param shape: shape (> 0) parameter for the Gamma distribution :param scale: scale (> 0) parameter for the Gamma distribution ...
[ "Generates", "an", "RDD", "comprised", "of", "i", ".", "i", ".", "d", ".", "samples", "from", "the", "Gamma", "distribution", "with", "the", "input", "shape", "and", "scale", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/random.py#L197-L225
19,301
apache/spark
python/pyspark/mllib/random.py
RandomRDDs.normalVectorRDD
def normalVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the standard normal distribution. :param sc: SparkContext used to create the RDD. :param numRows: Number of Vectors in the RDD...
python
def normalVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the standard normal distribution. :param sc: SparkContext used to create the RDD. :param numRows: Number of Vectors in the RDD...
[ "def", "normalVectorRDD", "(", "sc", ",", "numRows", ",", "numCols", ",", "numPartitions", "=", "None", ",", "seed", "=", "None", ")", ":", "return", "callMLlibFunc", "(", "\"normalVectorRDD\"", ",", "sc", ".", "_jsc", ",", "numRows", ",", "numCols", ",", ...
Generates an RDD comprised of vectors containing i.i.d. samples drawn from the standard normal distribution. :param sc: SparkContext used to create the RDD. :param numRows: Number of Vectors in the RDD. :param numCols: Number of elements in each Vector. :param numPartitions: Num...
[ "Generates", "an", "RDD", "comprised", "of", "vectors", "containing", "i", ".", "i", ".", "d", ".", "samples", "drawn", "from", "the", "standard", "normal", "distribution", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/random.py#L256-L277
19,302
apache/spark
python/pyspark/mllib/random.py
RandomRDDs.logNormalVectorRDD
def logNormalVectorRDD(sc, mean, std, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the log normal distribution. :param sc: SparkContext used to create the RDD. :param mean: Mean of the log normal...
python
def logNormalVectorRDD(sc, mean, std, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the log normal distribution. :param sc: SparkContext used to create the RDD. :param mean: Mean of the log normal...
[ "def", "logNormalVectorRDD", "(", "sc", ",", "mean", ",", "std", ",", "numRows", ",", "numCols", ",", "numPartitions", "=", "None", ",", "seed", "=", "None", ")", ":", "return", "callMLlibFunc", "(", "\"logNormalVectorRDD\"", ",", "sc", ".", "_jsc", ",", ...
Generates an RDD comprised of vectors containing i.i.d. samples drawn from the log normal distribution. :param sc: SparkContext used to create the RDD. :param mean: Mean of the log normal distribution :param std: Standard Deviation of the log normal distribution :param numRows: ...
[ "Generates", "an", "RDD", "comprised", "of", "vectors", "containing", "i", ".", "i", ".", "d", ".", "samples", "drawn", "from", "the", "log", "normal", "distribution", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/random.py#L282-L312
19,303
apache/spark
python/pyspark/mllib/random.py
RandomRDDs.poissonVectorRDD
def poissonVectorRDD(sc, mean, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the Poisson distribution with the input mean. :param sc: SparkContext used to create the RDD. :param mean: Mean, or lam...
python
def poissonVectorRDD(sc, mean, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the Poisson distribution with the input mean. :param sc: SparkContext used to create the RDD. :param mean: Mean, or lam...
[ "def", "poissonVectorRDD", "(", "sc", ",", "mean", ",", "numRows", ",", "numCols", ",", "numPartitions", "=", "None", ",", "seed", "=", "None", ")", ":", "return", "callMLlibFunc", "(", "\"poissonVectorRDD\"", ",", "sc", ".", "_jsc", ",", "float", "(", "...
Generates an RDD comprised of vectors containing i.i.d. samples drawn from the Poisson distribution with the input mean. :param sc: SparkContext used to create the RDD. :param mean: Mean, or lambda, for the Poisson distribution. :param numRows: Number of Vectors in the RDD. :par...
[ "Generates", "an", "RDD", "comprised", "of", "vectors", "containing", "i", ".", "i", ".", "d", ".", "samples", "drawn", "from", "the", "Poisson", "distribution", "with", "the", "input", "mean", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/random.py#L317-L343
19,304
apache/spark
python/pyspark/mllib/random.py
RandomRDDs.gammaVectorRDD
def gammaVectorRDD(sc, shape, scale, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the Gamma distribution. :param sc: SparkContext used to create the RDD. :param shape: Shape (> 0) of the Gamma di...
python
def gammaVectorRDD(sc, shape, scale, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the Gamma distribution. :param sc: SparkContext used to create the RDD. :param shape: Shape (> 0) of the Gamma di...
[ "def", "gammaVectorRDD", "(", "sc", ",", "shape", ",", "scale", ",", "numRows", ",", "numCols", ",", "numPartitions", "=", "None", ",", "seed", "=", "None", ")", ":", "return", "callMLlibFunc", "(", "\"gammaVectorRDD\"", ",", "sc", ".", "_jsc", ",", "flo...
Generates an RDD comprised of vectors containing i.i.d. samples drawn from the Gamma distribution. :param sc: SparkContext used to create the RDD. :param shape: Shape (> 0) of the Gamma distribution :param scale: Scale (> 0) of the Gamma distribution :param numRows: Number of Ve...
[ "Generates", "an", "RDD", "comprised", "of", "vectors", "containing", "i", ".", "i", ".", "d", ".", "samples", "drawn", "from", "the", "Gamma", "distribution", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/random.py#L379-L408
19,305
apache/spark
python/pyspark/sql/session.py
SparkSession.conf
def conf(self): """Runtime configuration interface for Spark. This is the interface through which the user can get and set all Spark and Hadoop configurations that are relevant to Spark SQL. When getting the value of a config, this defaults to the value set in the underlying :class:`Spa...
python
def conf(self): """Runtime configuration interface for Spark. This is the interface through which the user can get and set all Spark and Hadoop configurations that are relevant to Spark SQL. When getting the value of a config, this defaults to the value set in the underlying :class:`Spa...
[ "def", "conf", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_conf\"", ")", ":", "self", ".", "_conf", "=", "RuntimeConfig", "(", "self", ".", "_jsparkSession", ".", "conf", "(", ")", ")", "return", "self", ".", "_conf" ]
Runtime configuration interface for Spark. This is the interface through which the user can get and set all Spark and Hadoop configurations that are relevant to Spark SQL. When getting the value of a config, this defaults to the value set in the underlying :class:`SparkContext`, if any.
[ "Runtime", "configuration", "interface", "for", "Spark", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/session.py#L298-L307
19,306
apache/spark
python/pyspark/sql/session.py
SparkSession.catalog
def catalog(self): """Interface through which the user may create, drop, alter or query underlying databases, tables, functions etc. :return: :class:`Catalog` """ from pyspark.sql.catalog import Catalog if not hasattr(self, "_catalog"): self._catalog = Catalo...
python
def catalog(self): """Interface through which the user may create, drop, alter or query underlying databases, tables, functions etc. :return: :class:`Catalog` """ from pyspark.sql.catalog import Catalog if not hasattr(self, "_catalog"): self._catalog = Catalo...
[ "def", "catalog", "(", "self", ")", ":", "from", "pyspark", ".", "sql", ".", "catalog", "import", "Catalog", "if", "not", "hasattr", "(", "self", ",", "\"_catalog\"", ")", ":", "self", ".", "_catalog", "=", "Catalog", "(", "self", ")", "return", "self"...
Interface through which the user may create, drop, alter or query underlying databases, tables, functions etc. :return: :class:`Catalog`
[ "Interface", "through", "which", "the", "user", "may", "create", "drop", "alter", "or", "query", "underlying", "databases", "tables", "functions", "etc", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/session.py#L311-L320
19,307
apache/spark
python/pyspark/sql/session.py
SparkSession._inferSchemaFromList
def _inferSchemaFromList(self, data, names=None): """ Infer schema from list of Row or tuple. :param data: list of Row or tuple :param names: list of column names :return: :class:`pyspark.sql.types.StructType` """ if not data: raise ValueError("can no...
python
def _inferSchemaFromList(self, data, names=None): """ Infer schema from list of Row or tuple. :param data: list of Row or tuple :param names: list of column names :return: :class:`pyspark.sql.types.StructType` """ if not data: raise ValueError("can no...
[ "def", "_inferSchemaFromList", "(", "self", ",", "data", ",", "names", "=", "None", ")", ":", "if", "not", "data", ":", "raise", "ValueError", "(", "\"can not infer schema from empty dataset\"", ")", "first", "=", "data", "[", "0", "]", "if", "type", "(", ...
Infer schema from list of Row or tuple. :param data: list of Row or tuple :param names: list of column names :return: :class:`pyspark.sql.types.StructType`
[ "Infer", "schema", "from", "list", "of", "Row", "or", "tuple", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/session.py#L363-L380
19,308
apache/spark
python/pyspark/sql/session.py
SparkSession._inferSchema
def _inferSchema(self, rdd, samplingRatio=None, names=None): """ Infer schema from an RDD of Row or tuple. :param rdd: an RDD of Row or tuple :param samplingRatio: sampling ratio, or no sampling (default) :return: :class:`pyspark.sql.types.StructType` """ first =...
python
def _inferSchema(self, rdd, samplingRatio=None, names=None): """ Infer schema from an RDD of Row or tuple. :param rdd: an RDD of Row or tuple :param samplingRatio: sampling ratio, or no sampling (default) :return: :class:`pyspark.sql.types.StructType` """ first =...
[ "def", "_inferSchema", "(", "self", ",", "rdd", ",", "samplingRatio", "=", "None", ",", "names", "=", "None", ")", ":", "first", "=", "rdd", ".", "first", "(", ")", "if", "not", "first", ":", "raise", "ValueError", "(", "\"The first row in RDD is empty, \"...
Infer schema from an RDD of Row or tuple. :param rdd: an RDD of Row or tuple :param samplingRatio: sampling ratio, or no sampling (default) :return: :class:`pyspark.sql.types.StructType`
[ "Infer", "schema", "from", "an", "RDD", "of", "Row", "or", "tuple", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/session.py#L382-L412
19,309
apache/spark
python/pyspark/sql/session.py
SparkSession._createFromRDD
def _createFromRDD(self, rdd, schema, samplingRatio): """ Create an RDD for DataFrame from an existing RDD, returns the RDD and schema. """ if schema is None or isinstance(schema, (list, tuple)): struct = self._inferSchema(rdd, samplingRatio, names=schema) convert...
python
def _createFromRDD(self, rdd, schema, samplingRatio): """ Create an RDD for DataFrame from an existing RDD, returns the RDD and schema. """ if schema is None or isinstance(schema, (list, tuple)): struct = self._inferSchema(rdd, samplingRatio, names=schema) convert...
[ "def", "_createFromRDD", "(", "self", ",", "rdd", ",", "schema", ",", "samplingRatio", ")", ":", "if", "schema", "is", "None", "or", "isinstance", "(", "schema", ",", "(", "list", ",", "tuple", ")", ")", ":", "struct", "=", "self", ".", "_inferSchema",...
Create an RDD for DataFrame from an existing RDD, returns the RDD and schema.
[ "Create", "an", "RDD", "for", "DataFrame", "from", "an", "existing", "RDD", "returns", "the", "RDD", "and", "schema", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/session.py#L414-L433
19,310
apache/spark
python/pyspark/sql/session.py
SparkSession._createFromLocal
def _createFromLocal(self, data, schema): """ Create an RDD for DataFrame from a list or pandas.DataFrame, returns the RDD and schema. """ # make sure data could consumed multiple times if not isinstance(data, list): data = list(data) if schema is Non...
python
def _createFromLocal(self, data, schema): """ Create an RDD for DataFrame from a list or pandas.DataFrame, returns the RDD and schema. """ # make sure data could consumed multiple times if not isinstance(data, list): data = list(data) if schema is Non...
[ "def", "_createFromLocal", "(", "self", ",", "data", ",", "schema", ")", ":", "# make sure data could consumed multiple times", "if", "not", "isinstance", "(", "data", ",", "list", ")", ":", "data", "=", "list", "(", "data", ")", "if", "schema", "is", "None"...
Create an RDD for DataFrame from a list or pandas.DataFrame, returns the RDD and schema.
[ "Create", "an", "RDD", "for", "DataFrame", "from", "a", "list", "or", "pandas", ".", "DataFrame", "returns", "the", "RDD", "and", "schema", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/session.py#L435-L459
19,311
apache/spark
python/pyspark/sql/session.py
SparkSession._create_from_pandas_with_arrow
def _create_from_pandas_with_arrow(self, pdf, schema, timezone): """ Create a DataFrame from a given pandas.DataFrame by slicing it into partitions, converting to Arrow data, then sending to the JVM to parallelize. If a schema is passed in, the data types will be used to coerce the data ...
python
def _create_from_pandas_with_arrow(self, pdf, schema, timezone): """ Create a DataFrame from a given pandas.DataFrame by slicing it into partitions, converting to Arrow data, then sending to the JVM to parallelize. If a schema is passed in, the data types will be used to coerce the data ...
[ "def", "_create_from_pandas_with_arrow", "(", "self", ",", "pdf", ",", "schema", ",", "timezone", ")", ":", "from", "pyspark", ".", "serializers", "import", "ArrowStreamPandasSerializer", "from", "pyspark", ".", "sql", ".", "types", "import", "from_arrow_type", ",...
Create a DataFrame from a given pandas.DataFrame by slicing it into partitions, converting to Arrow data, then sending to the JVM to parallelize. If a schema is passed in, the data types will be used to coerce the data in Pandas to Arrow conversion.
[ "Create", "a", "DataFrame", "from", "a", "given", "pandas", ".", "DataFrame", "by", "slicing", "it", "into", "partitions", "converting", "to", "Arrow", "data", "then", "sending", "to", "the", "JVM", "to", "parallelize", ".", "If", "a", "schema", "is", "pas...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/session.py#L527-L588
19,312
apache/spark
python/pyspark/sql/session.py
SparkSession._create_shell_session
def _create_shell_session(): """ Initialize a SparkSession for a pyspark shell session. This is called from shell.py to make error handling simpler without needing to declare local variables in that script, which would expose those to users. """ import py4j from p...
python
def _create_shell_session(): """ Initialize a SparkSession for a pyspark shell session. This is called from shell.py to make error handling simpler without needing to declare local variables in that script, which would expose those to users. """ import py4j from p...
[ "def", "_create_shell_session", "(", ")", ":", "import", "py4j", "from", "pyspark", ".", "conf", "import", "SparkConf", "from", "pyspark", ".", "context", "import", "SparkContext", "try", ":", "# Try to access HiveConf, it will raise exception if Hive is not added", "conf...
Initialize a SparkSession for a pyspark shell session. This is called from shell.py to make error handling simpler without needing to declare local variables in that script, which would expose those to users.
[ "Initialize", "a", "SparkSession", "for", "a", "pyspark", "shell", "session", ".", "This", "is", "called", "from", "shell", ".", "py", "to", "make", "error", "handling", "simpler", "without", "needing", "to", "declare", "local", "variables", "in", "that", "s...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/session.py#L591-L615
19,313
apache/spark
python/pyspark/serializers.py
_restore
def _restore(name, fields, value): """ Restore an object of namedtuple""" k = (name, fields) cls = __cls.get(k) if cls is None: cls = collections.namedtuple(name, fields) __cls[k] = cls return cls(*value)
python
def _restore(name, fields, value): """ Restore an object of namedtuple""" k = (name, fields) cls = __cls.get(k) if cls is None: cls = collections.namedtuple(name, fields) __cls[k] = cls return cls(*value)
[ "def", "_restore", "(", "name", ",", "fields", ",", "value", ")", ":", "k", "=", "(", "name", ",", "fields", ")", "cls", "=", "__cls", ".", "get", "(", "k", ")", "if", "cls", "is", "None", ":", "cls", "=", "collections", ".", "namedtuple", "(", ...
Restore an object of namedtuple
[ "Restore", "an", "object", "of", "namedtuple" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/serializers.py#L578-L585
19,314
apache/spark
python/pyspark/serializers.py
_hack_namedtuple
def _hack_namedtuple(cls): """ Make class generated by namedtuple picklable """ name = cls.__name__ fields = cls._fields def __reduce__(self): return (_restore, (name, fields, tuple(self))) cls.__reduce__ = __reduce__ cls._is_namedtuple_ = True return cls
python
def _hack_namedtuple(cls): """ Make class generated by namedtuple picklable """ name = cls.__name__ fields = cls._fields def __reduce__(self): return (_restore, (name, fields, tuple(self))) cls.__reduce__ = __reduce__ cls._is_namedtuple_ = True return cls
[ "def", "_hack_namedtuple", "(", "cls", ")", ":", "name", "=", "cls", ".", "__name__", "fields", "=", "cls", ".", "_fields", "def", "__reduce__", "(", "self", ")", ":", "return", "(", "_restore", ",", "(", "name", ",", "fields", ",", "tuple", "(", "se...
Make class generated by namedtuple picklable
[ "Make", "class", "generated", "by", "namedtuple", "picklable" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/serializers.py#L588-L597
19,315
apache/spark
python/pyspark/serializers.py
ArrowCollectSerializer.load_stream
def load_stream(self, stream): """ Load a stream of un-ordered Arrow RecordBatches, where the last iteration yields a list of indices that can be used to put the RecordBatches in the correct order. """ # load the batches for batch in self.serializer.load_stream(stream): ...
python
def load_stream(self, stream): """ Load a stream of un-ordered Arrow RecordBatches, where the last iteration yields a list of indices that can be used to put the RecordBatches in the correct order. """ # load the batches for batch in self.serializer.load_stream(stream): ...
[ "def", "load_stream", "(", "self", ",", "stream", ")", ":", "# load the batches", "for", "batch", "in", "self", ".", "serializer", ".", "load_stream", "(", "stream", ")", ":", "yield", "batch", "# load the batch order indices", "num", "=", "read_int", "(", "st...
Load a stream of un-ordered Arrow RecordBatches, where the last iteration yields a list of indices that can be used to put the RecordBatches in the correct order.
[ "Load", "a", "stream", "of", "un", "-", "ordered", "Arrow", "RecordBatches", "where", "the", "last", "iteration", "yields", "a", "list", "of", "indices", "that", "can", "be", "used", "to", "put", "the", "RecordBatches", "in", "the", "correct", "order", "."...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/serializers.py#L200-L215
19,316
apache/spark
python/pyspark/serializers.py
ArrowStreamPandasSerializer._create_batch
def _create_batch(self, series): """ Create an Arrow record batch from the given pandas.Series or list of Series, with optional type. :param series: A single pandas.Series, list of Series, or list of (series, arrow_type) :return: Arrow RecordBatch """ import pand...
python
def _create_batch(self, series): """ Create an Arrow record batch from the given pandas.Series or list of Series, with optional type. :param series: A single pandas.Series, list of Series, or list of (series, arrow_type) :return: Arrow RecordBatch """ import pand...
[ "def", "_create_batch", "(", "self", ",", "series", ")", ":", "import", "pandas", "as", "pd", "import", "pyarrow", "as", "pa", "from", "pyspark", ".", "sql", ".", "types", "import", "_check_series_convert_timestamps_internal", "# Make input conform to [(series1, type1...
Create an Arrow record batch from the given pandas.Series or list of Series, with optional type. :param series: A single pandas.Series, list of Series, or list of (series, arrow_type) :return: Arrow RecordBatch
[ "Create", "an", "Arrow", "record", "batch", "from", "the", "given", "pandas", ".", "Series", "or", "list", "of", "Series", "with", "optional", "type", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/serializers.py#L274-L335
19,317
apache/spark
python/pyspark/serializers.py
ArrowStreamPandasSerializer.dump_stream
def dump_stream(self, iterator, stream): """ Make ArrowRecordBatches from Pandas Series and serialize. Input is a single series or a list of series accompanied by an optional pyarrow type to coerce the data to. """ batches = (self._create_batch(series) for series in iterator) ...
python
def dump_stream(self, iterator, stream): """ Make ArrowRecordBatches from Pandas Series and serialize. Input is a single series or a list of series accompanied by an optional pyarrow type to coerce the data to. """ batches = (self._create_batch(series) for series in iterator) ...
[ "def", "dump_stream", "(", "self", ",", "iterator", ",", "stream", ")", ":", "batches", "=", "(", "self", ".", "_create_batch", "(", "series", ")", "for", "series", "in", "iterator", ")", "super", "(", "ArrowStreamPandasSerializer", ",", "self", ")", ".", ...
Make ArrowRecordBatches from Pandas Series and serialize. Input is a single series or a list of series accompanied by an optional pyarrow type to coerce the data to.
[ "Make", "ArrowRecordBatches", "from", "Pandas", "Series", "and", "serialize", ".", "Input", "is", "a", "single", "series", "or", "a", "list", "of", "series", "accompanied", "by", "an", "optional", "pyarrow", "type", "to", "coerce", "the", "data", "to", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/serializers.py#L337-L343
19,318
apache/spark
python/pyspark/serializers.py
ArrowStreamPandasSerializer.load_stream
def load_stream(self, stream): """ Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series. """ batches = super(ArrowStreamPandasSerializer, self).load_stream(stream) import pyarrow as pa for batch in batches: yield [self.arrow_t...
python
def load_stream(self, stream): """ Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series. """ batches = super(ArrowStreamPandasSerializer, self).load_stream(stream) import pyarrow as pa for batch in batches: yield [self.arrow_t...
[ "def", "load_stream", "(", "self", ",", "stream", ")", ":", "batches", "=", "super", "(", "ArrowStreamPandasSerializer", ",", "self", ")", ".", "load_stream", "(", "stream", ")", "import", "pyarrow", "as", "pa", "for", "batch", "in", "batches", ":", "yield...
Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series.
[ "Deserialize", "ArrowRecordBatches", "to", "an", "Arrow", "table", "and", "return", "as", "a", "list", "of", "pandas", ".", "Series", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/serializers.py#L345-L352
19,319
apache/spark
python/pyspark/serializers.py
ArrowStreamPandasUDFSerializer.dump_stream
def dump_stream(self, iterator, stream): """ Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent. This should be sent after creating the first record batch so in case of an error, it can be sent back to the JVM before the Arrow stream starts. ...
python
def dump_stream(self, iterator, stream): """ Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent. This should be sent after creating the first record batch so in case of an error, it can be sent back to the JVM before the Arrow stream starts. ...
[ "def", "dump_stream", "(", "self", ",", "iterator", ",", "stream", ")", ":", "def", "init_stream_yield_batches", "(", ")", ":", "should_write_start_length", "=", "True", "for", "series", "in", "iterator", ":", "batch", "=", "self", ".", "_create_batch", "(", ...
Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent. This should be sent after creating the first record batch so in case of an error, it can be sent back to the JVM before the Arrow stream starts.
[ "Override", "because", "Pandas", "UDFs", "require", "a", "START_ARROW_STREAM", "before", "the", "Arrow", "stream", "is", "sent", ".", "This", "should", "be", "sent", "after", "creating", "the", "first", "record", "batch", "so", "in", "case", "of", "an", "err...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/serializers.py#L381-L397
19,320
apache/spark
python/pyspark/sql/streaming.py
DataStreamWriter.trigger
def trigger(self, processingTime=None, once=None, continuous=None): """Set the trigger for the stream query. If this is not set it will run the query as fast as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``. .. note:: Evolving. :param processing...
python
def trigger(self, processingTime=None, once=None, continuous=None): """Set the trigger for the stream query. If this is not set it will run the query as fast as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``. .. note:: Evolving. :param processing...
[ "def", "trigger", "(", "self", ",", "processingTime", "=", "None", ",", "once", "=", "None", ",", "continuous", "=", "None", ")", ":", "params", "=", "[", "processingTime", ",", "once", ",", "continuous", "]", "if", "params", ".", "count", "(", "None",...
Set the trigger for the stream query. If this is not set it will run the query as fast as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``. .. note:: Evolving. :param processingTime: a processing time interval as a string, e.g. '5 seconds', '1 minute'. ...
[ "Set", "the", "trigger", "for", "the", "stream", "query", ".", "If", "this", "is", "not", "set", "it", "will", "run", "the", "query", "as", "fast", "as", "possible", "which", "is", "equivalent", "to", "setting", "the", "trigger", "to", "processingTime", ...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/streaming.py#L829-L878
19,321
apache/spark
python/pyspark/sql/streaming.py
DataStreamWriter.foreach
def foreach(self, f): """ Sets the output of the streaming query to be processed using the provided writer ``f``. This is often used to write the output of a streaming query to arbitrary storage systems. The processing logic can be specified in two ways. #. A **function** that t...
python
def foreach(self, f): """ Sets the output of the streaming query to be processed using the provided writer ``f``. This is often used to write the output of a streaming query to arbitrary storage systems. The processing logic can be specified in two ways. #. A **function** that t...
[ "def", "foreach", "(", "self", ",", "f", ")", ":", "from", "pyspark", ".", "rdd", "import", "_wrap_function", "from", "pyspark", ".", "serializers", "import", "PickleSerializer", ",", "AutoBatchedSerializer", "from", "pyspark", ".", "taskcontext", "import", "Tas...
Sets the output of the streaming query to be processed using the provided writer ``f``. This is often used to write the output of a streaming query to arbitrary storage systems. The processing logic can be specified in two ways. #. A **function** that takes a row as input. This is a...
[ "Sets", "the", "output", "of", "the", "streaming", "query", "to", "be", "processed", "using", "the", "provided", "writer", "f", ".", "This", "is", "often", "used", "to", "write", "the", "output", "of", "a", "streaming", "query", "to", "arbitrary", "storage...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/streaming.py#L881-L1040
19,322
apache/spark
python/pyspark/cloudpickle.py
dumps
def dumps(obj, protocol=None): """Serialize obj as a string of bytes allocated in memory protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed between processes running the same Python version. Set protocol=p...
python
def dumps(obj, protocol=None): """Serialize obj as a string of bytes allocated in memory protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed between processes running the same Python version. Set protocol=p...
[ "def", "dumps", "(", "obj", ",", "protocol", "=", "None", ")", ":", "file", "=", "StringIO", "(", ")", "try", ":", "cp", "=", "CloudPickler", "(", "file", ",", "protocol", "=", "protocol", ")", "cp", ".", "dump", "(", "obj", ")", "return", "file", ...
Serialize obj as a string of bytes allocated in memory protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed between processes running the same Python version. Set protocol=pickle.DEFAULT_PROTOCOL instead if you ...
[ "Serialize", "obj", "as", "a", "string", "of", "bytes", "allocated", "in", "memory" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/cloudpickle.py#L939-L955
19,323
apache/spark
python/pyspark/cloudpickle.py
_fill_function
def _fill_function(*args): """Fills in the rest of function data into the skeleton function object The skeleton itself is create by _make_skel_func(). """ if len(args) == 2: func = args[0] state = args[1] elif len(args) == 5: # Backwards compat for cloudpickle v0.4.0, after ...
python
def _fill_function(*args): """Fills in the rest of function data into the skeleton function object The skeleton itself is create by _make_skel_func(). """ if len(args) == 2: func = args[0] state = args[1] elif len(args) == 5: # Backwards compat for cloudpickle v0.4.0, after ...
[ "def", "_fill_function", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "func", "=", "args", "[", "0", "]", "state", "=", "args", "[", "1", "]", "elif", "len", "(", "args", ")", "==", "5", ":", "# Backwards compat for ...
Fills in the rest of function data into the skeleton function object The skeleton itself is create by _make_skel_func().
[ "Fills", "in", "the", "rest", "of", "function", "data", "into", "the", "skeleton", "function", "object" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/cloudpickle.py#L1060-L1113
19,324
apache/spark
python/pyspark/cloudpickle.py
_is_dynamic
def _is_dynamic(module): """ Return True if the module is special module that cannot be imported by its name. """ # Quick check: module that have __file__ attribute are not dynamic modules. if hasattr(module, '__file__'): return False if hasattr(module, '__spec__'): return m...
python
def _is_dynamic(module): """ Return True if the module is special module that cannot be imported by its name. """ # Quick check: module that have __file__ attribute are not dynamic modules. if hasattr(module, '__file__'): return False if hasattr(module, '__spec__'): return m...
[ "def", "_is_dynamic", "(", "module", ")", ":", "# Quick check: module that have __file__ attribute are not dynamic modules.", "if", "hasattr", "(", "module", ",", "'__file__'", ")", ":", "return", "False", "if", "hasattr", "(", "module", ",", "'__spec__'", ")", ":", ...
Return True if the module is special module that cannot be imported by its name.
[ "Return", "True", "if", "the", "module", "is", "special", "module", "that", "cannot", "be", "imported", "by", "its", "name", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/cloudpickle.py#L1164-L1188
19,325
apache/spark
python/pyspark/cloudpickle.py
CloudPickler.save_function
def save_function(self, obj, name=None): """ Registered with the dispatch to handle all function types. Determines what kind of function obj is (e.g. lambda, defined at interactive prompt, etc) and handles the pickling appropriately. """ try: should_special_case = ob...
python
def save_function(self, obj, name=None): """ Registered with the dispatch to handle all function types. Determines what kind of function obj is (e.g. lambda, defined at interactive prompt, etc) and handles the pickling appropriately. """ try: should_special_case = ob...
[ "def", "save_function", "(", "self", ",", "obj", ",", "name", "=", "None", ")", ":", "try", ":", "should_special_case", "=", "obj", "in", "_BUILTIN_TYPE_CONSTRUCTORS", "except", "TypeError", ":", "# Methods of builtin types aren't hashable in python 2.", "should_special...
Registered with the dispatch to handle all function types. Determines what kind of function obj is (e.g. lambda, defined at interactive prompt, etc) and handles the pickling appropriately.
[ "Registered", "with", "the", "dispatch", "to", "handle", "all", "function", "types", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/cloudpickle.py#L319-L412
19,326
apache/spark
python/pyspark/cloudpickle.py
CloudPickler.save_inst
def save_inst(self, obj): """Inner logic to save instance. Based off pickle.save_inst""" cls = obj.__class__ # Try the dispatch table (pickle module doesn't do it) f = self.dispatch.get(cls) if f: f(self, obj) # Call unbound method with explicit self ret...
python
def save_inst(self, obj): """Inner logic to save instance. Based off pickle.save_inst""" cls = obj.__class__ # Try the dispatch table (pickle module doesn't do it) f = self.dispatch.get(cls) if f: f(self, obj) # Call unbound method with explicit self ret...
[ "def", "save_inst", "(", "self", ",", "obj", ")", ":", "cls", "=", "obj", ".", "__class__", "# Try the dispatch table (pickle module doesn't do it)", "f", "=", "self", ".", "dispatch", ".", "get", "(", "cls", ")", "if", "f", ":", "f", "(", "self", ",", "...
Inner logic to save instance. Based off pickle.save_inst
[ "Inner", "logic", "to", "save", "instance", ".", "Based", "off", "pickle", ".", "save_inst" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/cloudpickle.py#L725-L768
19,327
apache/spark
python/pyspark/ml/param/__init__.py
Param._copy_new_parent
def _copy_new_parent(self, parent): """Copy the current param to a new parent, must be a dummy param.""" if self.parent == "undefined": param = copy.copy(self) param.parent = parent.uid return param else: raise ValueError("Cannot copy from non-dumm...
python
def _copy_new_parent(self, parent): """Copy the current param to a new parent, must be a dummy param.""" if self.parent == "undefined": param = copy.copy(self) param.parent = parent.uid return param else: raise ValueError("Cannot copy from non-dumm...
[ "def", "_copy_new_parent", "(", "self", ",", "parent", ")", ":", "if", "self", ".", "parent", "==", "\"undefined\"", ":", "param", "=", "copy", ".", "copy", "(", "self", ")", "param", ".", "parent", "=", "parent", ".", "uid", "return", "param", "else",...
Copy the current param to a new parent, must be a dummy param.
[ "Copy", "the", "current", "param", "to", "a", "new", "parent", "must", "be", "a", "dummy", "param", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L52-L59
19,328
apache/spark
python/pyspark/ml/param/__init__.py
TypeConverters.toList
def toList(value): """ Convert a value to a list, if possible. """ if type(value) == list: return value elif type(value) in [np.ndarray, tuple, xrange, array.array]: return list(value) elif isinstance(value, Vector): return list(value.t...
python
def toList(value): """ Convert a value to a list, if possible. """ if type(value) == list: return value elif type(value) in [np.ndarray, tuple, xrange, array.array]: return list(value) elif isinstance(value, Vector): return list(value.t...
[ "def", "toList", "(", "value", ")", ":", "if", "type", "(", "value", ")", "==", "list", ":", "return", "value", "elif", "type", "(", "value", ")", "in", "[", "np", ".", "ndarray", ",", "tuple", ",", "xrange", ",", "array", ".", "array", "]", ":",...
Convert a value to a list, if possible.
[ "Convert", "a", "value", "to", "a", "list", "if", "possible", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L113-L124
19,329
apache/spark
python/pyspark/ml/param/__init__.py
TypeConverters.toListFloat
def toListFloat(value): """ Convert a value to list of floats, if possible. """ if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._is_numeric(v), value)): return [float(v) for v ...
python
def toListFloat(value): """ Convert a value to list of floats, if possible. """ if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._is_numeric(v), value)): return [float(v) for v ...
[ "def", "toListFloat", "(", "value", ")", ":", "if", "TypeConverters", ".", "_can_convert_to_list", "(", "value", ")", ":", "value", "=", "TypeConverters", ".", "toList", "(", "value", ")", "if", "all", "(", "map", "(", "lambda", "v", ":", "TypeConverters",...
Convert a value to list of floats, if possible.
[ "Convert", "a", "value", "to", "list", "of", "floats", "if", "possible", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L127-L135
19,330
apache/spark
python/pyspark/ml/param/__init__.py
TypeConverters.toListInt
def toListInt(value): """ Convert a value to list of ints, if possible. """ if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._is_integer(v), value)): return [int(v) for v in val...
python
def toListInt(value): """ Convert a value to list of ints, if possible. """ if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._is_integer(v), value)): return [int(v) for v in val...
[ "def", "toListInt", "(", "value", ")", ":", "if", "TypeConverters", ".", "_can_convert_to_list", "(", "value", ")", ":", "value", "=", "TypeConverters", ".", "toList", "(", "value", ")", "if", "all", "(", "map", "(", "lambda", "v", ":", "TypeConverters", ...
Convert a value to list of ints, if possible.
[ "Convert", "a", "value", "to", "list", "of", "ints", "if", "possible", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L138-L146
19,331
apache/spark
python/pyspark/ml/param/__init__.py
TypeConverters.toListString
def toListString(value): """ Convert a value to list of strings, if possible. """ if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._can_convert_to_string(v), value)): return [Ty...
python
def toListString(value): """ Convert a value to list of strings, if possible. """ if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._can_convert_to_string(v), value)): return [Ty...
[ "def", "toListString", "(", "value", ")", ":", "if", "TypeConverters", ".", "_can_convert_to_list", "(", "value", ")", ":", "value", "=", "TypeConverters", ".", "toList", "(", "value", ")", "if", "all", "(", "map", "(", "lambda", "v", ":", "TypeConverters"...
Convert a value to list of strings, if possible.
[ "Convert", "a", "value", "to", "list", "of", "strings", "if", "possible", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L149-L157
19,332
apache/spark
python/pyspark/ml/param/__init__.py
TypeConverters.toVector
def toVector(value): """ Convert a value to a MLlib Vector, if possible. """ if isinstance(value, Vector): return value elif TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._i...
python
def toVector(value): """ Convert a value to a MLlib Vector, if possible. """ if isinstance(value, Vector): return value elif TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._i...
[ "def", "toVector", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Vector", ")", ":", "return", "value", "elif", "TypeConverters", ".", "_can_convert_to_list", "(", "value", ")", ":", "value", "=", "TypeConverters", ".", "toList", "(", "val...
Convert a value to a MLlib Vector, if possible.
[ "Convert", "a", "value", "to", "a", "MLlib", "Vector", "if", "possible", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L160-L170
19,333
apache/spark
python/pyspark/ml/param/__init__.py
TypeConverters.toString
def toString(value): """ Convert a value to a string, if possible. """ if isinstance(value, basestring): return value elif type(value) in [np.string_, np.str_]: return str(value) elif type(value) == np.unicode_: return unicode(value) ...
python
def toString(value): """ Convert a value to a string, if possible. """ if isinstance(value, basestring): return value elif type(value) in [np.string_, np.str_]: return str(value) elif type(value) == np.unicode_: return unicode(value) ...
[ "def", "toString", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "return", "value", "elif", "type", "(", "value", ")", "in", "[", "np", ".", "string_", ",", "np", ".", "str_", "]", ":", "return", "str", "(",...
Convert a value to a string, if possible.
[ "Convert", "a", "value", "to", "a", "string", "if", "possible", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L202-L213
19,334
apache/spark
python/pyspark/ml/param/__init__.py
Params._copy_params
def _copy_params(self): """ Copy all params defined on the class to current object. """ cls = type(self) src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)] src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs)) for name, ...
python
def _copy_params(self): """ Copy all params defined on the class to current object. """ cls = type(self) src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)] src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs)) for name, ...
[ "def", "_copy_params", "(", "self", ")", ":", "cls", "=", "type", "(", "self", ")", "src_name_attrs", "=", "[", "(", "x", ",", "getattr", "(", "cls", ",", "x", ")", ")", "for", "x", "in", "dir", "(", "cls", ")", "]", "src_params", "=", "list", ...
Copy all params defined on the class to current object.
[ "Copy", "all", "params", "defined", "on", "the", "class", "to", "current", "object", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L250-L258
19,335
apache/spark
python/pyspark/ml/param/__init__.py
Params.explainParam
def explainParam(self, param): """ Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string. """ param = self._resolveParam(param) values = [] if self.isDefined(param): if param in self._defaultP...
python
def explainParam(self, param): """ Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string. """ param = self._resolveParam(param) values = [] if self.isDefined(param): if param in self._defaultP...
[ "def", "explainParam", "(", "self", ",", "param", ")", ":", "param", "=", "self", ".", "_resolveParam", "(", "param", ")", "values", "=", "[", "]", "if", "self", ".", "isDefined", "(", "param", ")", ":", "if", "param", "in", "self", ".", "_defaultPar...
Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.
[ "Explains", "a", "single", "param", "and", "returns", "its", "name", "doc", "and", "optional", "default", "value", "and", "user", "-", "supplied", "value", "in", "a", "string", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L273-L288
19,336
apache/spark
python/pyspark/ml/param/__init__.py
Params.getParam
def getParam(self, paramName): """ Gets a param by its name. """ param = getattr(self, paramName) if isinstance(param, Param): return param else: raise ValueError("Cannot find param with name %s." % paramName)
python
def getParam(self, paramName): """ Gets a param by its name. """ param = getattr(self, paramName) if isinstance(param, Param): return param else: raise ValueError("Cannot find param with name %s." % paramName)
[ "def", "getParam", "(", "self", ",", "paramName", ")", ":", "param", "=", "getattr", "(", "self", ",", "paramName", ")", "if", "isinstance", "(", "param", ",", "Param", ")", ":", "return", "param", "else", ":", "raise", "ValueError", "(", "\"Cannot find ...
Gets a param by its name.
[ "Gets", "a", "param", "by", "its", "name", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L297-L305
19,337
apache/spark
python/pyspark/ml/param/__init__.py
Params.isSet
def isSet(self, param): """ Checks whether a param is explicitly set by user. """ param = self._resolveParam(param) return param in self._paramMap
python
def isSet(self, param): """ Checks whether a param is explicitly set by user. """ param = self._resolveParam(param) return param in self._paramMap
[ "def", "isSet", "(", "self", ",", "param", ")", ":", "param", "=", "self", ".", "_resolveParam", "(", "param", ")", "return", "param", "in", "self", ".", "_paramMap" ]
Checks whether a param is explicitly set by user.
[ "Checks", "whether", "a", "param", "is", "explicitly", "set", "by", "user", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L307-L312
19,338
apache/spark
python/pyspark/ml/param/__init__.py
Params.hasDefault
def hasDefault(self, param): """ Checks whether a param has a default value. """ param = self._resolveParam(param) return param in self._defaultParamMap
python
def hasDefault(self, param): """ Checks whether a param has a default value. """ param = self._resolveParam(param) return param in self._defaultParamMap
[ "def", "hasDefault", "(", "self", ",", "param", ")", ":", "param", "=", "self", ".", "_resolveParam", "(", "param", ")", "return", "param", "in", "self", ".", "_defaultParamMap" ]
Checks whether a param has a default value.
[ "Checks", "whether", "a", "param", "has", "a", "default", "value", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L314-L319
19,339
apache/spark
python/pyspark/ml/param/__init__.py
Params.getOrDefault
def getOrDefault(self, param): """ Gets the value of a param in the user-supplied param map or its default value. Raises an error if neither is set. """ param = self._resolveParam(param) if param in self._paramMap: return self._paramMap[param] else: ...
python
def getOrDefault(self, param): """ Gets the value of a param in the user-supplied param map or its default value. Raises an error if neither is set. """ param = self._resolveParam(param) if param in self._paramMap: return self._paramMap[param] else: ...
[ "def", "getOrDefault", "(", "self", ",", "param", ")", ":", "param", "=", "self", ".", "_resolveParam", "(", "param", ")", "if", "param", "in", "self", ".", "_paramMap", ":", "return", "self", ".", "_paramMap", "[", "param", "]", "else", ":", "return",...
Gets the value of a param in the user-supplied param map or its default value. Raises an error if neither is set.
[ "Gets", "the", "value", "of", "a", "param", "in", "the", "user", "-", "supplied", "param", "map", "or", "its", "default", "value", ".", "Raises", "an", "error", "if", "neither", "is", "set", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L339-L348
19,340
apache/spark
python/pyspark/ml/param/__init__.py
Params.set
def set(self, param, value): """ Sets a parameter in the embedded param map. """ self._shouldOwn(param) try: value = param.typeConverter(value) except ValueError as e: raise ValueError('Invalid param value given for param "%s". %s' % (param.name, e...
python
def set(self, param, value): """ Sets a parameter in the embedded param map. """ self._shouldOwn(param) try: value = param.typeConverter(value) except ValueError as e: raise ValueError('Invalid param value given for param "%s". %s' % (param.name, e...
[ "def", "set", "(", "self", ",", "param", ",", "value", ")", ":", "self", ".", "_shouldOwn", "(", "param", ")", "try", ":", "value", "=", "param", ".", "typeConverter", "(", "value", ")", "except", "ValueError", "as", "e", ":", "raise", "ValueError", ...
Sets a parameter in the embedded param map.
[ "Sets", "a", "parameter", "in", "the", "embedded", "param", "map", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L387-L396
19,341
apache/spark
python/pyspark/ml/param/__init__.py
Params._shouldOwn
def _shouldOwn(self, param): """ Validates that the input param belongs to this Params instance. """ if not (self.uid == param.parent and self.hasParam(param.name)): raise ValueError("Param %r does not belong to %r." % (param, self))
python
def _shouldOwn(self, param): """ Validates that the input param belongs to this Params instance. """ if not (self.uid == param.parent and self.hasParam(param.name)): raise ValueError("Param %r does not belong to %r." % (param, self))
[ "def", "_shouldOwn", "(", "self", ",", "param", ")", ":", "if", "not", "(", "self", ".", "uid", "==", "param", ".", "parent", "and", "self", ".", "hasParam", "(", "param", ".", "name", ")", ")", ":", "raise", "ValueError", "(", "\"Param %r does not bel...
Validates that the input param belongs to this Params instance.
[ "Validates", "that", "the", "input", "param", "belongs", "to", "this", "Params", "instance", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L398-L403
19,342
apache/spark
python/pyspark/ml/param/__init__.py
Params._resolveParam
def _resolveParam(self, param): """ Resolves a param and validates the ownership. :param param: param name or the param instance, which must belong to this Params instance :return: resolved param instance """ if isinstance(param, Param): ...
python
def _resolveParam(self, param): """ Resolves a param and validates the ownership. :param param: param name or the param instance, which must belong to this Params instance :return: resolved param instance """ if isinstance(param, Param): ...
[ "def", "_resolveParam", "(", "self", ",", "param", ")", ":", "if", "isinstance", "(", "param", ",", "Param", ")", ":", "self", ".", "_shouldOwn", "(", "param", ")", "return", "param", "elif", "isinstance", "(", "param", ",", "basestring", ")", ":", "re...
Resolves a param and validates the ownership. :param param: param name or the param instance, which must belong to this Params instance :return: resolved param instance
[ "Resolves", "a", "param", "and", "validates", "the", "ownership", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L405-L419
19,343
apache/spark
python/pyspark/ml/param/__init__.py
Params._set
def _set(self, **kwargs): """ Sets user-supplied params. """ for param, value in kwargs.items(): p = getattr(self, param) if value is not None: try: value = p.typeConverter(value) except TypeError as e: ...
python
def _set(self, **kwargs): """ Sets user-supplied params. """ for param, value in kwargs.items(): p = getattr(self, param) if value is not None: try: value = p.typeConverter(value) except TypeError as e: ...
[ "def", "_set", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "param", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "p", "=", "getattr", "(", "self", ",", "param", ")", "if", "value", "is", "not", "None", ":", "try", ":", ...
Sets user-supplied params.
[ "Sets", "user", "-", "supplied", "params", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L431-L443
19,344
apache/spark
python/pyspark/ml/param/__init__.py
Params._setDefault
def _setDefault(self, **kwargs): """ Sets default params. """ for param, value in kwargs.items(): p = getattr(self, param) if value is not None and not isinstance(value, JavaObject): try: value = p.typeConverter(value) ...
python
def _setDefault(self, **kwargs): """ Sets default params. """ for param, value in kwargs.items(): p = getattr(self, param) if value is not None and not isinstance(value, JavaObject): try: value = p.typeConverter(value) ...
[ "def", "_setDefault", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "param", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "p", "=", "getattr", "(", "self", ",", "param", ")", "if", "value", "is", "not", "None", "and", "not"...
Sets default params.
[ "Sets", "default", "params", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L452-L465
19,345
apache/spark
python/pyspark/ml/param/__init__.py
Params._copyValues
def _copyValues(self, to, extra=None): """ Copies param values from this instance to another instance for params shared by them. :param to: the target instance :param extra: extra params to be copied :return: the target instance with param values copied """ ...
python
def _copyValues(self, to, extra=None): """ Copies param values from this instance to another instance for params shared by them. :param to: the target instance :param extra: extra params to be copied :return: the target instance with param values copied """ ...
[ "def", "_copyValues", "(", "self", ",", "to", ",", "extra", "=", "None", ")", ":", "paramMap", "=", "self", ".", "_paramMap", ".", "copy", "(", ")", "if", "extra", "is", "not", "None", ":", "paramMap", ".", "update", "(", "extra", ")", "for", "para...
Copies param values from this instance to another instance for params shared by them. :param to: the target instance :param extra: extra params to be copied :return: the target instance with param values copied
[ "Copies", "param", "values", "from", "this", "instance", "to", "another", "instance", "for", "params", "shared", "by", "them", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L467-L486
19,346
apache/spark
python/pyspark/ml/common.py
_to_java_object_rdd
def _to_java_object_rdd(rdd): """ Return an JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not. """ rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer())) return rdd.ctx._jvm.org.apache.spark...
python
def _to_java_object_rdd(rdd): """ Return an JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not. """ rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer())) return rdd.ctx._jvm.org.apache.spark...
[ "def", "_to_java_object_rdd", "(", "rdd", ")", ":", "rdd", "=", "rdd", ".", "_reserialize", "(", "AutoBatchedSerializer", "(", "PickleSerializer", "(", ")", ")", ")", "return", "rdd", ".", "ctx", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".",...
Return an JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not.
[ "Return", "an", "JavaRDD", "of", "Object", "by", "unpickling" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/common.py#L60-L67
19,347
apache/spark
python/pyspark/broadcast.py
Broadcast.value
def value(self): """ Return the broadcasted value """ if not hasattr(self, "_value") and self._path is not None: # we only need to decrypt it here when encryption is enabled and # if its on the driver, since executor decryption is handled already if self._sc i...
python
def value(self): """ Return the broadcasted value """ if not hasattr(self, "_value") and self._path is not None: # we only need to decrypt it here when encryption is enabled and # if its on the driver, since executor decryption is handled already if self._sc i...
[ "def", "value", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_value\"", ")", "and", "self", ".", "_path", "is", "not", "None", ":", "# we only need to decrypt it here when encryption is enabled and", "# if its on the driver, since executor decrypt...
Return the broadcasted value
[ "Return", "the", "broadcasted", "value" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/broadcast.py#L135-L148
19,348
apache/spark
python/pyspark/broadcast.py
Broadcast.unpersist
def unpersist(self, blocking=False): """ Delete cached copies of this broadcast on the executors. If the broadcast is used after this is called, it will need to be re-sent to each executor. :param blocking: Whether to block until unpersisting has completed """ if...
python
def unpersist(self, blocking=False): """ Delete cached copies of this broadcast on the executors. If the broadcast is used after this is called, it will need to be re-sent to each executor. :param blocking: Whether to block until unpersisting has completed """ if...
[ "def", "unpersist", "(", "self", ",", "blocking", "=", "False", ")", ":", "if", "self", ".", "_jbroadcast", "is", "None", ":", "raise", "Exception", "(", "\"Broadcast can only be unpersisted in driver\"", ")", "self", ".", "_jbroadcast", ".", "unpersist", "(", ...
Delete cached copies of this broadcast on the executors. If the broadcast is used after this is called, it will need to be re-sent to each executor. :param blocking: Whether to block until unpersisting has completed
[ "Delete", "cached", "copies", "of", "this", "broadcast", "on", "the", "executors", ".", "If", "the", "broadcast", "is", "used", "after", "this", "is", "called", "it", "will", "need", "to", "be", "re", "-", "sent", "to", "each", "executor", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/broadcast.py#L150-L160
19,349
apache/spark
python/pyspark/broadcast.py
Broadcast.destroy
def destroy(self, blocking=False): """ Destroy all data and metadata related to this broadcast variable. Use this with caution; once a broadcast variable has been destroyed, it cannot be used again. .. versionchanged:: 3.0.0 Added optional argument `blocking` to speci...
python
def destroy(self, blocking=False): """ Destroy all data and metadata related to this broadcast variable. Use this with caution; once a broadcast variable has been destroyed, it cannot be used again. .. versionchanged:: 3.0.0 Added optional argument `blocking` to speci...
[ "def", "destroy", "(", "self", ",", "blocking", "=", "False", ")", ":", "if", "self", ".", "_jbroadcast", "is", "None", ":", "raise", "Exception", "(", "\"Broadcast can only be destroyed in driver\"", ")", "self", ".", "_jbroadcast", ".", "destroy", "(", "bloc...
Destroy all data and metadata related to this broadcast variable. Use this with caution; once a broadcast variable has been destroyed, it cannot be used again. .. versionchanged:: 3.0.0 Added optional argument `blocking` to specify whether to block until all blocks are del...
[ "Destroy", "all", "data", "and", "metadata", "related", "to", "this", "broadcast", "variable", ".", "Use", "this", "with", "caution", ";", "once", "a", "broadcast", "variable", "has", "been", "destroyed", "it", "cannot", "be", "used", "again", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/broadcast.py#L162-L175
19,350
apache/spark
python/pyspark/sql/udf.py
UserDefinedFunction._wrapped
def _wrapped(self): """ Wrap this udf with a function and attach docstring from func """ # It is possible for a callable instance without __name__ attribute or/and # __module__ attribute to be wrapped here. For example, functools.partial. In this case, # we should avoid ...
python
def _wrapped(self): """ Wrap this udf with a function and attach docstring from func """ # It is possible for a callable instance without __name__ attribute or/and # __module__ attribute to be wrapped here. For example, functools.partial. In this case, # we should avoid ...
[ "def", "_wrapped", "(", "self", ")", ":", "# It is possible for a callable instance without __name__ attribute or/and", "# __module__ attribute to be wrapped here. For example, functools.partial. In this case,", "# we should avoid wrapping the attributes from the wrapped function to the wrapper", ...
Wrap this udf with a function and attach docstring from func
[ "Wrap", "this", "udf", "with", "a", "function", "and", "attach", "docstring", "from", "func" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/udf.py#L177-L204
19,351
apache/spark
python/pyspark/sql/udf.py
UDFRegistration.registerJavaFunction
def registerJavaFunction(self, name, javaClassName, returnType=None): """Register a Java user-defined function as a SQL function. In addition to a name and the function itself, the return type can be optionally specified. When the return type is not specified we would infer it via reflection. ...
python
def registerJavaFunction(self, name, javaClassName, returnType=None): """Register a Java user-defined function as a SQL function. In addition to a name and the function itself, the return type can be optionally specified. When the return type is not specified we would infer it via reflection. ...
[ "def", "registerJavaFunction", "(", "self", ",", "name", ",", "javaClassName", ",", "returnType", "=", "None", ")", ":", "jdt", "=", "None", "if", "returnType", "is", "not", "None", ":", "if", "not", "isinstance", "(", "returnType", ",", "DataType", ")", ...
Register a Java user-defined function as a SQL function. In addition to a name and the function itself, the return type can be optionally specified. When the return type is not specified we would infer it via reflection. :param name: name of the user-defined function :param javaClassNa...
[ "Register", "a", "Java", "user", "-", "defined", "function", "as", "a", "SQL", "function", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/udf.py#L345-L378
19,352
apache/spark
python/pyspark/sql/udf.py
UDFRegistration.registerJavaUDAF
def registerJavaUDAF(self, name, javaClassName): """Register a Java user-defined aggregate function as a SQL function. :param name: name of the user-defined aggregate function :param javaClassName: fully qualified name of java class >>> spark.udf.registerJavaUDAF("javaUDAF", "test.org....
python
def registerJavaUDAF(self, name, javaClassName): """Register a Java user-defined aggregate function as a SQL function. :param name: name of the user-defined aggregate function :param javaClassName: fully qualified name of java class >>> spark.udf.registerJavaUDAF("javaUDAF", "test.org....
[ "def", "registerJavaUDAF", "(", "self", ",", "name", ",", "javaClassName", ")", ":", "self", ".", "sparkSession", ".", "_jsparkSession", ".", "udf", "(", ")", ".", "registerJavaUDAF", "(", "name", ",", "javaClassName", ")" ]
Register a Java user-defined aggregate function as a SQL function. :param name: name of the user-defined aggregate function :param javaClassName: fully qualified name of java class >>> spark.udf.registerJavaUDAF("javaUDAF", "test.org.apache.spark.sql.MyDoubleAvg") >>> df = spark.create...
[ "Register", "a", "Java", "user", "-", "defined", "aggregate", "function", "as", "a", "SQL", "function", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/udf.py#L382-L395
19,353
apache/spark
python/pyspark/streaming/context.py
StreamingContext.getOrCreate
def getOrCreate(cls, checkpointPath, setupFunc): """ Either recreate a StreamingContext from checkpoint data or create a new StreamingContext. If checkpoint data exists in the provided `checkpointPath`, then StreamingContext will be recreated from the checkpoint data. If the data does no...
python
def getOrCreate(cls, checkpointPath, setupFunc): """ Either recreate a StreamingContext from checkpoint data or create a new StreamingContext. If checkpoint data exists in the provided `checkpointPath`, then StreamingContext will be recreated from the checkpoint data. If the data does no...
[ "def", "getOrCreate", "(", "cls", ",", "checkpointPath", ",", "setupFunc", ")", ":", "cls", ".", "_ensure_initialized", "(", ")", "gw", "=", "SparkContext", ".", "_gateway", "# Check whether valid checkpoint information exists in the given path", "ssc_option", "=", "gw"...
Either recreate a StreamingContext from checkpoint data or create a new StreamingContext. If checkpoint data exists in the provided `checkpointPath`, then StreamingContext will be recreated from the checkpoint data. If the data does not exist, then the provided setupFunc will be used to create a...
[ "Either", "recreate", "a", "StreamingContext", "from", "checkpoint", "data", "or", "create", "a", "new", "StreamingContext", ".", "If", "checkpoint", "data", "exists", "in", "the", "provided", "checkpointPath", "then", "StreamingContext", "will", "be", "recreated", ...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L88-L120
19,354
apache/spark
python/pyspark/streaming/context.py
StreamingContext.awaitTermination
def awaitTermination(self, timeout=None): """ Wait for the execution to stop. @param timeout: time to wait in seconds """ if timeout is None: self._jssc.awaitTermination() else: self._jssc.awaitTerminationOrTimeout(int(timeout * 1000))
python
def awaitTermination(self, timeout=None): """ Wait for the execution to stop. @param timeout: time to wait in seconds """ if timeout is None: self._jssc.awaitTermination() else: self._jssc.awaitTerminationOrTimeout(int(timeout * 1000))
[ "def", "awaitTermination", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "self", ".", "_jssc", ".", "awaitTermination", "(", ")", "else", ":", "self", ".", "_jssc", ".", "awaitTerminationOrTimeout", "(", "int", "...
Wait for the execution to stop. @param timeout: time to wait in seconds
[ "Wait", "for", "the", "execution", "to", "stop", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L182-L191
19,355
apache/spark
python/pyspark/streaming/context.py
StreamingContext.stop
def stop(self, stopSparkContext=True, stopGraceFully=False): """ Stop the execution of the streams, with option of ensuring all received data has been processed. @param stopSparkContext: Stop the associated SparkContext or not @param stopGracefully: Stop gracefully by waiting fo...
python
def stop(self, stopSparkContext=True, stopGraceFully=False): """ Stop the execution of the streams, with option of ensuring all received data has been processed. @param stopSparkContext: Stop the associated SparkContext or not @param stopGracefully: Stop gracefully by waiting fo...
[ "def", "stop", "(", "self", ",", "stopSparkContext", "=", "True", ",", "stopGraceFully", "=", "False", ")", ":", "self", ".", "_jssc", ".", "stop", "(", "stopSparkContext", ",", "stopGraceFully", ")", "StreamingContext", ".", "_activeContext", "=", "None", "...
Stop the execution of the streams, with option of ensuring all received data has been processed. @param stopSparkContext: Stop the associated SparkContext or not @param stopGracefully: Stop gracefully by waiting for the processing of all received data to be complet...
[ "Stop", "the", "execution", "of", "the", "streams", "with", "option", "of", "ensuring", "all", "received", "data", "has", "been", "processed", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L203-L215
19,356
apache/spark
python/pyspark/streaming/context.py
StreamingContext.textFileStream
def textFileStream(self, directory): """ Create an input stream that monitors a Hadoop-compatible file system for new files and reads them as text files. Files must be wrriten to the monitored directory by "moving" them from another location within the same file system. File name...
python
def textFileStream(self, directory): """ Create an input stream that monitors a Hadoop-compatible file system for new files and reads them as text files. Files must be wrriten to the monitored directory by "moving" them from another location within the same file system. File name...
[ "def", "textFileStream", "(", "self", ",", "directory", ")", ":", "return", "DStream", "(", "self", ".", "_jssc", ".", "textFileStream", "(", "directory", ")", ",", "self", ",", "UTF8Deserializer", "(", ")", ")" ]
Create an input stream that monitors a Hadoop-compatible file system for new files and reads them as text files. Files must be wrriten to the monitored directory by "moving" them from another location within the same file system. File names starting with . are ignored. The text files mus...
[ "Create", "an", "input", "stream", "that", "monitors", "a", "Hadoop", "-", "compatible", "file", "system", "for", "new", "files", "and", "reads", "them", "as", "text", "files", ".", "Files", "must", "be", "wrriten", "to", "the", "monitored", "directory", "...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L255-L263
19,357
apache/spark
python/pyspark/streaming/context.py
StreamingContext.binaryRecordsStream
def binaryRecordsStream(self, directory, recordLength): """ Create an input stream that monitors a Hadoop-compatible file system for new files and reads them as flat binary files with records of fixed length. Files must be written to the monitored directory by "moving" them from ...
python
def binaryRecordsStream(self, directory, recordLength): """ Create an input stream that monitors a Hadoop-compatible file system for new files and reads them as flat binary files with records of fixed length. Files must be written to the monitored directory by "moving" them from ...
[ "def", "binaryRecordsStream", "(", "self", ",", "directory", ",", "recordLength", ")", ":", "return", "DStream", "(", "self", ".", "_jssc", ".", "binaryRecordsStream", "(", "directory", ",", "recordLength", ")", ",", "self", ",", "NoOpSerializer", "(", ")", ...
Create an input stream that monitors a Hadoop-compatible file system for new files and reads them as flat binary files with records of fixed length. Files must be written to the monitored directory by "moving" them from another location within the same file system. File names starting wi...
[ "Create", "an", "input", "stream", "that", "monitors", "a", "Hadoop", "-", "compatible", "file", "system", "for", "new", "files", "and", "reads", "them", "as", "flat", "binary", "files", "with", "records", "of", "fixed", "length", ".", "Files", "must", "be...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L265-L277
19,358
apache/spark
python/pyspark/streaming/context.py
StreamingContext.queueStream
def queueStream(self, rdds, oneAtATime=True, default=None): """ Create an input stream from a queue of RDDs or list. In each batch, it will process either one or all of the RDDs returned by the queue. .. note:: Changes to the queue after the stream is created will not be recognized. ...
python
def queueStream(self, rdds, oneAtATime=True, default=None): """ Create an input stream from a queue of RDDs or list. In each batch, it will process either one or all of the RDDs returned by the queue. .. note:: Changes to the queue after the stream is created will not be recognized. ...
[ "def", "queueStream", "(", "self", ",", "rdds", ",", "oneAtATime", "=", "True", ",", "default", "=", "None", ")", ":", "if", "default", "and", "not", "isinstance", "(", "default", ",", "RDD", ")", ":", "default", "=", "self", ".", "_sc", ".", "parall...
Create an input stream from a queue of RDDs or list. In each batch, it will process either one or all of the RDDs returned by the queue. .. note:: Changes to the queue after the stream is created will not be recognized. @param rdds: Queue of RDDs @param oneAtATime: pick one rdd e...
[ "Create", "an", "input", "stream", "from", "a", "queue", "of", "RDDs", "or", "list", ".", "In", "each", "batch", "it", "will", "process", "either", "one", "or", "all", "of", "the", "RDDs", "returned", "by", "the", "queue", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L286-L313
19,359
apache/spark
python/pyspark/streaming/context.py
StreamingContext.transform
def transform(self, dstreams, transformFunc): """ Create a new DStream in which each RDD is generated by applying a function on RDDs of the DStreams. The order of the JavaRDDs in the transform function parameter will be the same as the order of corresponding DStreams in the list....
python
def transform(self, dstreams, transformFunc): """ Create a new DStream in which each RDD is generated by applying a function on RDDs of the DStreams. The order of the JavaRDDs in the transform function parameter will be the same as the order of corresponding DStreams in the list....
[ "def", "transform", "(", "self", ",", "dstreams", ",", "transformFunc", ")", ":", "jdstreams", "=", "[", "d", ".", "_jdstream", "for", "d", "in", "dstreams", "]", "# change the final serializer to sc.serializer", "func", "=", "TransformFunction", "(", "self", "....
Create a new DStream in which each RDD is generated by applying a function on RDDs of the DStreams. The order of the JavaRDDs in the transform function parameter will be the same as the order of corresponding DStreams in the list.
[ "Create", "a", "new", "DStream", "in", "which", "each", "RDD", "is", "generated", "by", "applying", "a", "function", "on", "RDDs", "of", "the", "DStreams", ".", "The", "order", "of", "the", "JavaRDDs", "in", "the", "transform", "function", "parameter", "wi...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L315-L329
19,360
apache/spark
python/pyspark/streaming/context.py
StreamingContext.union
def union(self, *dstreams): """ Create a unified DStream from multiple DStreams of the same type and same slide duration. """ if not dstreams: raise ValueError("should have at least one DStream to union") if len(dstreams) == 1: return dstreams[0] ...
python
def union(self, *dstreams): """ Create a unified DStream from multiple DStreams of the same type and same slide duration. """ if not dstreams: raise ValueError("should have at least one DStream to union") if len(dstreams) == 1: return dstreams[0] ...
[ "def", "union", "(", "self", ",", "*", "dstreams", ")", ":", "if", "not", "dstreams", ":", "raise", "ValueError", "(", "\"should have at least one DStream to union\"", ")", "if", "len", "(", "dstreams", ")", "==", "1", ":", "return", "dstreams", "[", "0", ...
Create a unified DStream from multiple DStreams of the same type and same slide duration.
[ "Create", "a", "unified", "DStream", "from", "multiple", "DStreams", "of", "the", "same", "type", "and", "same", "slide", "duration", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/streaming/context.py#L331-L348
19,361
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/modeling_gpt2.py
GPT2Config.from_json_file
def from_json_file(cls, json_file): """Constructs a `GPT2Config` from a json file of parameters.""" with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() return cls.from_dict(json.loads(text))
python
def from_json_file(cls, json_file): """Constructs a `GPT2Config` from a json file of parameters.""" with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() return cls.from_dict(json.loads(text))
[ "def", "from_json_file", "(", "cls", ",", "json_file", ")", ":", "with", "open", "(", "json_file", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "reader", ":", "text", "=", "reader", ".", "read", "(", ")", "return", "cls", ".", "from_dict...
Constructs a `GPT2Config` from a json file of parameters.
[ "Constructs", "a", "GPT2Config", "from", "a", "json", "file", "of", "parameters", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_gpt2.py#L162-L166
19,362
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/modeling_gpt2.py
GPT2Config.to_json_file
def to_json_file(self, json_file_path): """ Save this instance to a json file.""" with open(json_file_path, "w", encoding='utf-8') as writer: writer.write(self.to_json_string())
python
def to_json_file(self, json_file_path): """ Save this instance to a json file.""" with open(json_file_path, "w", encoding='utf-8') as writer: writer.write(self.to_json_string())
[ "def", "to_json_file", "(", "self", ",", "json_file_path", ")", ":", "with", "open", "(", "json_file_path", ",", "\"w\"", ",", "encoding", "=", "'utf-8'", ")", "as", "writer", ":", "writer", ".", "write", "(", "self", ".", "to_json_string", "(", ")", ")"...
Save this instance to a json file.
[ "Save", "this", "instance", "to", "a", "json", "file", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_gpt2.py#L180-L183
19,363
huggingface/pytorch-pretrained-BERT
examples/extract_features.py
convert_examples_to_features
def convert_examples_to_features(examples, seq_length, tokenizer): """Loads a data file into a list of `InputFeature`s.""" features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: toke...
python
def convert_examples_to_features(examples, seq_length, tokenizer): """Loads a data file into a list of `InputFeature`s.""" features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: toke...
[ "def", "convert_examples_to_features", "(", "examples", ",", "seq_length", ",", "tokenizer", ")", ":", "features", "=", "[", "]", "for", "(", "ex_index", ",", "example", ")", "in", "enumerate", "(", "examples", ")", ":", "tokens_a", "=", "tokenizer", ".", ...
Loads a data file into a list of `InputFeature`s.
[ "Loads", "a", "data", "file", "into", "a", "list", "of", "InputFeature", "s", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/extract_features.py#L59-L147
19,364
huggingface/pytorch-pretrained-BERT
examples/extract_features.py
read_examples
def read_examples(input_file): """Read a list of `InputExample`s from an input file.""" examples = [] unique_id = 0 with open(input_file, "r", encoding='utf-8') as reader: while True: line = reader.readline() if not line: break line = line.stri...
python
def read_examples(input_file): """Read a list of `InputExample`s from an input file.""" examples = [] unique_id = 0 with open(input_file, "r", encoding='utf-8') as reader: while True: line = reader.readline() if not line: break line = line.stri...
[ "def", "read_examples", "(", "input_file", ")", ":", "examples", "=", "[", "]", "unique_id", "=", "0", "with", "open", "(", "input_file", ",", "\"r\"", ",", "encoding", "=", "'utf-8'", ")", "as", "reader", ":", "while", "True", ":", "line", "=", "reade...
Read a list of `InputExample`s from an input file.
[ "Read", "a", "list", "of", "InputExample", "s", "from", "an", "input", "file", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/extract_features.py#L167-L188
19,365
huggingface/pytorch-pretrained-BERT
examples/run_squad.py
read_squad_examples
def read_squad_examples(input_file, is_training, version_2_with_negative): """Read a SQuAD json file into a list of SquadExample.""" with open(input_file, "r", encoding='utf-8') as reader: input_data = json.load(reader)["data"] def is_whitespace(c): if c == " " or c == "\t" or c == "\r" or ...
python
def read_squad_examples(input_file, is_training, version_2_with_negative): """Read a SQuAD json file into a list of SquadExample.""" with open(input_file, "r", encoding='utf-8') as reader: input_data = json.load(reader)["data"] def is_whitespace(c): if c == " " or c == "\t" or c == "\r" or ...
[ "def", "read_squad_examples", "(", "input_file", ",", "is_training", ",", "version_2_with_negative", ")", ":", "with", "open", "(", "input_file", ",", "\"r\"", ",", "encoding", "=", "'utf-8'", ")", "as", "reader", ":", "input_data", "=", "json", ".", "load", ...
Read a SQuAD json file into a list of SquadExample.
[ "Read", "a", "SQuAD", "json", "file", "into", "a", "list", "of", "SquadExample", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_squad.py#L122-L197
19,366
huggingface/pytorch-pretrained-BERT
examples/run_squad.py
_improve_answer_span
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): """Returns tokenized answer spans that better match the annotated answer.""" # The SQuAD annotations are character based. We first project them to # whitespace-tokenized words. But then after...
python
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): """Returns tokenized answer spans that better match the annotated answer.""" # The SQuAD annotations are character based. We first project them to # whitespace-tokenized words. But then after...
[ "def", "_improve_answer_span", "(", "doc_tokens", ",", "input_start", ",", "input_end", ",", "tokenizer", ",", "orig_answer_text", ")", ":", "# The SQuAD annotations are character based. We first project them to", "# whitespace-tokenized words. But then after WordPiece tokenization, we...
Returns tokenized answer spans that better match the annotated answer.
[ "Returns", "tokenized", "answer", "spans", "that", "better", "match", "the", "annotated", "answer", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_squad.py#L363-L397
19,367
huggingface/pytorch-pretrained-BERT
examples/run_squad.py
_check_is_max_context
def _check_is_max_context(doc_spans, cur_span_index, position): """Check if this is the 'max context' doc span for the token.""" # Because of the sliding window approach taken to scoring documents, a single # token can appear in multiple documents. E.g. # Doc: the man went to the store and bought a ga...
python
def _check_is_max_context(doc_spans, cur_span_index, position): """Check if this is the 'max context' doc span for the token.""" # Because of the sliding window approach taken to scoring documents, a single # token can appear in multiple documents. E.g. # Doc: the man went to the store and bought a ga...
[ "def", "_check_is_max_context", "(", "doc_spans", ",", "cur_span_index", ",", "position", ")", ":", "# Because of the sliding window approach taken to scoring documents, a single", "# token can appear in multiple documents. E.g.", "# Doc: the man went to the store and bought a gallon of mil...
Check if this is the 'max context' doc span for the token.
[ "Check", "if", "this", "is", "the", "max", "context", "doc", "span", "for", "the", "token", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_squad.py#L400-L434
19,368
huggingface/pytorch-pretrained-BERT
examples/run_squad.py
_get_best_indexes
def _get_best_indexes(logits, n_best_size): """Get the n-best logits from a list.""" index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True) best_indexes = [] for i in range(len(index_and_score)): if i >= n_best_size: break best_indexes.append(index_and...
python
def _get_best_indexes(logits, n_best_size): """Get the n-best logits from a list.""" index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True) best_indexes = [] for i in range(len(index_and_score)): if i >= n_best_size: break best_indexes.append(index_and...
[ "def", "_get_best_indexes", "(", "logits", ",", "n_best_size", ")", ":", "index_and_score", "=", "sorted", "(", "enumerate", "(", "logits", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "best_indexes", ...
Get the n-best logits from a list.
[ "Get", "the", "n", "-", "best", "logits", "from", "a", "list", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_squad.py#L729-L738
19,369
huggingface/pytorch-pretrained-BERT
examples/run_squad.py
_compute_softmax
def _compute_softmax(scores): """Compute softmax probability over raw logits.""" if not scores: return [] max_score = None for score in scores: if max_score is None or score > max_score: max_score = score exp_scores = [] total_sum = 0.0 for score in scores: ...
python
def _compute_softmax(scores): """Compute softmax probability over raw logits.""" if not scores: return [] max_score = None for score in scores: if max_score is None or score > max_score: max_score = score exp_scores = [] total_sum = 0.0 for score in scores: ...
[ "def", "_compute_softmax", "(", "scores", ")", ":", "if", "not", "scores", ":", "return", "[", "]", "max_score", "=", "None", "for", "score", "in", "scores", ":", "if", "max_score", "is", "None", "or", "score", ">", "max_score", ":", "max_score", "=", ...
Compute softmax probability over raw logits.
[ "Compute", "softmax", "probability", "over", "raw", "logits", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_squad.py#L741-L761
19,370
huggingface/pytorch-pretrained-BERT
examples/run_classifier.py
DataProcessor._read_tsv
def _read_tsv(cls, input_file, quotechar=None): """Reads a tab separated value file.""" with open(input_file, "r", encoding="utf-8") as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: if sys.version_info[0]...
python
def _read_tsv(cls, input_file, quotechar=None): """Reads a tab separated value file.""" with open(input_file, "r", encoding="utf-8") as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: if sys.version_info[0]...
[ "def", "_read_tsv", "(", "cls", ",", "input_file", ",", "quotechar", "=", "None", ")", ":", "with", "open", "(", "input_file", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "reader", "=", "csv", ".", "reader", "(", "f", ",", ...
Reads a tab separated value file.
[ "Reads", "a", "tab", "separated", "value", "file", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_classifier.py#L93-L102
19,371
huggingface/pytorch-pretrained-BERT
examples/run_classifier.py
MrpcProcessor._create_examples
def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, i) text_a = line[3] text_b = line[4]...
python
def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, i) text_a = line[3] text_b = line[4]...
[ "def", "_create_examples", "(", "self", ",", "lines", ",", "set_type", ")", ":", "examples", "=", "[", "]", "for", "(", "i", ",", "line", ")", "in", "enumerate", "(", "lines", ")", ":", "if", "i", "==", "0", ":", "continue", "guid", "=", "\"%s-%s\"...
Creates examples for the training and dev sets.
[ "Creates", "examples", "for", "the", "training", "and", "dev", "sets", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_classifier.py#L123-L135
19,372
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/modeling_openai.py
OpenAIGPTConfig.from_dict
def from_dict(cls, json_object): """Constructs a `OpenAIGPTConfig` from a Python dictionary of parameters.""" config = OpenAIGPTConfig(vocab_size_or_config_json_file=-1) for key, value in json_object.items(): config.__dict__[key] = value return config
python
def from_dict(cls, json_object): """Constructs a `OpenAIGPTConfig` from a Python dictionary of parameters.""" config = OpenAIGPTConfig(vocab_size_or_config_json_file=-1) for key, value in json_object.items(): config.__dict__[key] = value return config
[ "def", "from_dict", "(", "cls", ",", "json_object", ")", ":", "config", "=", "OpenAIGPTConfig", "(", "vocab_size_or_config_json_file", "=", "-", "1", ")", "for", "key", ",", "value", "in", "json_object", ".", "items", "(", ")", ":", "config", ".", "__dict_...
Constructs a `OpenAIGPTConfig` from a Python dictionary of parameters.
[ "Constructs", "a", "OpenAIGPTConfig", "from", "a", "Python", "dictionary", "of", "parameters", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_openai.py#L200-L205
19,373
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/modeling_openai.py
OpenAIGPTModel.set_num_special_tokens
def set_num_special_tokens(self, num_special_tokens): " Update input embeddings with new embedding matrice if needed " if self.config.n_special == num_special_tokens: return # Update config self.config.n_special = num_special_tokens # Build new embeddings and initiali...
python
def set_num_special_tokens(self, num_special_tokens): " Update input embeddings with new embedding matrice if needed " if self.config.n_special == num_special_tokens: return # Update config self.config.n_special = num_special_tokens # Build new embeddings and initiali...
[ "def", "set_num_special_tokens", "(", "self", ",", "num_special_tokens", ")", ":", "if", "self", ".", "config", ".", "n_special", "==", "num_special_tokens", ":", "return", "# Update config", "self", ".", "config", ".", "n_special", "=", "num_special_tokens", "# B...
Update input embeddings with new embedding matrice if needed
[ "Update", "input", "embeddings", "with", "new", "embedding", "matrice", "if", "needed" ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_openai.py#L605-L617
19,374
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/modeling_openai.py
OpenAIGPTLMHeadModel.set_num_special_tokens
def set_num_special_tokens(self, num_special_tokens): """ Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings """ self.transformer.set_num_special_tokens(num_special_tokens) self.lm_head.set_embeddings_weights(self.transformer...
python
def set_num_special_tokens(self, num_special_tokens): """ Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings """ self.transformer.set_num_special_tokens(num_special_tokens) self.lm_head.set_embeddings_weights(self.transformer...
[ "def", "set_num_special_tokens", "(", "self", ",", "num_special_tokens", ")", ":", "self", ".", "transformer", ".", "set_num_special_tokens", "(", "num_special_tokens", ")", "self", ".", "lm_head", ".", "set_embeddings_weights", "(", "self", ".", "transformer", ".",...
Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings
[ "Update", "input", "and", "output", "embeddings", "with", "new", "embedding", "matrice", "Make", "sure", "we", "are", "sharing", "the", "embeddings" ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_openai.py#L710-L715
19,375
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/tokenization.py
BertTokenizer.convert_tokens_to_ids
def convert_tokens_to_ids(self, tokens): """Converts a sequence of tokens into ids using the vocab.""" ids = [] for token in tokens: ids.append(self.vocab[token]) if len(ids) > self.max_len: logger.warning( "Token indices sequence length is longer ...
python
def convert_tokens_to_ids(self, tokens): """Converts a sequence of tokens into ids using the vocab.""" ids = [] for token in tokens: ids.append(self.vocab[token]) if len(ids) > self.max_len: logger.warning( "Token indices sequence length is longer ...
[ "def", "convert_tokens_to_ids", "(", "self", ",", "tokens", ")", ":", "ids", "=", "[", "]", "for", "token", "in", "tokens", ":", "ids", ".", "append", "(", "self", ".", "vocab", "[", "token", "]", ")", "if", "len", "(", "ids", ")", ">", "self", "...
Converts a sequence of tokens into ids using the vocab.
[ "Converts", "a", "sequence", "of", "tokens", "into", "ids", "using", "the", "vocab", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L117-L128
19,376
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/tokenization.py
BertTokenizer.convert_ids_to_tokens
def convert_ids_to_tokens(self, ids): """Converts a sequence of ids in wordpiece tokens using the vocab.""" tokens = [] for i in ids: tokens.append(self.ids_to_tokens[i]) return tokens
python
def convert_ids_to_tokens(self, ids): """Converts a sequence of ids in wordpiece tokens using the vocab.""" tokens = [] for i in ids: tokens.append(self.ids_to_tokens[i]) return tokens
[ "def", "convert_ids_to_tokens", "(", "self", ",", "ids", ")", ":", "tokens", "=", "[", "]", "for", "i", "in", "ids", ":", "tokens", ".", "append", "(", "self", ".", "ids_to_tokens", "[", "i", "]", ")", "return", "tokens" ]
Converts a sequence of ids in wordpiece tokens using the vocab.
[ "Converts", "a", "sequence", "of", "ids", "in", "wordpiece", "tokens", "using", "the", "vocab", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L130-L135
19,377
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/tokenization.py
BertTokenizer.save_vocabulary
def save_vocabulary(self, vocab_path): """Save the tokenizer vocabulary to a directory or file.""" index = 0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_NAME) with open(vocab_file, "w", encoding="utf-8") as writer: for token, token_in...
python
def save_vocabulary(self, vocab_path): """Save the tokenizer vocabulary to a directory or file.""" index = 0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_NAME) with open(vocab_file, "w", encoding="utf-8") as writer: for token, token_in...
[ "def", "save_vocabulary", "(", "self", ",", "vocab_path", ")", ":", "index", "=", "0", "if", "os", ".", "path", ".", "isdir", "(", "vocab_path", ")", ":", "vocab_file", "=", "os", ".", "path", ".", "join", "(", "vocab_path", ",", "VOCAB_NAME", ")", "...
Save the tokenizer vocabulary to a directory or file.
[ "Save", "the", "tokenizer", "vocabulary", "to", "a", "directory", "or", "file", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L137-L150
19,378
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/tokenization.py
BertTokenizer.from_pretrained
def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): """ Instantiate a PreTrainedBertModel from a pre-trained model file. Download and cache the pre-trained model file if needed. """ if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHI...
python
def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): """ Instantiate a PreTrainedBertModel from a pre-trained model file. Download and cache the pre-trained model file if needed. """ if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHI...
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "cache_dir", "=", "None", ",", "*", "inputs", ",", "*", "*", "kwargs", ")", ":", "if", "pretrained_model_name_or_path", "in", "PRETRAINED_VOCAB_ARCHIVE_MAP", ":", "vocab_file", "=", "...
Instantiate a PreTrainedBertModel from a pre-trained model file. Download and cache the pre-trained model file if needed.
[ "Instantiate", "a", "PreTrainedBertModel", "from", "a", "pre", "-", "trained", "model", "file", ".", "Download", "and", "cache", "the", "pre", "-", "trained", "model", "file", "if", "needed", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L153-L198
19,379
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/tokenization.py
BasicTokenizer._run_strip_accents
def _run_strip_accents(self, text): """Strips accents from a piece of text.""" text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": continue output.append(char) ...
python
def _run_strip_accents(self, text): """Strips accents from a piece of text.""" text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": continue output.append(char) ...
[ "def", "_run_strip_accents", "(", "self", ",", "text", ")", ":", "text", "=", "unicodedata", ".", "normalize", "(", "\"NFD\"", ",", "text", ")", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cat", "=", "unicodedata", ".", "category", "(",...
Strips accents from a piece of text.
[ "Strips", "accents", "from", "a", "piece", "of", "text", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L236-L245
19,380
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/tokenization.py
BasicTokenizer._tokenize_chinese_chars
def _tokenize_chinese_chars(self, text): """Adds whitespace around any CJK character.""" output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") ...
python
def _tokenize_chinese_chars(self, text): """Adds whitespace around any CJK character.""" output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") ...
[ "def", "_tokenize_chinese_chars", "(", "self", ",", "text", ")", ":", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cp", "=", "ord", "(", "char", ")", "if", "self", ".", "_is_chinese_char", "(", "cp", ")", ":", "output", ".", "append", ...
Adds whitespace around any CJK character.
[ "Adds", "whitespace", "around", "any", "CJK", "character", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L269-L280
19,381
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/tokenization.py
BasicTokenizer._is_chinese_char
def _is_chinese_char(self, cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is ...
python
def _is_chinese_char(self, cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is ...
[ "def", "_is_chinese_char", "(", "self", ",", "cp", ")", ":", "# This defines a \"chinese character\" as anything in the CJK Unicode block:", "# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)", "#", "# Note that the CJK Unicode block is NOT all Japanese and Korean charac...
Checks whether CP is the codepoint of a CJK character.
[ "Checks", "whether", "CP", "is", "the", "codepoint", "of", "a", "CJK", "character", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L282-L302
19,382
huggingface/pytorch-pretrained-BERT
examples/lm_finetuning/simple_lm_finetuning.py
BERTDataset.get_next_line
def get_next_line(self): """ Gets next line of random_file and starts over when reaching end of file""" try: line = next(self.random_file).strip() #keep track of which document we are currently looking at to later avoid having the same doc as t1 if line == "": ...
python
def get_next_line(self): """ Gets next line of random_file and starts over when reaching end of file""" try: line = next(self.random_file).strip() #keep track of which document we are currently looking at to later avoid having the same doc as t1 if line == "": ...
[ "def", "get_next_line", "(", "self", ")", ":", "try", ":", "line", "=", "next", "(", "self", ".", "random_file", ")", ".", "strip", "(", ")", "#keep track of which document we are currently looking at to later avoid having the same doc as t1", "if", "line", "==", "\"\...
Gets next line of random_file and starts over when reaching end of file
[ "Gets", "next", "line", "of", "random_file", "and", "starts", "over", "when", "reaching", "end", "of", "file" ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/simple_lm_finetuning.py#L219-L231
19,383
huggingface/pytorch-pretrained-BERT
examples/lm_finetuning/pregenerate_training_data.py
create_masked_lm_predictions
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_list): """Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but with several refactors to clean it up and remove a lot of unnecessary variables.""" cand_indices = [] ...
python
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_list): """Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but with several refactors to clean it up and remove a lot of unnecessary variables.""" cand_indices = [] ...
[ "def", "create_masked_lm_predictions", "(", "tokens", ",", "masked_lm_prob", ",", "max_predictions_per_seq", ",", "vocab_list", ")", ":", "cand_indices", "=", "[", "]", "for", "(", "i", ",", "token", ")", "in", "enumerate", "(", "tokens", ")", ":", "if", "to...
Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but with several refactors to clean it up and remove a lot of unnecessary variables.
[ "Creates", "the", "predictions", "for", "the", "masked", "LM", "objective", ".", "This", "is", "mostly", "copied", "from", "the", "Google", "BERT", "repo", "but", "with", "several", "refactors", "to", "clean", "it", "up", "and", "remove", "a", "lot", "of",...
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/pregenerate_training_data.py#L102-L131
19,384
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/modeling_transfo_xl.py
build_tf_to_pytorch_map
def build_tf_to_pytorch_map(model, config): """ A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible. """ tf_to_pt_map = {} if hasattr(model, 'transformer'): # We are loading in a TransfoXLLMHeadModel...
python
def build_tf_to_pytorch_map(model, config): """ A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible. """ tf_to_pt_map = {} if hasattr(model, 'transformer'): # We are loading in a TransfoXLLMHeadModel...
[ "def", "build_tf_to_pytorch_map", "(", "model", ",", "config", ")", ":", "tf_to_pt_map", "=", "{", "}", "if", "hasattr", "(", "model", ",", "'transformer'", ")", ":", "# We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax", "tf_to_pt_map", "...
A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible.
[ "A", "map", "of", "modules", "from", "TF", "to", "PyTorch", ".", "This", "time", "I", "use", "a", "map", "to", "keep", "the", "PyTorch", "model", "as", "identical", "to", "the", "original", "PyTorch", "model", "as", "possible", "." ]
b832d5bb8a6dfc5965015b828e577677eace601e
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl.py#L56-L126
19,385
pandas-dev/pandas
pandas/tseries/frequencies.py
to_offset
def to_offset(freq): """ Return DateOffset object from string or tuple representation or datetime.timedelta object Parameters ---------- freq : str, tuple, datetime.timedelta, DateOffset or None Returns ------- DateOffset None if freq is None. Raises ------ Val...
python
def to_offset(freq): """ Return DateOffset object from string or tuple representation or datetime.timedelta object Parameters ---------- freq : str, tuple, datetime.timedelta, DateOffset or None Returns ------- DateOffset None if freq is None. Raises ------ Val...
[ "def", "to_offset", "(", "freq", ")", ":", "if", "freq", "is", "None", ":", "return", "None", "if", "isinstance", "(", "freq", ",", "DateOffset", ")", ":", "return", "freq", "if", "isinstance", "(", "freq", ",", "tuple", ")", ":", "name", "=", "freq"...
Return DateOffset object from string or tuple representation or datetime.timedelta object Parameters ---------- freq : str, tuple, datetime.timedelta, DateOffset or None Returns ------- DateOffset None if freq is None. Raises ------ ValueError If freq is an inv...
[ "Return", "DateOffset", "object", "from", "string", "or", "tuple", "representation", "or", "datetime", ".", "timedelta", "object" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/frequencies.py#L57-L164
19,386
pandas-dev/pandas
pandas/tseries/frequencies.py
get_offset
def get_offset(name): """ Return DateOffset object associated with rule name Examples -------- get_offset('EOM') --> BMonthEnd(1) """ if name not in libfreqs._dont_uppercase: name = name.upper() name = libfreqs._lite_rule_alias.get(name, name) name = libfreqs._lite_r...
python
def get_offset(name): """ Return DateOffset object associated with rule name Examples -------- get_offset('EOM') --> BMonthEnd(1) """ if name not in libfreqs._dont_uppercase: name = name.upper() name = libfreqs._lite_rule_alias.get(name, name) name = libfreqs._lite_r...
[ "def", "get_offset", "(", "name", ")", ":", "if", "name", "not", "in", "libfreqs", ".", "_dont_uppercase", ":", "name", "=", "name", ".", "upper", "(", ")", "name", "=", "libfreqs", ".", "_lite_rule_alias", ".", "get", "(", "name", ",", "name", ")", ...
Return DateOffset object associated with rule name Examples -------- get_offset('EOM') --> BMonthEnd(1)
[ "Return", "DateOffset", "object", "associated", "with", "rule", "name" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/frequencies.py#L167-L195
19,387
pandas-dev/pandas
pandas/tseries/frequencies.py
infer_freq
def infer_freq(index, warn=True): """ Infer the most likely frequency given the input index. If the frequency is uncertain, a warning will be printed. Parameters ---------- index : DatetimeIndex or TimedeltaIndex if passed a Series will use the values of the series (NOT THE INDEX) war...
python
def infer_freq(index, warn=True): """ Infer the most likely frequency given the input index. If the frequency is uncertain, a warning will be printed. Parameters ---------- index : DatetimeIndex or TimedeltaIndex if passed a Series will use the values of the series (NOT THE INDEX) war...
[ "def", "infer_freq", "(", "index", ",", "warn", "=", "True", ")", ":", "import", "pandas", "as", "pd", "if", "isinstance", "(", "index", ",", "ABCSeries", ")", ":", "values", "=", "index", ".", "_values", "if", "not", "(", "is_datetime64_dtype", "(", "...
Infer the most likely frequency given the input index. If the frequency is uncertain, a warning will be printed. Parameters ---------- index : DatetimeIndex or TimedeltaIndex if passed a Series will use the values of the series (NOT THE INDEX) warn : boolean, default True Returns ---...
[ "Infer", "the", "most", "likely", "frequency", "given", "the", "input", "index", ".", "If", "the", "frequency", "is", "uncertain", "a", "warning", "will", "be", "printed", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/frequencies.py#L202-L252
19,388
pandas-dev/pandas
pandas/tseries/frequencies.py
_FrequencyInferer.get_freq
def get_freq(self): """ Find the appropriate frequency string to describe the inferred frequency of self.values Returns ------- str or None """ if not self.is_monotonic or not self.index._is_unique: return None delta = self.deltas[0] ...
python
def get_freq(self): """ Find the appropriate frequency string to describe the inferred frequency of self.values Returns ------- str or None """ if not self.is_monotonic or not self.index._is_unique: return None delta = self.deltas[0] ...
[ "def", "get_freq", "(", "self", ")", ":", "if", "not", "self", ".", "is_monotonic", "or", "not", "self", ".", "index", ".", "_is_unique", ":", "return", "None", "delta", "=", "self", ".", "deltas", "[", "0", "]", "if", "_is_multiple", "(", "delta", "...
Find the appropriate frequency string to describe the inferred frequency of self.values Returns ------- str or None
[ "Find", "the", "appropriate", "frequency", "string", "to", "describe", "the", "inferred", "frequency", "of", "self", ".", "values" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/frequencies.py#L294-L337
19,389
pandas-dev/pandas
pandas/compat/pickle_compat.py
load
def load(fh, encoding=None, is_verbose=False): """load a pickle, with a provided encoding if compat is True: fake the old class hierarchy if it works, then return the new type objects Parameters ---------- fh : a filelike object encoding : an optional encoding is_verbose : sh...
python
def load(fh, encoding=None, is_verbose=False): """load a pickle, with a provided encoding if compat is True: fake the old class hierarchy if it works, then return the new type objects Parameters ---------- fh : a filelike object encoding : an optional encoding is_verbose : sh...
[ "def", "load", "(", "fh", ",", "encoding", "=", "None", ",", "is_verbose", "=", "False", ")", ":", "try", ":", "fh", ".", "seek", "(", "0", ")", "if", "encoding", "is", "not", "None", ":", "up", "=", "Unpickler", "(", "fh", ",", "encoding", "=", ...
load a pickle, with a provided encoding if compat is True: fake the old class hierarchy if it works, then return the new type objects Parameters ---------- fh : a filelike object encoding : an optional encoding is_verbose : show exception output
[ "load", "a", "pickle", "with", "a", "provided", "encoding" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/compat/pickle_compat.py#L189-L213
19,390
pandas-dev/pandas
pandas/core/indexes/base.py
ensure_index_from_sequences
def ensure_index_from_sequences(sequences, names=None): """ Construct an index from sequences of data. A single sequence returns an Index. Many sequences returns a MultiIndex. Parameters ---------- sequences : sequence of sequences names : sequence of str Returns ------- i...
python
def ensure_index_from_sequences(sequences, names=None): """ Construct an index from sequences of data. A single sequence returns an Index. Many sequences returns a MultiIndex. Parameters ---------- sequences : sequence of sequences names : sequence of str Returns ------- i...
[ "def", "ensure_index_from_sequences", "(", "sequences", ",", "names", "=", "None", ")", ":", "from", ".", "multi", "import", "MultiIndex", "if", "len", "(", "sequences", ")", "==", "1", ":", "if", "names", "is", "not", "None", ":", "names", "=", "names",...
Construct an index from sequences of data. A single sequence returns an Index. Many sequences returns a MultiIndex. Parameters ---------- sequences : sequence of sequences names : sequence of str Returns ------- index : Index or MultiIndex Examples -------- >>> ensure...
[ "Construct", "an", "index", "from", "sequences", "of", "data", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5277-L5315
19,391
pandas-dev/pandas
pandas/core/indexes/base.py
ensure_index
def ensure_index(index_like, copy=False): """ Ensure that we have an index from some index-like object. Parameters ---------- index : sequence An Index or other sequence copy : bool Returns ------- index : Index or MultiIndex Examples -------- >>> ensure_index(...
python
def ensure_index(index_like, copy=False): """ Ensure that we have an index from some index-like object. Parameters ---------- index : sequence An Index or other sequence copy : bool Returns ------- index : Index or MultiIndex Examples -------- >>> ensure_index(...
[ "def", "ensure_index", "(", "index_like", ",", "copy", "=", "False", ")", ":", "if", "isinstance", "(", "index_like", ",", "Index", ")", ":", "if", "copy", ":", "index_like", "=", "index_like", ".", "copy", "(", ")", "return", "index_like", "if", "hasatt...
Ensure that we have an index from some index-like object. Parameters ---------- index : sequence An Index or other sequence copy : bool Returns ------- index : Index or MultiIndex Examples -------- >>> ensure_index(['a', 'b']) Index(['a', 'b'], dtype='object') ...
[ "Ensure", "that", "we", "have", "an", "index", "from", "some", "index", "-", "like", "object", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5318-L5378
19,392
pandas-dev/pandas
pandas/core/indexes/base.py
Index._simple_new
def _simple_new(cls, values, name=None, dtype=None, **kwargs): """ We require that we have a dtype compat for the values. If we are passed a non-dtype compat, then coerce using the constructor. Must be careful not to recurse. """ if not hasattr(values, 'dtype'): ...
python
def _simple_new(cls, values, name=None, dtype=None, **kwargs): """ We require that we have a dtype compat for the values. If we are passed a non-dtype compat, then coerce using the constructor. Must be careful not to recurse. """ if not hasattr(values, 'dtype'): ...
[ "def", "_simple_new", "(", "cls", ",", "values", ",", "name", "=", "None", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "values", ",", "'dtype'", ")", ":", "if", "(", "values", "is", "None", "or", "no...
We require that we have a dtype compat for the values. If we are passed a non-dtype compat, then coerce using the constructor. Must be careful not to recurse.
[ "We", "require", "that", "we", "have", "a", "dtype", "compat", "for", "the", "values", ".", "If", "we", "are", "passed", "a", "non", "-", "dtype", "compat", "then", "coerce", "using", "the", "constructor", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L506-L539
19,393
pandas-dev/pandas
pandas/core/indexes/base.py
Index._shallow_copy_with_infer
def _shallow_copy_with_infer(self, values, **kwargs): """ Create a new Index inferring the class with passed value, don't copy the data, use the same object attributes with passed in attributes taking precedence. *this is an internal non-public method* Parameters ...
python
def _shallow_copy_with_infer(self, values, **kwargs): """ Create a new Index inferring the class with passed value, don't copy the data, use the same object attributes with passed in attributes taking precedence. *this is an internal non-public method* Parameters ...
[ "def", "_shallow_copy_with_infer", "(", "self", ",", "values", ",", "*", "*", "kwargs", ")", ":", "attributes", "=", "self", ".", "_get_attributes_dict", "(", ")", "attributes", ".", "update", "(", "kwargs", ")", "attributes", "[", "'copy'", "]", "=", "Fal...
Create a new Index inferring the class with passed value, don't copy the data, use the same object attributes with passed in attributes taking precedence. *this is an internal non-public method* Parameters ---------- values : the values to create the new Index, optional...
[ "Create", "a", "new", "Index", "inferring", "the", "class", "with", "passed", "value", "don", "t", "copy", "the", "data", "use", "the", "same", "object", "attributes", "with", "passed", "in", "attributes", "taking", "precedence", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L585-L608
19,394
pandas-dev/pandas
pandas/core/indexes/base.py
Index.is_
def is_(self, other): """ More flexible, faster check like ``is`` but that works through views. Note: this is *not* the same as ``Index.identical()``, which checks that metadata is also the same. Parameters ---------- other : object other object to c...
python
def is_(self, other): """ More flexible, faster check like ``is`` but that works through views. Note: this is *not* the same as ``Index.identical()``, which checks that metadata is also the same. Parameters ---------- other : object other object to c...
[ "def", "is_", "(", "self", ",", "other", ")", ":", "# use something other than None to be clearer", "return", "self", ".", "_id", "is", "getattr", "(", "other", ",", "'_id'", ",", "Ellipsis", ")", "and", "self", ".", "_id", "is", "not", "None" ]
More flexible, faster check like ``is`` but that works through views. Note: this is *not* the same as ``Index.identical()``, which checks that metadata is also the same. Parameters ---------- other : object other object to compare against. Returns -...
[ "More", "flexible", "faster", "check", "like", "is", "but", "that", "works", "through", "views", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L614-L632
19,395
pandas-dev/pandas
pandas/core/indexes/base.py
Index._assert_take_fillable
def _assert_take_fillable(self, values, indices, allow_fill=True, fill_value=None, na_value=np.nan): """ Internal method to handle NA filling of take. """ indices = ensure_platform_int(indices) # only fill if we are passing a non-None fill_value ...
python
def _assert_take_fillable(self, values, indices, allow_fill=True, fill_value=None, na_value=np.nan): """ Internal method to handle NA filling of take. """ indices = ensure_platform_int(indices) # only fill if we are passing a non-None fill_value ...
[ "def", "_assert_take_fillable", "(", "self", ",", "values", ",", "indices", ",", "allow_fill", "=", "True", ",", "fill_value", "=", "None", ",", "na_value", "=", "np", ".", "nan", ")", ":", "indices", "=", "ensure_platform_int", "(", "indices", ")", "# onl...
Internal method to handle NA filling of take.
[ "Internal", "method", "to", "handle", "NA", "filling", "of", "take", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L803-L822
19,396
pandas-dev/pandas
pandas/core/indexes/base.py
Index._format_data
def _format_data(self, name=None): """ Return the formatted data as a unicode string. """ # do we want to justify (only do so for non-objects) is_justify = not (self.inferred_type in ('string', 'unicode') or (self.inferred_type == 'categorical' and ...
python
def _format_data(self, name=None): """ Return the formatted data as a unicode string. """ # do we want to justify (only do so for non-objects) is_justify = not (self.inferred_type in ('string', 'unicode') or (self.inferred_type == 'categorical' and ...
[ "def", "_format_data", "(", "self", ",", "name", "=", "None", ")", ":", "# do we want to justify (only do so for non-objects)", "is_justify", "=", "not", "(", "self", ".", "inferred_type", "in", "(", "'string'", ",", "'unicode'", ")", "or", "(", "self", ".", "...
Return the formatted data as a unicode string.
[ "Return", "the", "formatted", "data", "as", "a", "unicode", "string", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L958-L969
19,397
pandas-dev/pandas
pandas/core/indexes/base.py
Index.format
def format(self, name=False, formatter=None, **kwargs): """ Render a string representation of the Index. """ header = [] if name: header.append(pprint_thing(self.name, escape_chars=('\t', '\r', '\n')) if ...
python
def format(self, name=False, formatter=None, **kwargs): """ Render a string representation of the Index. """ header = [] if name: header.append(pprint_thing(self.name, escape_chars=('\t', '\r', '\n')) if ...
[ "def", "format", "(", "self", ",", "name", "=", "False", ",", "formatter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "header", "=", "[", "]", "if", "name", ":", "header", ".", "append", "(", "pprint_thing", "(", "self", ".", "name", ",", "e...
Render a string representation of the Index.
[ "Render", "a", "string", "representation", "of", "the", "Index", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L981-L994
19,398
pandas-dev/pandas
pandas/core/indexes/base.py
Index.to_native_types
def to_native_types(self, slicer=None, **kwargs): """ Format specified values of `self` and return them. Parameters ---------- slicer : int, array-like An indexer into `self` that specifies which values are used in the formatting process. kwargs :...
python
def to_native_types(self, slicer=None, **kwargs): """ Format specified values of `self` and return them. Parameters ---------- slicer : int, array-like An indexer into `self` that specifies which values are used in the formatting process. kwargs :...
[ "def", "to_native_types", "(", "self", ",", "slicer", "=", "None", ",", "*", "*", "kwargs", ")", ":", "values", "=", "self", "if", "slicer", "is", "not", "None", ":", "values", "=", "values", "[", "slicer", "]", "return", "values", ".", "_format_native...
Format specified values of `self` and return them. Parameters ---------- slicer : int, array-like An indexer into `self` that specifies which values are used in the formatting process. kwargs : dict Options for specifying how the values should be form...
[ "Format", "specified", "values", "of", "self", "and", "return", "them", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1022-L1046
19,399
pandas-dev/pandas
pandas/core/indexes/base.py
Index._format_native_types
def _format_native_types(self, na_rep='', quoting=None, **kwargs): """ Actually format specific types of the index. """ mask = isna(self) if not self.is_object() and not quoting: values = np.asarray(self).astype(str) else: values = np.array(self, d...
python
def _format_native_types(self, na_rep='', quoting=None, **kwargs): """ Actually format specific types of the index. """ mask = isna(self) if not self.is_object() and not quoting: values = np.asarray(self).astype(str) else: values = np.array(self, d...
[ "def", "_format_native_types", "(", "self", ",", "na_rep", "=", "''", ",", "quoting", "=", "None", ",", "*", "*", "kwargs", ")", ":", "mask", "=", "isna", "(", "self", ")", "if", "not", "self", ".", "is_object", "(", ")", "and", "not", "quoting", "...
Actually format specific types of the index.
[ "Actually", "format", "specific", "types", "of", "the", "index", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1048-L1059