Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function:def _createFromLocal(self, data, schema): # make sure data could consumed multiple times if not isinstance(data, list): data = list(data) if schema is None or isinstance(schema, (list, tuple)): struct = self._inferSchemaFromList(data, names=schema) converter = _create_converter(struct) data = map(converter, data) if isinstance(schema, (list, tuple)): for i, name in enumerate(schema): struct.fields[i].name = name struct.names[i] = name schema = struct elif not isinstance(schema, StructType): raise TypeError("schema should be StructType or list or None, but got: %s" % schema) # convert python objects to sql data data = [schema.toInternal(row) for row in data] return self._sc.parallelize(data), schema
[ "\n Create an RDD for DataFrame from a list or pandas.DataFrame, returns\n the RDD and schema.\n " ]
Please provide a description of the function:def _get_numpy_record_dtype(self, rec): import numpy as np cur_dtypes = rec.dtype col_names = cur_dtypes.names record_type_list = [] has_rec_fix = False for i in xrange(len(cur_dtypes)): curr_type = cur_dtypes[i] # If type is a datetime64 timestamp, convert to microseconds # NOTE: if dtype is datetime[ns] then np.record.tolist() will output values as longs, # conversion from [us] or lower will lead to py datetime objects, see SPARK-22417 if curr_type == np.dtype('datetime64[ns]'): curr_type = 'datetime64[us]' has_rec_fix = True record_type_list.append((str(col_names[i]), curr_type)) return np.dtype(record_type_list) if has_rec_fix else None
[ "\n Used when converting a pandas.DataFrame to Spark using to_records(), this will correct\n the dtypes of fields in a record so they can be properly loaded into Spark.\n :param rec: a numpy record to check field dtypes\n :return corrected dtype for a numpy.record or None if no correction needed\n " ]
Please provide a description of the function:def _convert_from_pandas(self, pdf, schema, timezone): if timezone is not None: from pyspark.sql.types import _check_series_convert_timestamps_tz_local copied = False if isinstance(schema, StructType): for field in schema: # TODO: handle nested timestamps, such as ArrayType(TimestampType())? if isinstance(field.dataType, TimestampType): s = _check_series_convert_timestamps_tz_local(pdf[field.name], timezone) if s is not pdf[field.name]: if not copied: # Copy once if the series is modified to prevent the original # Pandas DataFrame from being updated pdf = pdf.copy() copied = True pdf[field.name] = s else: for column, series in pdf.iteritems(): s = _check_series_convert_timestamps_tz_local(series, timezone) if s is not series: if not copied: # Copy once if the series is modified to prevent the original # Pandas DataFrame from being updated pdf = pdf.copy() copied = True pdf[column] = s # Convert pandas.DataFrame to list of numpy records np_records = pdf.to_records(index=False) # Check if any columns need to be fixed for Spark to infer properly if len(np_records) > 0: record_dtype = self._get_numpy_record_dtype(np_records[0]) if record_dtype is not None: return [r.astype(record_dtype).tolist() for r in np_records] # Convert list of numpy records to python lists return [r.tolist() for r in np_records]
[ "\n Convert a pandas.DataFrame to list of records that can be used to make a DataFrame\n :return list of records\n " ]
Please provide a description of the function:def _create_from_pandas_with_arrow(self, pdf, schema, timezone): from pyspark.serializers import ArrowStreamPandasSerializer from pyspark.sql.types import from_arrow_type, to_arrow_type, TimestampType from pyspark.sql.utils import require_minimum_pandas_version, \ require_minimum_pyarrow_version require_minimum_pandas_version() require_minimum_pyarrow_version() from pandas.api.types import is_datetime64_dtype, is_datetime64tz_dtype import pyarrow as pa # Create the Spark schema from list of names passed in with Arrow types if isinstance(schema, (list, tuple)): arrow_schema = pa.Schema.from_pandas(pdf, preserve_index=False) struct = StructType() for name, field in zip(schema, arrow_schema): struct.add(name, from_arrow_type(field.type), nullable=field.nullable) schema = struct # Determine arrow types to coerce data when creating batches if isinstance(schema, StructType): arrow_types = [to_arrow_type(f.dataType) for f in schema.fields] elif isinstance(schema, DataType): raise ValueError("Single data type %s is not supported with Arrow" % str(schema)) else: # Any timestamps must be coerced to be compatible with Spark arrow_types = [to_arrow_type(TimestampType()) if is_datetime64_dtype(t) or is_datetime64tz_dtype(t) else None for t in pdf.dtypes] # Slice the DataFrame to be batched step = -(-len(pdf) // self.sparkContext.defaultParallelism) # round int up pdf_slices = (pdf[start:start + step] for start in xrange(0, len(pdf), step)) # Create list of Arrow (columns, type) for serializer dump_stream arrow_data = [[(c, t) for (_, c), t in zip(pdf_slice.iteritems(), arrow_types)] for pdf_slice in pdf_slices] jsqlContext = self._wrapped._jsqlContext safecheck = self._wrapped._conf.arrowSafeTypeConversion() col_by_name = True # col by name only applies to StructType columns, can't happen here ser = ArrowStreamPandasSerializer(timezone, safecheck, col_by_name) def reader_func(temp_filename): return self._jvm.PythonSQLUtils.readArrowStreamFromFile(jsqlContext, temp_filename) def create_RDD_server(): return self._jvm.ArrowRDDServer(jsqlContext) # Create Spark DataFrame from Arrow stream file, using one batch per partition jrdd = self._sc._serialize_to_jvm(arrow_data, ser, reader_func, create_RDD_server) jdf = self._jvm.PythonSQLUtils.toDataFrame(jrdd, schema.json(), jsqlContext) df = DataFrame(jdf, self._wrapped) df._schema = schema return df
[ "\n Create a DataFrame from a given pandas.DataFrame by slicing it into partitions, converting\n to Arrow data, then sending to the JVM to parallelize. If a schema is passed in, the\n data types will be used to coerce the data in Pandas to Arrow conversion.\n " ]
Please provide a description of the function: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 = SparkConf() if conf.get('spark.sql.catalogImplementation', 'hive').lower() == 'hive': SparkContext._jvm.org.apache.hadoop.hive.conf.HiveConf() return SparkSession.builder\ .enableHiveSupport()\ .getOrCreate() else: return SparkSession.builder.getOrCreate() except (py4j.protocol.Py4JError, TypeError): if conf.get('spark.sql.catalogImplementation', '').lower() == 'hive': warnings.warn("Fall back to non-hive support because failing to access HiveConf, " "please make sure you build spark with hive") return SparkSession.builder.getOrCreate()
[ "\n Initialize a SparkSession for a pyspark shell session. This is called from shell.py\n to make error handling simpler without needing to declare local variables in that\n script, which would expose those to users.\n " ]
Please provide a description of the function:def createDataFrame(self, data, schema=None, samplingRatio=None, verifySchema=True): SparkSession._activeSession = self self._jvm.SparkSession.setActiveSession(self._jsparkSession) if isinstance(data, DataFrame): raise TypeError("data is already a DataFrame") if isinstance(schema, basestring): schema = _parse_datatype_string(schema) elif isinstance(schema, (list, tuple)): # Must re-encode any unicode strings to be consistent with StructField names schema = [x.encode('utf-8') if not isinstance(x, str) else x for x in schema] try: import pandas has_pandas = True except Exception: has_pandas = False if has_pandas and isinstance(data, pandas.DataFrame): from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() if self._wrapped._conf.pandasRespectSessionTimeZone(): timezone = self._wrapped._conf.sessionLocalTimeZone() else: timezone = None # If no schema supplied by user then get the names of columns only if schema is None: schema = [str(x) if not isinstance(x, basestring) else (x.encode('utf-8') if not isinstance(x, str) else x) for x in data.columns] if self._wrapped._conf.arrowEnabled() and len(data) > 0: try: return self._create_from_pandas_with_arrow(data, schema, timezone) except Exception as e: from pyspark.util import _exception_message if self._wrapped._conf.arrowFallbackEnabled(): msg = ( "createDataFrame attempted Arrow optimization because " "'spark.sql.execution.arrow.enabled' is set to true; however, " "failed by the reason below:\n %s\n" "Attempting non-optimization as " "'spark.sql.execution.arrow.fallback.enabled' is set to " "true." % _exception_message(e)) warnings.warn(msg) else: msg = ( "createDataFrame attempted Arrow optimization because " "'spark.sql.execution.arrow.enabled' is set to true, but has reached " "the error below and will not continue because automatic fallback " "with 'spark.sql.execution.arrow.fallback.enabled' has been set to " "false.\n %s" % _exception_message(e)) warnings.warn(msg) raise data = self._convert_from_pandas(data, schema, timezone) if isinstance(schema, StructType): verify_func = _make_type_verifier(schema) if verifySchema else lambda _: True def prepare(obj): verify_func(obj) return obj elif isinstance(schema, DataType): dataType = schema schema = StructType().add("value", schema) verify_func = _make_type_verifier( dataType, name="field value") if verifySchema else lambda _: True def prepare(obj): verify_func(obj) return obj, else: prepare = lambda obj: obj if isinstance(data, RDD): rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio) else: rdd, schema = self._createFromLocal(map(prepare, data), schema) jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd()) jdf = self._jsparkSession.applySchemaToPythonRDD(jrdd.rdd(), schema.json()) df = DataFrame(jdf, self._wrapped) df._schema = schema return df
[ "\n Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`.\n\n When ``schema`` is a list of column names, the type of each column\n will be inferred from ``data``.\n\n When ``schema`` is ``None``, it will try to infer the schema (column names and types)\n from ``data``, which should be an RDD of :class:`Row`,\n or :class:`namedtuple`, or :class:`dict`.\n\n When ``schema`` is :class:`pyspark.sql.types.DataType` or a datatype string, it must match\n the real data, or an exception will be thrown at runtime. If the given schema is not\n :class:`pyspark.sql.types.StructType`, it will be wrapped into a\n :class:`pyspark.sql.types.StructType` as its only field, and the field name will be \"value\",\n each record will also be wrapped into a tuple, which can be converted to row later.\n\n If schema inference is needed, ``samplingRatio`` is used to determined the ratio of\n rows used for schema inference. The first row will be used if ``samplingRatio`` is ``None``.\n\n :param data: an RDD of any kind of SQL data representation(e.g. row, tuple, int, boolean,\n etc.), or :class:`list`, or :class:`pandas.DataFrame`.\n :param schema: a :class:`pyspark.sql.types.DataType` or a datatype string or a list of\n column names, default is ``None``. The data type string format equals to\n :class:`pyspark.sql.types.DataType.simpleString`, except that top level struct type can\n omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use\n ``byte`` instead of ``tinyint`` for :class:`pyspark.sql.types.ByteType`. We can also use\n ``int`` as a short name for ``IntegerType``.\n :param samplingRatio: the sample ratio of rows used for inferring\n :param verifySchema: verify data types of every row against schema.\n :return: :class:`DataFrame`\n\n .. versionchanged:: 2.1\n Added verifySchema.\n\n .. note:: Usage with spark.sql.execution.arrow.enabled=True is experimental.\n\n >>> l = [('Alice', 1)]\n >>> spark.createDataFrame(l).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> spark.createDataFrame(l, ['name', 'age']).collect()\n [Row(name=u'Alice', age=1)]\n\n >>> d = [{'name': 'Alice', 'age': 1}]\n >>> spark.createDataFrame(d).collect()\n [Row(age=1, name=u'Alice')]\n\n >>> rdd = sc.parallelize(l)\n >>> spark.createDataFrame(rdd).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> df = spark.createDataFrame(rdd, ['name', 'age'])\n >>> df.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql import Row\n >>> Person = Row('name', 'age')\n >>> person = rdd.map(lambda r: Person(*r))\n >>> df2 = spark.createDataFrame(person)\n >>> df2.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql.types import *\n >>> schema = StructType([\n ... StructField(\"name\", StringType(), True),\n ... StructField(\"age\", IntegerType(), True)])\n >>> df3 = spark.createDataFrame(rdd, schema)\n >>> df3.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> spark.createDataFrame(df.toPandas()).collect() # doctest: +SKIP\n [Row(name=u'Alice', age=1)]\n >>> spark.createDataFrame(pandas.DataFrame([[1, 2]])).collect() # doctest: +SKIP\n [Row(0=1, 1=2)]\n\n >>> spark.createDataFrame(rdd, \"a: string, b: int\").collect()\n [Row(a=u'Alice', b=1)]\n >>> rdd = rdd.map(lambda row: row[1])\n >>> spark.createDataFrame(rdd, \"int\").collect()\n [Row(value=1)]\n >>> spark.createDataFrame(rdd, \"boolean\").collect() # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n Py4JJavaError: ...\n " ]
Please provide a description of the function:def sql(self, sqlQuery): return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped)
[ "Returns a :class:`DataFrame` representing the result of the given query.\n\n :return: :class:`DataFrame`\n\n >>> df.createOrReplaceTempView(\"table1\")\n >>> df2 = spark.sql(\"SELECT field1 AS f1, field2 as f2 from table1\")\n >>> df2.collect()\n [Row(f1=1, f2=u'row1'), Row(f1=2, f2=u'row2'), Row(f1=3, f2=u'row3')]\n " ]
Please provide a description of the function:def table(self, tableName): return DataFrame(self._jsparkSession.table(tableName), self._wrapped)
[ "Returns the specified table as a :class:`DataFrame`.\n\n :return: :class:`DataFrame`\n\n >>> df.createOrReplaceTempView(\"table1\")\n >>> df2 = spark.table(\"table1\")\n >>> sorted(df.collect()) == sorted(df2.collect())\n True\n " ]
Please provide a description of the function:def streams(self): from pyspark.sql.streaming import StreamingQueryManager return StreamingQueryManager(self._jsparkSession.streams())
[ "Returns a :class:`StreamingQueryManager` that allows managing all the\n :class:`StreamingQuery` StreamingQueries active on `this` context.\n\n .. note:: Evolving.\n\n :return: :class:`StreamingQueryManager`\n " ]
Please provide a description of the function:def stop(self): self._sc.stop() # We should clean the default session up. See SPARK-23228. self._jvm.SparkSession.clearDefaultSession() self._jvm.SparkSession.clearActiveSession() SparkSession._instantiatedSession = None SparkSession._activeSession = None
[ "Stop the underlying :class:`SparkContext`.\n " ]
Please provide a description of the function:def getJobInfo(self, jobId): job = self._jtracker.getJobInfo(jobId) if job is not None: return SparkJobInfo(jobId, job.stageIds(), str(job.status()))
[ "\n Returns a :class:`SparkJobInfo` object, or None if the job info\n could not be found or was garbage collected.\n " ]
Please provide a description of the function:def getStageInfo(self, stageId): stage = self._jtracker.getStageInfo(stageId) if stage is not None: # TODO: fetch them in batch for better performance attrs = [getattr(stage, f)() for f in SparkStageInfo._fields[1:]] return SparkStageInfo(stageId, *attrs)
[ "\n Returns a :class:`SparkStageInfo` object, or None if the stage\n info could not be found or was garbage collected.\n " ]
Please provide a description of the function:def _restore(name, fields, value): k = (name, fields) cls = __cls.get(k) if cls is None: cls = collections.namedtuple(name, fields) __cls[k] = cls return cls(*value)
[ " Restore an object of namedtuple" ]
Please provide a description of the function:def _hack_namedtuple(cls): name = cls.__name__ fields = cls._fields def __reduce__(self): return (_restore, (name, fields, tuple(self))) cls.__reduce__ = __reduce__ cls._is_namedtuple_ = True return cls
[ " Make class generated by namedtuple picklable " ]
Please provide a description of the function:def _hijack_namedtuple(): # hijack only one time if hasattr(collections.namedtuple, "__hijack"): return global _old_namedtuple # or it will put in closure global _old_namedtuple_kwdefaults # or it will put in closure too def _copy_func(f): return types.FunctionType(f.__code__, f.__globals__, f.__name__, f.__defaults__, f.__closure__) def _kwdefaults(f): # __kwdefaults__ contains the default values of keyword-only arguments which are # introduced from Python 3. The possible cases for __kwdefaults__ in namedtuple # are as below: # # - Does not exist in Python 2. # - Returns None in <= Python 3.5.x. # - Returns a dictionary containing the default values to the keys from Python 3.6.x # (See https://bugs.python.org/issue25628). kargs = getattr(f, "__kwdefaults__", None) if kargs is None: return {} else: return kargs _old_namedtuple = _copy_func(collections.namedtuple) _old_namedtuple_kwdefaults = _kwdefaults(collections.namedtuple) def namedtuple(*args, **kwargs): for k, v in _old_namedtuple_kwdefaults.items(): kwargs[k] = kwargs.get(k, v) cls = _old_namedtuple(*args, **kwargs) return _hack_namedtuple(cls) # replace namedtuple with the new one collections.namedtuple.__globals__["_old_namedtuple_kwdefaults"] = _old_namedtuple_kwdefaults collections.namedtuple.__globals__["_old_namedtuple"] = _old_namedtuple collections.namedtuple.__globals__["_hack_namedtuple"] = _hack_namedtuple collections.namedtuple.__code__ = namedtuple.__code__ collections.namedtuple.__hijack = 1 # hack the cls already generated by namedtuple. # Those created in other modules can be pickled as normal, # so only hack those in __main__ module for n, o in sys.modules["__main__"].__dict__.items(): if (type(o) is type and o.__base__ is tuple and hasattr(o, "_fields") and "__reduce__" not in o.__dict__): _hack_namedtuple(o)
[ " Hack namedtuple() to make it picklable " ]
Please provide a description of the function: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(stream) batch_order = [] for i in xrange(num): index = read_int(stream) batch_order.append(index) yield batch_order
[ "\n Load a stream of un-ordered Arrow RecordBatches, where the last iteration yields\n a list of indices that can be used to put the RecordBatches in the correct order.\n " ]
Please provide a description of the function: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), (series2, type2), ...] if not isinstance(series, (list, tuple)) or \ (len(series) == 2 and isinstance(series[1], pa.DataType)): series = [series] series = ((s, None) if not isinstance(s, (list, tuple)) else s for s in series) def create_array(s, t): mask = s.isnull() # Ensure timestamp series are in expected form for Spark internal representation if t is not None and pa.types.is_timestamp(t): s = _check_series_convert_timestamps_internal(s.fillna(0), self._timezone) # TODO: need cast after Arrow conversion, ns values cause error with pandas 0.19.2 return pa.Array.from_pandas(s, mask=mask).cast(t, safe=False) try: array = pa.Array.from_pandas(s, mask=mask, type=t, safe=self._safecheck) except pa.ArrowException as e: error_msg = "Exception thrown when converting pandas.Series (%s) to Arrow " + \ "Array (%s). It can be caused by overflows or other unsafe " + \ "conversions warned by Arrow. Arrow safe type check can be " + \ "disabled by using SQL config " + \ "`spark.sql.execution.pandas.arrowSafeTypeConversion`." raise RuntimeError(error_msg % (s.dtype, t), e) return array arrs = [] for s, t in series: if t is not None and pa.types.is_struct(t): if not isinstance(s, pd.DataFrame): raise ValueError("A field of type StructType expects a pandas.DataFrame, " "but got: %s" % str(type(s))) # Input partition and result pandas.DataFrame empty, make empty Arrays with struct if len(s) == 0 and len(s.columns) == 0: arrs_names = [(pa.array([], type=field.type), field.name) for field in t] # Assign result columns by schema name if user labeled with strings elif self._assign_cols_by_name and any(isinstance(name, basestring) for name in s.columns): arrs_names = [(create_array(s[field.name], field.type), field.name) for field in t] # Assign result columns by position else: arrs_names = [(create_array(s[s.columns[i]], field.type), field.name) for i, field in enumerate(t)] struct_arrs, struct_names = zip(*arrs_names) arrs.append(pa.StructArray.from_arrays(struct_arrs, struct_names)) else: arrs.append(create_array(s, t)) return pa.RecordBatch.from_arrays(arrs, ["_%d" % i for i in xrange(len(arrs))])
[ "\n Create an Arrow record batch from the given pandas.Series or list of Series,\n with optional type.\n\n :param series: A single pandas.Series, list of Series, or list of (series, arrow_type)\n :return: Arrow RecordBatch\n " ]
Please provide a description of the function:def dump_stream(self, iterator, stream): batches = (self._create_batch(series) for series in iterator) super(ArrowStreamPandasSerializer, self).dump_stream(batches, stream)
[ "\n Make ArrowRecordBatches from Pandas Series and serialize. Input is a single series or\n a list of series accompanied by an optional pyarrow type to coerce the data to.\n " ]
Please provide a description of the function:def load_stream(self, stream): batches = super(ArrowStreamPandasSerializer, self).load_stream(stream) import pyarrow as pa for batch in batches: yield [self.arrow_to_pandas(c) for c in pa.Table.from_batches([batch]).itercolumns()]
[ "\n Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series.\n " ]
Please provide a description of the function:def dump_stream(self, iterator, stream): def init_stream_yield_batches(): should_write_start_length = True for series in iterator: batch = self._create_batch(series) if should_write_start_length: write_int(SpecialLengths.START_ARROW_STREAM, stream) should_write_start_length = False yield batch return ArrowStreamSerializer.dump_stream(self, init_stream_yield_batches(), stream)
[ "\n Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent.\n This should be sent after creating the first record batch so in case of an error, it can\n be sent back to the JVM before the Arrow stream starts.\n " ]
Please provide a description of the function:def awaitTermination(self, timeout=None): if timeout is not None: if not isinstance(timeout, (int, float)) or timeout < 0: raise ValueError("timeout must be a positive integer or float. Got %s" % timeout) return self._jsq.awaitTermination(int(timeout * 1000)) else: return self._jsq.awaitTermination()
[ "Waits for the termination of `this` query, either by :func:`query.stop()` or by an\n exception. If the query has terminated with an exception, then the exception will be thrown.\n If `timeout` is set, it returns whether the query has terminated or not within the\n `timeout` seconds.\n\n If the query has terminated, then all subsequent calls to this method will either return\n immediately (if the query was terminated by :func:`stop()`), or throw the exception\n immediately (if the query has terminated with exception).\n\n throws :class:`StreamingQueryException`, if `this` query has terminated with an exception\n " ]
Please provide a description of the function:def recentProgress(self): return [json.loads(p.json()) for p in self._jsq.recentProgress()]
[ "Returns an array of the most recent [[StreamingQueryProgress]] updates for this query.\n The number of progress updates retained for each stream is configured by Spark session\n configuration `spark.sql.streaming.numRecentProgressUpdates`.\n " ]
Please provide a description of the function:def lastProgress(self): lastProgress = self._jsq.lastProgress() if lastProgress: return json.loads(lastProgress.json()) else: return None
[ "\n Returns the most recent :class:`StreamingQueryProgress` update of this streaming query or\n None if there were no progress updates\n :return: a map\n " ]
Please provide a description of the function:def exception(self): if self._jsq.exception().isDefined(): je = self._jsq.exception().get() msg = je.toString().split(': ', 1)[1] # Drop the Java StreamingQueryException type info stackTrace = '\n\t at '.join(map(lambda x: x.toString(), je.getStackTrace())) return StreamingQueryException(msg, stackTrace, je.getCause()) else: return None
[ "\n :return: the StreamingQueryException if the query was terminated by an exception, or None.\n " ]
Please provide a description of the function:def awaitAnyTermination(self, timeout=None): if timeout is not None: if not isinstance(timeout, (int, float)) or timeout < 0: raise ValueError("timeout must be a positive integer or float. Got %s" % timeout) return self._jsqm.awaitAnyTermination(int(timeout * 1000)) else: return self._jsqm.awaitAnyTermination()
[ "Wait until any of the queries on the associated SQLContext has terminated since the\n creation of the context, or since :func:`resetTerminated()` was called. If any query was\n terminated with an exception, then the exception will be thrown.\n If `timeout` is set, it returns whether the query has terminated or not within the\n `timeout` seconds.\n\n If a query has terminated, then subsequent calls to :func:`awaitAnyTermination()` will\n either return immediately (if the query was terminated by :func:`query.stop()`),\n or throw the exception immediately (if the query was terminated with exception). Use\n :func:`resetTerminated()` to clear past terminations and wait for new terminations.\n\n In the case where multiple queries have terminated since :func:`resetTermination()`\n was called, if any query has terminated with exception, then :func:`awaitAnyTermination()`\n will throw any of the exception. For correctly documenting exceptions across multiple\n queries, users need to stop all of them after any of them terminates with exception, and\n then check the `query.exception()` for each query.\n\n throws :class:`StreamingQueryException`, if `this` query has terminated with an exception\n " ]
Please provide a description of the function:def load(self, path=None, format=None, schema=None, **options): if format is not None: self.format(format) if schema is not None: self.schema(schema) self.options(**options) if path is not None: if type(path) != str or len(path.strip()) == 0: raise ValueError("If the path is provided for stream, it needs to be a " + "non-empty string. List of paths are not supported.") return self._df(self._jreader.load(path)) else: return self._df(self._jreader.load())
[ "Loads a data stream from a data source and returns it as a :class`DataFrame`.\n\n .. note:: Evolving.\n\n :param path: optional string for file-system backed data sources.\n :param format: optional string for format of the data source. Default to 'parquet'.\n :param schema: optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param options: all other string options\n\n >>> json_sdf = spark.readStream.format(\"json\") \\\\\n ... .schema(sdf_schema) \\\\\n ... .load(tempfile.mkdtemp())\n >>> json_sdf.isStreaming\n True\n >>> json_sdf.schema == sdf_schema\n True\n " ]
Please provide a description of the function:def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None, allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None, allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None, mode=None, columnNameOfCorruptRecord=None, dateFormat=None, timestampFormat=None, multiLine=None, allowUnquotedControlChars=None, lineSep=None, locale=None, dropFieldIfAllNull=None, encoding=None): self._set_opts( schema=schema, primitivesAsString=primitivesAsString, prefersDecimal=prefersDecimal, allowComments=allowComments, allowUnquotedFieldNames=allowUnquotedFieldNames, allowSingleQuotes=allowSingleQuotes, allowNumericLeadingZero=allowNumericLeadingZero, allowBackslashEscapingAnyCharacter=allowBackslashEscapingAnyCharacter, mode=mode, columnNameOfCorruptRecord=columnNameOfCorruptRecord, dateFormat=dateFormat, timestampFormat=timestampFormat, multiLine=multiLine, allowUnquotedControlChars=allowUnquotedControlChars, lineSep=lineSep, locale=locale, dropFieldIfAllNull=dropFieldIfAllNull, encoding=encoding) if isinstance(path, basestring): return self._df(self._jreader.json(path)) else: raise TypeError("path can be only a single string")
[ "\n Loads a JSON file stream and returns the results as a :class:`DataFrame`.\n\n `JSON Lines <http://jsonlines.org/>`_ (newline-delimited JSON) is supported by default.\n For JSON (one record per file), set the ``multiLine`` parameter to ``true``.\n\n If the ``schema`` parameter is not specified, this function goes\n through the input once to determine the input schema.\n\n .. note:: Evolving.\n\n :param path: string represents path to the JSON dataset,\n or RDD of Strings storing JSON objects.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param primitivesAsString: infers all primitive values as a string type. If None is set,\n it uses the default value, ``false``.\n :param prefersDecimal: infers all floating-point values as a decimal type. If the values\n do not fit in decimal, then it infers them as doubles. If None is\n set, it uses the default value, ``false``.\n :param allowComments: ignores Java/C++ style comment in JSON records. If None is set,\n it uses the default value, ``false``.\n :param allowUnquotedFieldNames: allows unquoted JSON field names. If None is set,\n it uses the default value, ``false``.\n :param allowSingleQuotes: allows single quotes in addition to double quotes. If None is\n set, it uses the default value, ``true``.\n :param allowNumericLeadingZero: allows leading zeros in numbers (e.g. 00012). If None is\n set, it uses the default value, ``false``.\n :param allowBackslashEscapingAnyCharacter: allows accepting quoting of all character\n using backslash quoting mechanism. If None is\n set, it uses the default value, ``false``.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n When inferring a schema, it implicitly adds a ``columnNameOfCorruptRecord`` \\\n field in an output schema.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param multiLine: parse one record, which may span multiple lines, per file. If None is\n set, it uses the default value, ``false``.\n :param allowUnquotedControlChars: allows JSON Strings to contain unquoted control\n characters (ASCII characters with value less than 32,\n including tab and line feed characters) or not.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param dropFieldIfAllNull: whether to ignore column of all null values or empty\n array/struct during schema inference. If None is set, it\n uses the default value, ``false``.\n :param encoding: allows to forcibly set one of standard basic or extended encoding for\n the JSON files. For example UTF-16BE, UTF-32LE. If None is set,\n the encoding of input JSON will be detected automatically\n when the multiLine option is set to ``true``.\n\n >>> json_sdf = spark.readStream.json(tempfile.mkdtemp(), schema = sdf_schema)\n >>> json_sdf.isStreaming\n True\n >>> json_sdf.schema == sdf_schema\n True\n " ]
Please provide a description of the function:def orc(self, path): if isinstance(path, basestring): return self._df(self._jreader.orc(path)) else: raise TypeError("path can be only a single string")
[ "Loads a ORC file stream, returning the result as a :class:`DataFrame`.\n\n .. note:: Evolving.\n\n >>> orc_sdf = spark.readStream.schema(sdf_schema).orc(tempfile.mkdtemp())\n >>> orc_sdf.isStreaming\n True\n >>> orc_sdf.schema == sdf_schema\n True\n " ]
Please provide a description of the function:def parquet(self, path): if isinstance(path, basestring): return self._df(self._jreader.parquet(path)) else: raise TypeError("path can be only a single string")
[ "Loads a Parquet file stream, returning the result as a :class:`DataFrame`.\n\n You can set the following Parquet-specific option(s) for reading Parquet files:\n * ``mergeSchema``: sets whether we should merge schemas collected from all \\\n Parquet part-files. This will override ``spark.sql.parquet.mergeSchema``. \\\n The default value is specified in ``spark.sql.parquet.mergeSchema``.\n\n .. note:: Evolving.\n\n >>> parquet_sdf = spark.readStream.schema(sdf_schema).parquet(tempfile.mkdtemp())\n >>> parquet_sdf.isStreaming\n True\n >>> parquet_sdf.schema == sdf_schema\n True\n " ]
Please provide a description of the function:def text(self, path, wholetext=False, lineSep=None): self._set_opts(wholetext=wholetext, lineSep=lineSep) if isinstance(path, basestring): return self._df(self._jreader.text(path)) else: raise TypeError("path can be only a single string")
[ "\n Loads a text file stream and returns a :class:`DataFrame` whose schema starts with a\n string column named \"value\", and followed by partitioned columns if there\n are any.\n The text files must be encoded as UTF-8.\n\n By default, each line in the text file is a new row in the resulting DataFrame.\n\n .. note:: Evolving.\n\n :param paths: string, or list of strings, for input path(s).\n :param wholetext: if true, read each file from input path(s) as a single row.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n\n >>> text_sdf = spark.readStream.text(tempfile.mkdtemp())\n >>> text_sdf.isStreaming\n True\n >>> \"value\" in str(text_sdf.schema)\n True\n " ]
Please provide a description of the function:def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None, comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None, ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None, negativeInf=None, dateFormat=None, timestampFormat=None, maxColumns=None, maxCharsPerColumn=None, maxMalformedLogPerPartition=None, mode=None, columnNameOfCorruptRecord=None, multiLine=None, charToEscapeQuoteEscaping=None, enforceSchema=None, emptyValue=None, locale=None, lineSep=None): r self._set_opts( schema=schema, sep=sep, encoding=encoding, quote=quote, escape=escape, comment=comment, header=header, inferSchema=inferSchema, ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace, nullValue=nullValue, nanValue=nanValue, positiveInf=positiveInf, negativeInf=negativeInf, dateFormat=dateFormat, timestampFormat=timestampFormat, maxColumns=maxColumns, maxCharsPerColumn=maxCharsPerColumn, maxMalformedLogPerPartition=maxMalformedLogPerPartition, mode=mode, columnNameOfCorruptRecord=columnNameOfCorruptRecord, multiLine=multiLine, charToEscapeQuoteEscaping=charToEscapeQuoteEscaping, enforceSchema=enforceSchema, emptyValue=emptyValue, locale=locale, lineSep=lineSep) if isinstance(path, basestring): return self._df(self._jreader.csv(path)) else: raise TypeError("path can be only a single string")
[ "Loads a CSV file stream and returns the result as a :class:`DataFrame`.\n\n This function will go through the input once to determine the input schema if\n ``inferSchema`` is enabled. To avoid going through the entire data once, disable\n ``inferSchema`` option or specify the schema explicitly using ``schema``.\n\n .. note:: Evolving.\n\n :param path: string, or list of strings, for input path(s).\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param sep: sets a single character as a separator for each field and value.\n If None is set, it uses the default value, ``,``.\n :param encoding: decodes the CSV files by the given encoding type. If None is set,\n it uses the default value, ``UTF-8``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If you would like to turn off quotations, you need to set an\n empty string.\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``.\n :param comment: sets a single character used for skipping lines beginning with this\n character. By default (None), it is disabled.\n :param header: uses the first line as names of columns. If None is set, it uses the\n default value, ``false``.\n :param inferSchema: infers the input schema automatically from data. It requires one extra\n pass over the data. If None is set, it uses the default value, ``false``.\n :param enforceSchema: If it is set to ``true``, the specified or inferred schema will be\n forcibly applied to datasource files, and headers in CSV files will be\n ignored. If the option is set to ``false``, the schema will be\n validated against all headers in CSV files or the first header in RDD\n if the ``header`` option is set to ``true``. Field names in the schema\n and column names in CSV headers are checked by their positions\n taking into account ``spark.sql.caseSensitive``. If None is set,\n ``true`` is used by default. Though the default value is ``true``,\n it is recommended to disable the ``enforceSchema`` option\n to avoid incorrect results.\n :param ignoreLeadingWhiteSpace: a flag indicating whether or not leading whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param ignoreTrailingWhiteSpace: a flag indicating whether or not trailing whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string. Since 2.0.1, this ``nullValue`` param\n applies to all supported types including the string type.\n :param nanValue: sets the string representation of a non-number value. If None is set, it\n uses the default value, ``NaN``.\n :param positiveInf: sets the string representation of a positive infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param negativeInf: sets the string representation of a negative infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param maxColumns: defines a hard limit of how many columns a record can have. If None is\n set, it uses the default value, ``20480``.\n :param maxCharsPerColumn: defines the maximum number of characters allowed for any given\n value being read. If None is set, it uses the default value,\n ``-1`` meaning unlimited length.\n :param maxMalformedLogPerPartition: this parameter is no longer used since Spark 2.2.0.\n If specified, it is ignored.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n A record with less/more tokens than schema is not a corrupted record to CSV. \\\n When it meets a record having fewer tokens than the length of the schema, \\\n sets ``null`` to extra fields. When the record has more tokens than the \\\n length of the schema, it drops extra tokens.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param multiLine: parse one record, which may span multiple lines. If None is\n set, it uses the default value, ``false``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise..\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, empty string.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n Maximum length is 1 character.\n\n >>> csv_sdf = spark.readStream.csv(tempfile.mkdtemp(), schema = sdf_schema)\n >>> csv_sdf.isStreaming\n True\n >>> csv_sdf.schema == sdf_schema\n True\n " ]
Please provide a description of the function:def outputMode(self, outputMode): if not outputMode or type(outputMode) != str or len(outputMode.strip()) == 0: raise ValueError('The output mode must be a non-empty string. Got: %s' % outputMode) self._jwrite = self._jwrite.outputMode(outputMode) return self
[ "Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.\n\n Options include:\n\n * `append`:Only the new rows in the streaming DataFrame/Dataset will be written to\n the sink\n * `complete`:All the rows in the streaming DataFrame/Dataset will be written to the sink\n every time these is some updates\n * `update`:only the rows that were updated in the streaming DataFrame/Dataset will be\n written to the sink every time there are some updates. If the query doesn't contain\n aggregations, it will be equivalent to `append` mode.\n\n .. note:: Evolving.\n\n >>> writer = sdf.writeStream.outputMode('append')\n " ]
Please provide a description of the function:def queryName(self, queryName): if not queryName or type(queryName) != str or len(queryName.strip()) == 0: raise ValueError('The queryName must be a non-empty string. Got: %s' % queryName) self._jwrite = self._jwrite.queryName(queryName) return self
[ "Specifies the name of the :class:`StreamingQuery` that can be started with\n :func:`start`. This name must be unique among all the currently active queries\n in the associated SparkSession.\n\n .. note:: Evolving.\n\n :param queryName: unique name for the query\n\n >>> writer = sdf.writeStream.queryName('streaming_query')\n " ]
Please provide a description of the function:def trigger(self, processingTime=None, once=None, continuous=None): params = [processingTime, once, continuous] if params.count(None) == 3: raise ValueError('No trigger provided') elif params.count(None) < 2: raise ValueError('Multiple triggers not allowed.') jTrigger = None if processingTime is not None: if type(processingTime) != str or len(processingTime.strip()) == 0: raise ValueError('Value for processingTime must be a non empty string. Got: %s' % processingTime) interval = processingTime.strip() jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.ProcessingTime( interval) elif once is not None: if once is not True: raise ValueError('Value for once must be True. Got: %s' % once) jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.Once() else: if type(continuous) != str or len(continuous.strip()) == 0: raise ValueError('Value for continuous must be a non empty string. Got: %s' % continuous) interval = continuous.strip() jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.Continuous( interval) self._jwrite = self._jwrite.trigger(jTrigger) return self
[ "Set the trigger for the stream query. If this is not set it will run the query as fast\n as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``.\n\n .. note:: Evolving.\n\n :param processingTime: a processing time interval as a string, e.g. '5 seconds', '1 minute'.\n Set a trigger that runs a query periodically based on the processing\n time. Only one trigger can be set.\n :param once: if set to True, set a trigger that processes only one batch of data in a\n streaming query then terminates the query. Only one trigger can be set.\n\n >>> # trigger the query for execution every 5 seconds\n >>> writer = sdf.writeStream.trigger(processingTime='5 seconds')\n >>> # trigger the query for just once batch of data\n >>> writer = sdf.writeStream.trigger(once=True)\n >>> # trigger the query for execution every 5 seconds\n >>> writer = sdf.writeStream.trigger(continuous='5 seconds')\n " ]
Please provide a description of the function:def foreach(self, f): from pyspark.rdd import _wrap_function from pyspark.serializers import PickleSerializer, AutoBatchedSerializer from pyspark.taskcontext import TaskContext if callable(f): # The provided object is a callable function that is supposed to be called on each row. # Construct a function that takes an iterator and calls the provided function on each # row. def func_without_process(_, iterator): for x in iterator: f(x) return iter([]) func = func_without_process else: # The provided object is not a callable function. Then it is expected to have a # 'process(row)' method, and optional 'open(partition_id, epoch_id)' and # 'close(error)' methods. if not hasattr(f, 'process'): raise Exception("Provided object does not have a 'process' method") if not callable(getattr(f, 'process')): raise Exception("Attribute 'process' in provided object is not callable") def doesMethodExist(method_name): exists = hasattr(f, method_name) if exists and not callable(getattr(f, method_name)): raise Exception( "Attribute '%s' in provided object is not callable" % method_name) return exists open_exists = doesMethodExist('open') close_exists = doesMethodExist('close') def func_with_open_process_close(partition_id, iterator): epoch_id = TaskContext.get().getLocalProperty('streaming.sql.batchId') if epoch_id: epoch_id = int(epoch_id) else: raise Exception("Could not get batch id from TaskContext") # Check if the data should be processed should_process = True if open_exists: should_process = f.open(partition_id, epoch_id) error = None try: if should_process: for x in iterator: f.process(x) except Exception as ex: error = ex finally: if close_exists: f.close(error) if error: raise error return iter([]) func = func_with_open_process_close serializer = AutoBatchedSerializer(PickleSerializer()) wrapped_func = _wrap_function(self._spark._sc, func, serializer, serializer) jForeachWriter = \ self._spark._sc._jvm.org.apache.spark.sql.execution.python.PythonForeachWriter( wrapped_func, self._df._jdf.schema()) self._jwrite.foreach(jForeachWriter) return self
[ "\n Sets the output of the streaming query to be processed using the provided writer ``f``.\n This is often used to write the output of a streaming query to arbitrary storage systems.\n The processing logic can be specified in two ways.\n\n #. A **function** that takes a row as input.\n This is a simple way to express your processing logic. Note that this does\n not allow you to deduplicate generated data when failures cause reprocessing of\n some input data. That would require you to specify the processing logic in the next\n way.\n\n #. An **object** with a ``process`` method and optional ``open`` and ``close`` methods.\n The object can have the following methods.\n\n * ``open(partition_id, epoch_id)``: *Optional* method that initializes the processing\n (for example, open a connection, start a transaction, etc). Additionally, you can\n use the `partition_id` and `epoch_id` to deduplicate regenerated data\n (discussed later).\n\n * ``process(row)``: *Non-optional* method that processes each :class:`Row`.\n\n * ``close(error)``: *Optional* method that finalizes and cleans up (for example,\n close connection, commit transaction, etc.) after all rows have been processed.\n\n The object will be used by Spark in the following way.\n\n * A single copy of this object is responsible of all the data generated by a\n single task in a query. In other words, one instance is responsible for\n processing one partition of the data generated in a distributed manner.\n\n * This object must be serializable because each task will get a fresh\n serialized-deserialized copy of the provided object. Hence, it is strongly\n recommended that any initialization for writing data (e.g. opening a\n connection or starting a transaction) is done after the `open(...)`\n method has been called, which signifies that the task is ready to generate data.\n\n * The lifecycle of the methods are as follows.\n\n For each partition with ``partition_id``:\n\n ... For each batch/epoch of streaming data with ``epoch_id``:\n\n ....... Method ``open(partitionId, epochId)`` is called.\n\n ....... If ``open(...)`` returns true, for each row in the partition and\n batch/epoch, method ``process(row)`` is called.\n\n ....... Method ``close(errorOrNull)`` is called with error (if any) seen while\n processing rows.\n\n Important points to note:\n\n * The `partitionId` and `epochId` can be used to deduplicate generated data when\n failures cause reprocessing of some input data. This depends on the execution\n mode of the query. If the streaming query is being executed in the micro-batch\n mode, then every partition represented by a unique tuple (partition_id, epoch_id)\n is guaranteed to have the same data. Hence, (partition_id, epoch_id) can be used\n to deduplicate and/or transactionally commit data and achieve exactly-once\n guarantees. However, if the streaming query is being executed in the continuous\n mode, then this guarantee does not hold and therefore should not be used for\n deduplication.\n\n * The ``close()`` method (if exists) will be called if `open()` method exists and\n returns successfully (irrespective of the return value), except if the Python\n crashes in the middle.\n\n .. note:: Evolving.\n\n >>> # Print every row using a function\n >>> def print_row(row):\n ... print(row)\n ...\n >>> writer = sdf.writeStream.foreach(print_row)\n >>> # Print every row using a object with process() method\n >>> class RowPrinter:\n ... def open(self, partition_id, epoch_id):\n ... print(\"Opened %d, %d\" % (partition_id, epoch_id))\n ... return True\n ... def process(self, row):\n ... print(row)\n ... def close(self, error):\n ... print(\"Closed with error: %s\" % str(error))\n ...\n >>> writer = sdf.writeStream.foreach(RowPrinter())\n " ]
Please provide a description of the function:def foreachBatch(self, func): from pyspark.java_gateway import ensure_callback_server_started gw = self._spark._sc._gateway java_import(gw.jvm, "org.apache.spark.sql.execution.streaming.sources.*") wrapped_func = ForeachBatchFunction(self._spark, func) gw.jvm.PythonForeachBatchHelper.callForeachBatch(self._jwrite, wrapped_func) ensure_callback_server_started(gw) return self
[ "\n Sets the output of the streaming query to be processed using the provided\n function. This is supported only the in the micro-batch execution modes (that is, when the\n trigger is not continuous). In every micro-batch, the provided function will be called in\n every micro-batch with (i) the output rows as a DataFrame and (ii) the batch identifier.\n The batchId can be used deduplicate and transactionally write the output\n (that is, the provided Dataset) to external systems. The output DataFrame is guaranteed\n to exactly same for the same batchId (assuming all operations are deterministic in the\n query).\n\n .. note:: Evolving.\n\n >>> def func(batch_df, batch_id):\n ... batch_df.collect()\n ...\n >>> writer = sdf.writeStream.foreach(func)\n " ]
Please provide a description of the function:def start(self, path=None, format=None, outputMode=None, partitionBy=None, queryName=None, **options): self.options(**options) if outputMode is not None: self.outputMode(outputMode) if partitionBy is not None: self.partitionBy(partitionBy) if format is not None: self.format(format) if queryName is not None: self.queryName(queryName) if path is None: return self._sq(self._jwrite.start()) else: return self._sq(self._jwrite.start(path))
[ "Streams the contents of the :class:`DataFrame` to a data source.\n\n The data source is specified by the ``format`` and a set of ``options``.\n If ``format`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n .. note:: Evolving.\n\n :param path: the path in a Hadoop supported file system\n :param format: the format used to save\n :param outputMode: specifies how data of a streaming DataFrame/Dataset is written to a\n streaming sink.\n\n * `append`:Only the new rows in the streaming DataFrame/Dataset will be written to the\n sink\n * `complete`:All the rows in the streaming DataFrame/Dataset will be written to the sink\n every time these is some updates\n * `update`:only the rows that were updated in the streaming DataFrame/Dataset will be\n written to the sink every time there are some updates. If the query doesn't contain\n aggregations, it will be equivalent to `append` mode.\n :param partitionBy: names of partitioning columns\n :param queryName: unique name for the query\n :param options: All other string options. You may want to provide a `checkpointLocation`\n for most streams, however it is not required for a `memory` stream.\n\n >>> sq = sdf.writeStream.format('memory').queryName('this_query').start()\n >>> sq.isActive\n True\n >>> sq.name\n u'this_query'\n >>> sq.stop()\n >>> sq.isActive\n False\n >>> sq = sdf.writeStream.trigger(processingTime='5 seconds').start(\n ... queryName='that_query', outputMode=\"append\", format='memory')\n >>> sq.name\n u'that_query'\n >>> sq.isActive\n True\n >>> sq.stop()\n " ]
Please provide a description of the function:def _make_cell_set_template_code(): def inner(value): lambda: cell # make ``cell`` a closure so that we get a STORE_DEREF cell = value co = inner.__code__ # NOTE: we are marking the cell variable as a free variable intentionally # so that we simulate an inner function instead of the outer function. This # is what gives us the ``nonlocal`` behavior in a Python 2 compatible way. if not PY3: # pragma: no branch return types.CodeType( co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, co.co_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_cellvars, # this is the trickery (), ) else: return types.CodeType( co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, co.co_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_cellvars, # this is the trickery (), )
[ "Get the Python compiler to emit LOAD_FAST(arg); STORE_DEREF\n\n Notes\n -----\n In Python 3, we could use an easier function:\n\n .. code-block:: python\n\n def f():\n cell = None\n\n def _stub(value):\n nonlocal cell\n cell = value\n\n return _stub\n\n _cell_set_template_code = f().__code__\n\n This function is _only_ a LOAD_FAST(arg); STORE_DEREF, but that is\n invalid syntax on Python 2. If we use this function we also don't need\n to do the weird freevars/cellvars swap below\n " ]
Please provide a description of the function:def is_tornado_coroutine(func): if 'tornado.gen' not in sys.modules: return False gen = sys.modules['tornado.gen'] if not hasattr(gen, "is_coroutine_function"): # Tornado version is too old return False return gen.is_coroutine_function(func)
[ "\n Return whether *func* is a Tornado coroutine function.\n Running coroutines are not supported.\n " ]
Please provide a description of the function:def dump(obj, file, protocol=None): CloudPickler(file, protocol=protocol).dump(obj)
[ "Serialize obj as bytes streamed into file\n\n protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to\n pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed\n between processes running the same Python version.\n\n Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure\n compatibility with older versions of Python.\n " ]
Please provide a description of the function:def dumps(obj, protocol=None): file = StringIO() try: cp = CloudPickler(file, protocol=protocol) cp.dump(obj) return file.getvalue() finally: file.close()
[ "Serialize obj as a string of bytes allocated in memory\n\n protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to\n pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed\n between processes running the same Python version.\n\n Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure\n compatibility with older versions of Python.\n " ]
Please provide a description of the function:def _fill_function(*args): if len(args) == 2: func = args[0] state = args[1] elif len(args) == 5: # Backwards compat for cloudpickle v0.4.0, after which the `module` # argument was introduced func = args[0] keys = ['globals', 'defaults', 'dict', 'closure_values'] state = dict(zip(keys, args[1:])) elif len(args) == 6: # Backwards compat for cloudpickle v0.4.1, after which the function # state was passed as a dict to the _fill_function it-self. func = args[0] keys = ['globals', 'defaults', 'dict', 'module', 'closure_values'] state = dict(zip(keys, args[1:])) else: raise ValueError('Unexpected _fill_value arguments: %r' % (args,)) # - At pickling time, any dynamic global variable used by func is # serialized by value (in state['globals']). # - At unpickling time, func's __globals__ attribute is initialized by # first retrieving an empty isolated namespace that will be shared # with other functions pickled from the same original module # by the same CloudPickler instance and then updated with the # content of state['globals'] to populate the shared isolated # namespace with all the global variables that are specifically # referenced for this function. func.__globals__.update(state['globals']) func.__defaults__ = state['defaults'] func.__dict__ = state['dict'] if 'annotations' in state: func.__annotations__ = state['annotations'] if 'doc' in state: func.__doc__ = state['doc'] if 'name' in state: func.__name__ = state['name'] if 'module' in state: func.__module__ = state['module'] if 'qualname' in state: func.__qualname__ = state['qualname'] cells = func.__closure__ if cells is not None: for cell, value in zip(cells, state['closure_values']): if value is not _empty_cell_value: cell_set(cell, value) return func
[ "Fills in the rest of function data into the skeleton function object\n\n The skeleton itself is create by _make_skel_func().\n " ]
Please provide a description of the function:def _rehydrate_skeleton_class(skeleton_class, class_dict): registry = None for attrname, attr in class_dict.items(): if attrname == "_abc_impl": registry = attr else: setattr(skeleton_class, attrname, attr) if registry is not None: for subclass in registry: skeleton_class.register(subclass) return skeleton_class
[ "Put attributes from `class_dict` back on `skeleton_class`.\n\n See CloudPickler.save_dynamic_class for more info.\n " ]
Please provide a description of the function: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 module.__spec__ is None else: # Backward compat for Python 2 import imp try: path = None for part in module.__name__.split('.'): if path is not None: path = [path] f, path, description = imp.find_module(part, path) if f is not None: f.close() except ImportError: return True return False
[ "\n Return True if the module is special module that cannot be imported by its\n name.\n " ]
Please provide a description of the function:def save_codeobject(self, obj): if PY3: # pragma: no branch args = ( obj.co_argcount, obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize, obj.co_flags, obj.co_code, obj.co_consts, obj.co_names, obj.co_varnames, obj.co_filename, obj.co_name, obj.co_firstlineno, obj.co_lnotab, obj.co_freevars, obj.co_cellvars ) else: args = ( obj.co_argcount, obj.co_nlocals, obj.co_stacksize, obj.co_flags, obj.co_code, obj.co_consts, obj.co_names, obj.co_varnames, obj.co_filename, obj.co_name, obj.co_firstlineno, obj.co_lnotab, obj.co_freevars, obj.co_cellvars ) self.save_reduce(types.CodeType, args, obj=obj)
[ "\n Save a code object\n " ]
Please provide a description of the function: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_case = False if should_special_case: # We keep a special-cased cache of built-in type constructors at # global scope, because these functions are structured very # differently in different python versions and implementations (for # example, they're instances of types.BuiltinFunctionType in # CPython, but they're ordinary types.FunctionType instances in # PyPy). # # If the function we've received is in that cache, we just # serialize it as a lookup into the cache. return self.save_reduce(_BUILTIN_TYPE_CONSTRUCTORS[obj], (), obj=obj) write = self.write if name is None: name = obj.__name__ try: # whichmodule() could fail, see # https://bitbucket.org/gutworth/six/issues/63/importing-six-breaks-pickling modname = pickle.whichmodule(obj, name) except Exception: modname = None # print('which gives %s %s %s' % (modname, obj, name)) try: themodule = sys.modules[modname] except KeyError: # eval'd items such as namedtuple give invalid items for their function __module__ modname = '__main__' if modname == '__main__': themodule = None try: lookedup_by_name = getattr(themodule, name, None) except Exception: lookedup_by_name = None if themodule: if lookedup_by_name is obj: return self.save_global(obj, name) # a builtin_function_or_method which comes in as an attribute of some # object (e.g., itertools.chain.from_iterable) will end # up with modname "__main__" and so end up here. But these functions # have no __code__ attribute in CPython, so the handling for # user-defined functions below will fail. # So we pickle them here using save_reduce; have to do it differently # for different python versions. if not hasattr(obj, '__code__'): if PY3: # pragma: no branch rv = obj.__reduce_ex__(self.proto) else: if hasattr(obj, '__self__'): rv = (getattr, (obj.__self__, name)) else: raise pickle.PicklingError("Can't pickle %r" % obj) return self.save_reduce(obj=obj, *rv) # if func is lambda, def'ed at prompt, is in main, or is nested, then # we'll pickle the actual function object rather than simply saving a # reference (as is done in default pickler), via save_function_tuple. if (islambda(obj) or getattr(obj.__code__, 'co_filename', None) == '<stdin>' or themodule is None): self.save_function_tuple(obj) return else: # func is nested if lookedup_by_name is None or lookedup_by_name is not obj: self.save_function_tuple(obj) return if obj.__dict__: # essentially save_reduce, but workaround needed to avoid recursion self.save(_restore_attr) write(pickle.MARK + pickle.GLOBAL + modname + '\n' + name + '\n') self.memoize(obj) self.save(obj.__dict__) write(pickle.TUPLE + pickle.REDUCE) else: write(pickle.GLOBAL + modname + '\n' + name + '\n') self.memoize(obj)
[ " Registered with the dispatch to handle all function types.\n\n Determines what kind of function obj is (e.g. lambda, defined at\n interactive prompt, etc) and handles the pickling appropriately.\n " ]
Please provide a description of the function:def save_dynamic_class(self, obj): clsdict = dict(obj.__dict__) # copy dict proxy to a dict clsdict.pop('__weakref__', None) # For ABCMeta in python3.7+, remove _abc_impl as it is not picklable. # This is a fix which breaks the cache but this only makes the first # calls to issubclass slower. if "_abc_impl" in clsdict: import abc (registry, _, _, _) = abc._get_dump(obj) clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry] # On PyPy, __doc__ is a readonly attribute, so we need to include it in # the initial skeleton class. This is safe because we know that the # doc can't participate in a cycle with the original class. type_kwargs = {'__doc__': clsdict.pop('__doc__', None)} if hasattr(obj, "__slots__"): type_kwargs['__slots__'] = obj.__slots__ # pickle string length optimization: member descriptors of obj are # created automatically from obj's __slots__ attribute, no need to # save them in obj's state if isinstance(obj.__slots__, string_types): clsdict.pop(obj.__slots__) else: for k in obj.__slots__: clsdict.pop(k, None) # If type overrides __dict__ as a property, include it in the type kwargs. # In Python 2, we can't set this attribute after construction. __dict__ = clsdict.pop('__dict__', None) if isinstance(__dict__, property): type_kwargs['__dict__'] = __dict__ save = self.save write = self.write # We write pickle instructions explicitly here to handle the # possibility that the type object participates in a cycle with its own # __dict__. We first write an empty "skeleton" version of the class and # memoize it before writing the class' __dict__ itself. We then write # instructions to "rehydrate" the skeleton class by restoring the # attributes from the __dict__. # # A type can appear in a cycle with its __dict__ if an instance of the # type appears in the type's __dict__ (which happens for the stdlib # Enum class), or if the type defines methods that close over the name # of the type, (which is common for Python 2-style super() calls). # Push the rehydration function. save(_rehydrate_skeleton_class) # Mark the start of the args tuple for the rehydration function. write(pickle.MARK) # Create and memoize an skeleton class with obj's name and bases. tp = type(obj) self.save_reduce(tp, (obj.__name__, obj.__bases__, type_kwargs), obj=obj) # Now save the rest of obj's __dict__. Any references to obj # encountered while saving will point to the skeleton class. save(clsdict) # Write a tuple of (skeleton_class, clsdict). write(pickle.TUPLE) # Call _rehydrate_skeleton_class(skeleton_class, clsdict) write(pickle.REDUCE)
[ "\n Save a class that can't be stored as module global.\n\n This method is used to serialize classes that are defined inside\n functions, or that otherwise can't be serialized as attribute lookups\n from global modules.\n " ]
Please provide a description of the function:def save_function_tuple(self, func): if is_tornado_coroutine(func): self.save_reduce(_rebuild_tornado_coroutine, (func.__wrapped__,), obj=func) return save = self.save write = self.write code, f_globals, defaults, closure_values, dct, base_globals = self.extract_func_data(func) save(_fill_function) # skeleton function updater write(pickle.MARK) # beginning of tuple that _fill_function expects self._save_subimports( code, itertools.chain(f_globals.values(), closure_values or ()), ) # create a skeleton function object and memoize it save(_make_skel_func) save(( code, len(closure_values) if closure_values is not None else -1, base_globals, )) write(pickle.REDUCE) self.memoize(func) # save the rest of the func data needed by _fill_function state = { 'globals': f_globals, 'defaults': defaults, 'dict': dct, 'closure_values': closure_values, 'module': func.__module__, 'name': func.__name__, 'doc': func.__doc__, } if hasattr(func, '__annotations__') and sys.version_info >= (3, 7): state['annotations'] = func.__annotations__ if hasattr(func, '__qualname__'): state['qualname'] = func.__qualname__ save(state) write(pickle.TUPLE) write(pickle.REDUCE)
[ " Pickles an actual func object.\n\n A func comprises: code, globals, defaults, closure, and dict. We\n extract and save these, injecting reducing functions at certain points\n to recreate the func object. Keep in mind that some of these pieces\n can contain a ref to the func itself. Thus, a naive save on these\n pieces could trigger an infinite loop of save's. To get around that,\n we first create a skeleton func object using just the code (this is\n safe, since this won't contain a ref to the func), and memoize it as\n soon as it's created. The other stuff can then be filled in later.\n " ]
Please provide a description of the function:def save_global(self, obj, name=None, pack=struct.pack): if obj is type(None): return self.save_reduce(type, (None,), obj=obj) elif obj is type(Ellipsis): return self.save_reduce(type, (Ellipsis,), obj=obj) elif obj is type(NotImplemented): return self.save_reduce(type, (NotImplemented,), obj=obj) if obj.__module__ == "__main__": return self.save_dynamic_class(obj) try: return Pickler.save_global(self, obj, name=name) except Exception: if obj.__module__ == "__builtin__" or obj.__module__ == "builtins": if obj in _BUILTIN_TYPE_NAMES: return self.save_reduce( _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj) typ = type(obj) if typ is not obj and isinstance(obj, (type, types.ClassType)): return self.save_dynamic_class(obj) raise
[ "\n Save a \"global\".\n\n The name of this method is somewhat misleading: all types get\n dispatched here.\n " ]
Please provide a description of the function: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, obj) # Call unbound method with explicit self return memo = self.memo write = self.write save = self.save if hasattr(obj, '__getinitargs__'): args = obj.__getinitargs__() len(args) # XXX Assert it's a sequence pickle._keep_alive(args, memo) else: args = () write(pickle.MARK) if self.bin: save(cls) for arg in args: save(arg) write(pickle.OBJ) else: for arg in args: save(arg) write(pickle.INST + cls.__module__ + '\n' + cls.__name__ + '\n') self.memoize(obj) try: getstate = obj.__getstate__ except AttributeError: stuff = obj.__dict__ else: stuff = getstate() pickle._keep_alive(stuff, memo) save(stuff) write(pickle.BUILD)
[ "Inner logic to save instance. Based off pickle.save_inst" ]
Please provide a description of the function:def save_itemgetter(self, obj): class Dummy: def __getitem__(self, item): return item items = obj(Dummy()) if not isinstance(items, tuple): items = (items,) return self.save_reduce(operator.itemgetter, items)
[ "itemgetter serializer (needed for namedtuple support)" ]
Please provide a description of the function:def save_attrgetter(self, obj): class Dummy(object): def __init__(self, attrs, index=None): self.attrs = attrs self.index = index def __getattribute__(self, item): attrs = object.__getattribute__(self, "attrs") index = object.__getattribute__(self, "index") if index is None: index = len(attrs) attrs.append(item) else: attrs[index] = ".".join([attrs[index], item]) return type(self)(attrs, index) attrs = [] obj(Dummy(attrs)) return self.save_reduce(operator.attrgetter, tuple(attrs))
[ "attrgetter serializer" ]
Please provide a description of the function:def _copy_new_parent(self, parent): if self.parent == "undefined": param = copy.copy(self) param.parent = parent.uid return param else: raise ValueError("Cannot copy from non-dummy parent %s." % parent)
[ "Copy the current param to a new parent, must be a dummy param." ]
Please provide a description of the function:def toList(value): 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.toArray()) else: raise TypeError("Could not convert %s to list" % value)
[ "\n Convert a value to a list, if possible.\n " ]
Please provide a description of the function:def toListFloat(value): 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 in value] raise TypeError("Could not convert %s to list of floats" % value)
[ "\n Convert a value to list of floats, if possible.\n " ]
Please provide a description of the function:def toListInt(value): 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 value] raise TypeError("Could not convert %s to list of ints" % value)
[ "\n Convert a value to list of ints, if possible.\n " ]
Please provide a description of the function:def toListString(value): if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._can_convert_to_string(v), value)): return [TypeConverters.toString(v) for v in value] raise TypeError("Could not convert %s to list of strings" % value)
[ "\n Convert a value to list of strings, if possible.\n " ]
Please provide a description of the function:def toVector(value): if isinstance(value, Vector): return value elif TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._is_numeric(v), value)): return DenseVector(value) raise TypeError("Could not convert %s to vector" % value)
[ "\n Convert a value to a MLlib Vector, if possible.\n " ]
Please provide a description of the function:def toString(value): 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) else: raise TypeError("Could not convert %s to string type" % type(value))
[ "\n Convert a value to a string, if possible.\n " ]
Please provide a description of the function:def _copy_params(self): 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, param in src_params: setattr(self, name, param._copy_new_parent(self))
[ "\n Copy all params defined on the class to current object.\n " ]
Please provide a description of the function:def params(self): if self._params is None: self._params = list(filter(lambda attr: isinstance(attr, Param), [getattr(self, x) for x in dir(self) if x != "params" and not isinstance(getattr(type(self), x, None), property)])) return self._params
[ "\n Returns all params ordered by name. The default implementation\n uses :py:func:`dir` to get all attributes of type\n :py:class:`Param`.\n " ]
Please provide a description of the function:def explainParam(self, param): param = self._resolveParam(param) values = [] if self.isDefined(param): if param in self._defaultParamMap: values.append("default: %s" % self._defaultParamMap[param]) if param in self._paramMap: values.append("current: %s" % self._paramMap[param]) else: values.append("undefined") valueStr = "(" + ", ".join(values) + ")" return "%s: %s %s" % (param.name, param.doc, valueStr)
[ "\n Explains a single param and returns its name, doc, and optional\n default value and user-supplied value in a string.\n " ]
Please provide a description of the function:def getParam(self, paramName): param = getattr(self, paramName) if isinstance(param, Param): return param else: raise ValueError("Cannot find param with name %s." % paramName)
[ "\n Gets a param by its name.\n " ]
Please provide a description of the function:def isSet(self, param): param = self._resolveParam(param) return param in self._paramMap
[ "\n Checks whether a param is explicitly set by user.\n " ]
Please provide a description of the function:def hasDefault(self, param): param = self._resolveParam(param) return param in self._defaultParamMap
[ "\n Checks whether a param has a default value.\n " ]
Please provide a description of the function:def hasParam(self, paramName): if isinstance(paramName, basestring): p = getattr(self, paramName, None) return isinstance(p, Param) else: raise TypeError("hasParam(): paramName must be a string")
[ "\n Tests whether this instance contains a param with a given\n (string) name.\n " ]
Please provide a description of the function:def getOrDefault(self, param): param = self._resolveParam(param) if param in self._paramMap: return self._paramMap[param] else: return self._defaultParamMap[param]
[ "\n Gets the value of a param in the user-supplied param map or its\n default value. Raises an error if neither is set.\n " ]
Please provide a description of the function:def extractParamMap(self, extra=None): if extra is None: extra = dict() paramMap = self._defaultParamMap.copy() paramMap.update(self._paramMap) paramMap.update(extra) return paramMap
[ "\n Extracts the embedded default param values and user-supplied\n values, and then merges them with extra values from input into\n a flat param map, where the latter value is used if there exist\n conflicts, i.e., with ordering: default param values <\n user-supplied values < extra.\n\n :param extra: extra param values\n :return: merged param map\n " ]
Please provide a description of the function:def copy(self, extra=None): if extra is None: extra = dict() that = copy.copy(self) that._paramMap = {} that._defaultParamMap = {} return self._copyValues(that, extra)
[ "\n Creates a copy of this instance with the same uid and some\n extra params. The default implementation creates a\n shallow copy using :py:func:`copy.copy`, and then copies the\n embedded and extra parameters over and returns the copy.\n Subclasses should override this method if the default approach\n is not sufficient.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance\n " ]
Please provide a description of the function:def set(self, param, value): 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)) self._paramMap[param] = value
[ "\n Sets a parameter in the embedded param map.\n " ]
Please provide a description of the function:def _shouldOwn(self, param): if not (self.uid == param.parent and self.hasParam(param.name)): raise ValueError("Param %r does not belong to %r." % (param, self))
[ "\n Validates that the input param belongs to this Params instance.\n " ]
Please provide a description of the function:def _resolveParam(self, param): if isinstance(param, Param): self._shouldOwn(param) return param elif isinstance(param, basestring): return self.getParam(param) else: raise ValueError("Cannot resolve %r as a param." % param)
[ "\n Resolves a param and validates the ownership.\n\n :param param: param name or the param instance, which must\n belong to this Params instance\n :return: resolved param instance\n " ]
Please provide a description of the function:def _set(self, **kwargs): for param, value in kwargs.items(): p = getattr(self, param) if value is not None: try: value = p.typeConverter(value) except TypeError as e: raise TypeError('Invalid param value given for param "%s". %s' % (p.name, e)) self._paramMap[p] = value return self
[ "\n Sets user-supplied params.\n " ]
Please provide a description of the function:def _setDefault(self, **kwargs): 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) except TypeError as e: raise TypeError('Invalid default param value given for param "%s". %s' % (p.name, e)) self._defaultParamMap[p] = value return self
[ "\n Sets default params.\n " ]
Please provide a description of the function:def _copyValues(self, to, extra=None): paramMap = self._paramMap.copy() if extra is not None: paramMap.update(extra) for param in self.params: # copy default params if param in self._defaultParamMap and to.hasParam(param.name): to._defaultParamMap[to.getParam(param.name)] = self._defaultParamMap[param] # copy explicitly set params if param in paramMap and to.hasParam(param.name): to._set(**{param.name: paramMap[param]}) return to
[ "\n Copies param values from this instance to another instance for\n params shared by them.\n\n :param to: the target instance\n :param extra: extra params to be copied\n :return: the target instance with param values copied\n " ]
Please provide a description of the function:def _resetUid(self, newUid): newUid = unicode(newUid) self.uid = newUid newDefaultParamMap = dict() newParamMap = dict() for param in self.params: newParam = copy.copy(param) newParam.parent = newUid if param in self._defaultParamMap: newDefaultParamMap[newParam] = self._defaultParamMap[param] if param in self._paramMap: newParamMap[newParam] = self._paramMap[param] param.parent = newUid self._defaultParamMap = newDefaultParamMap self._paramMap = newParamMap return self
[ "\n Changes the uid of this instance. This updates both\n the stored uid and the parent uid of params and param maps.\n This is used by persistence (loading).\n :param newUid: new uid to use, which is converted to unicode\n :return: same instance, but with the uid and Param.parent values\n updated, including within param maps\n " ]
Please provide a description of the function:def _to_java_object_rdd(rdd): rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer())) return rdd.ctx._jvm.org.apache.spark.ml.python.MLSerDe.pythonToJava(rdd._jrdd, True)
[ " Return an JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.\n " ]
Please provide a description of the function: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 decryption is handled already if self._sc is not None and self._sc._encryption_enabled: port, auth_secret = self._python_broadcast.setupDecryptionServer() (decrypted_sock_file, _) = local_connect_and_auth(port, auth_secret) self._python_broadcast.waitTillBroadcastDataSent() return self.load(decrypted_sock_file) else: self._value = self.load_from_path(self._path) return self._value
[ " Return the broadcasted value\n " ]
Please provide a description of the function:def unpersist(self, blocking=False): if self._jbroadcast is None: raise Exception("Broadcast can only be unpersisted in driver") self._jbroadcast.unpersist(blocking)
[ "\n Delete cached copies of this broadcast on the executors. If the\n broadcast is used after this is called, it will need to be\n re-sent to each executor.\n\n :param blocking: Whether to block until unpersisting has completed\n " ]
Please provide a description of the function:def destroy(self, blocking=False): if self._jbroadcast is None: raise Exception("Broadcast can only be destroyed in driver") self._jbroadcast.destroy(blocking) os.unlink(self._path)
[ "\n Destroy all data and metadata related to this broadcast variable.\n Use this with caution; once a broadcast variable has been destroyed,\n it cannot be used again.\n\n .. versionchanged:: 3.0.0\n Added optional argument `blocking` to specify whether to block until all\n blocks are deleted.\n " ]
Please provide a description of the function: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 # function. So, we take out these attribute names from the default names to set and # then manually assign it after being wrapped. assignments = tuple( a for a in functools.WRAPPER_ASSIGNMENTS if a != '__name__' and a != '__module__') @functools.wraps(self.func, assigned=assignments) def wrapper(*args): return self(*args) wrapper.__name__ = self._name wrapper.__module__ = (self.func.__module__ if hasattr(self.func, '__module__') else self.func.__class__.__module__) wrapper.func = self.func wrapper.returnType = self.returnType wrapper.evalType = self.evalType wrapper.deterministic = self.deterministic wrapper.asNondeterministic = functools.wraps( self.asNondeterministic)(lambda: self.asNondeterministic()._wrapped()) return wrapper
[ "\n Wrap this udf with a function and attach docstring from func\n " ]
Please provide a description of the function:def register(self, name, f, returnType=None): # This is to check whether the input function is from a user-defined function or # Python function. if hasattr(f, 'asNondeterministic'): if returnType is not None: raise TypeError( "Invalid returnType: data type can not be specified when f is" "a user-defined function, but got %s." % returnType) if f.evalType not in [PythonEvalType.SQL_BATCHED_UDF, PythonEvalType.SQL_SCALAR_PANDAS_UDF, PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF]: raise ValueError( "Invalid f: f must be SQL_BATCHED_UDF, SQL_SCALAR_PANDAS_UDF or " "SQL_GROUPED_AGG_PANDAS_UDF") register_udf = UserDefinedFunction(f.func, returnType=f.returnType, name=name, evalType=f.evalType, deterministic=f.deterministic) return_udf = f else: if returnType is None: returnType = StringType() register_udf = UserDefinedFunction(f, returnType=returnType, name=name, evalType=PythonEvalType.SQL_BATCHED_UDF) return_udf = register_udf._wrapped() self.sparkSession._jsparkSession.udf().registerPython(name, register_udf._judf) return return_udf
[ "Register a Python function (including lambda function) or a user-defined function\n as a SQL function.\n\n :param name: name of the user-defined function in SQL statements.\n :param f: a Python function, or a user-defined function. The user-defined function can\n be either row-at-a-time or vectorized. See :meth:`pyspark.sql.functions.udf` and\n :meth:`pyspark.sql.functions.pandas_udf`.\n :param returnType: the return type of the registered user-defined function. The value can\n be either a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n :return: a user-defined function.\n\n To register a nondeterministic Python function, users need to first build\n a nondeterministic user-defined function for the Python function and then register it\n as a SQL function.\n\n `returnType` can be optionally specified when `f` is a Python function but not\n when `f` is a user-defined function. Please see below.\n\n 1. When `f` is a Python function:\n\n `returnType` defaults to string type and can be optionally specified. The produced\n object must match the specified type. In this case, this API works as if\n `register(name, f, returnType=StringType())`.\n\n >>> strlen = spark.udf.register(\"stringLengthString\", lambda x: len(x))\n >>> spark.sql(\"SELECT stringLengthString('test')\").collect()\n [Row(stringLengthString(test)=u'4')]\n\n >>> spark.sql(\"SELECT 'foo' AS text\").select(strlen(\"text\")).collect()\n [Row(stringLengthString(text)=u'3')]\n\n >>> from pyspark.sql.types import IntegerType\n >>> _ = spark.udf.register(\"stringLengthInt\", lambda x: len(x), IntegerType())\n >>> spark.sql(\"SELECT stringLengthInt('test')\").collect()\n [Row(stringLengthInt(test)=4)]\n\n >>> from pyspark.sql.types import IntegerType\n >>> _ = spark.udf.register(\"stringLengthInt\", lambda x: len(x), IntegerType())\n >>> spark.sql(\"SELECT stringLengthInt('test')\").collect()\n [Row(stringLengthInt(test)=4)]\n\n 2. When `f` is a user-defined function:\n\n Spark uses the return type of the given user-defined function as the return type of\n the registered user-defined function. `returnType` should not be specified.\n In this case, this API works as if `register(name, f)`.\n\n >>> from pyspark.sql.types import IntegerType\n >>> from pyspark.sql.functions import udf\n >>> slen = udf(lambda s: len(s), IntegerType())\n >>> _ = spark.udf.register(\"slen\", slen)\n >>> spark.sql(\"SELECT slen('test')\").collect()\n [Row(slen(test)=4)]\n\n >>> import random\n >>> from pyspark.sql.functions import udf\n >>> from pyspark.sql.types import IntegerType\n >>> random_udf = udf(lambda: random.randint(0, 100), IntegerType()).asNondeterministic()\n >>> new_random_udf = spark.udf.register(\"random_udf\", random_udf)\n >>> spark.sql(\"SELECT random_udf()\").collect() # doctest: +SKIP\n [Row(random_udf()=82)]\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> @pandas_udf(\"integer\", PandasUDFType.SCALAR) # doctest: +SKIP\n ... def add_one(x):\n ... return x + 1\n ...\n >>> _ = spark.udf.register(\"add_one\", add_one) # doctest: +SKIP\n >>> spark.sql(\"SELECT add_one(id) FROM range(3)\").collect() # doctest: +SKIP\n [Row(add_one(id)=1), Row(add_one(id)=2), Row(add_one(id)=3)]\n\n >>> @pandas_udf(\"integer\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def sum_udf(v):\n ... return v.sum()\n ...\n >>> _ = spark.udf.register(\"sum_udf\", sum_udf) # doctest: +SKIP\n >>> q = \"SELECT sum_udf(v1) FROM VALUES (3, 0), (2, 0), (1, 1) tbl(v1, v2) GROUP BY v2\"\n >>> spark.sql(q).collect() # doctest: +SKIP\n [Row(sum_udf(v1)=1), Row(sum_udf(v1)=5)]\n\n .. note:: Registration for a user-defined function (case 2.) was added from\n Spark 2.3.0.\n " ]
Please provide a description of the function:def registerJavaFunction(self, name, javaClassName, returnType=None): jdt = None if returnType is not None: if not isinstance(returnType, DataType): returnType = _parse_datatype_string(returnType) jdt = self.sparkSession._jsparkSession.parseDataType(returnType.json()) self.sparkSession._jsparkSession.udf().registerJava(name, javaClassName, jdt)
[ "Register a Java user-defined function as a SQL function.\n\n In addition to a name and the function itself, the return type can be optionally specified.\n When the return type is not specified we would infer it via reflection.\n\n :param name: name of the user-defined function\n :param javaClassName: fully qualified name of java class\n :param returnType: the return type of the registered Java function. The value can be either\n a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n\n >>> from pyspark.sql.types import IntegerType\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength\", \"test.org.apache.spark.sql.JavaStringLength\", IntegerType())\n >>> spark.sql(\"SELECT javaStringLength('test')\").collect()\n [Row(UDF:javaStringLength(test)=4)]\n\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength2\", \"test.org.apache.spark.sql.JavaStringLength\")\n >>> spark.sql(\"SELECT javaStringLength2('test')\").collect()\n [Row(UDF:javaStringLength2(test)=4)]\n\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength3\", \"test.org.apache.spark.sql.JavaStringLength\", \"integer\")\n >>> spark.sql(\"SELECT javaStringLength3('test')\").collect()\n [Row(UDF:javaStringLength3(test)=4)]\n " ]
Please provide a description of the function:def registerJavaUDAF(self, name, javaClassName): self.sparkSession._jsparkSession.udf().registerJavaUDAF(name, javaClassName)
[ "Register a Java user-defined aggregate function as a SQL function.\n\n :param name: name of the user-defined aggregate function\n :param javaClassName: fully qualified name of java class\n\n >>> spark.udf.registerJavaUDAF(\"javaUDAF\", \"test.org.apache.spark.sql.MyDoubleAvg\")\n >>> df = spark.createDataFrame([(1, \"a\"),(2, \"b\"), (3, \"a\")],[\"id\", \"name\"])\n >>> df.createOrReplaceTempView(\"df\")\n >>> spark.sql(\"SELECT name, javaUDAF(id) as avg from df group by name\").collect()\n [Row(name=u'b', avg=102.0), Row(name=u'a', avg=102.0)]\n " ]
Please provide a description of the function:def getOrCreate(cls, checkpointPath, setupFunc): cls._ensure_initialized() gw = SparkContext._gateway # Check whether valid checkpoint information exists in the given path ssc_option = gw.jvm.StreamingContextPythonHelper().tryRecoverFromCheckpoint(checkpointPath) if ssc_option.isEmpty(): ssc = setupFunc() ssc.checkpoint(checkpointPath) return ssc jssc = gw.jvm.JavaStreamingContext(ssc_option.get()) # If there is already an active instance of Python SparkContext use it, or create a new one if not SparkContext._active_spark_context: jsc = jssc.sparkContext() conf = SparkConf(_jconf=jsc.getConf()) SparkContext(conf=conf, gateway=gw, jsc=jsc) sc = SparkContext._active_spark_context # update ctx in serializer cls._transformerSerializer.ctx = sc return StreamingContext(sc, None, jssc)
[ "\n Either recreate a StreamingContext from checkpoint data or create a new StreamingContext.\n If checkpoint data exists in the provided `checkpointPath`, then StreamingContext will be\n recreated from the checkpoint data. If the data does not exist, then the provided setupFunc\n will be used to create a new context.\n\n @param checkpointPath: Checkpoint directory used in an earlier streaming program\n @param setupFunc: Function to create a new context and setup DStreams\n " ]
Please provide a description of the function:def getActive(cls): activePythonContext = cls._activeContext if activePythonContext is not None: # Verify that the current running Java StreamingContext is active and is the same one # backing the supposedly active Python context activePythonContextJavaId = activePythonContext._jssc.ssc().hashCode() activeJvmContextOption = activePythonContext._jvm.StreamingContext.getActive() if activeJvmContextOption.isEmpty(): cls._activeContext = None elif activeJvmContextOption.get().hashCode() != activePythonContextJavaId: cls._activeContext = None raise Exception("JVM's active JavaStreamingContext is not the JavaStreamingContext " "backing the action Python StreamingContext. This is unexpected.") return cls._activeContext
[ "\n Return either the currently active StreamingContext (i.e., if there is a context started\n but not stopped) or None.\n " ]
Please provide a description of the function:def getActiveOrCreate(cls, checkpointPath, setupFunc): if setupFunc is None: raise Exception("setupFunc cannot be None") activeContext = cls.getActive() if activeContext is not None: return activeContext elif checkpointPath is not None: return cls.getOrCreate(checkpointPath, setupFunc) else: return setupFunc()
[ "\n Either return the active StreamingContext (i.e. currently started but not stopped),\n or recreate a StreamingContext from checkpoint data or create a new StreamingContext\n using the provided setupFunc function. If the checkpointPath is None or does not contain\n valid checkpoint data, then setupFunc will be called to create a new context and setup\n DStreams.\n\n @param checkpointPath: Checkpoint directory used in an earlier streaming program. Can be\n None if the intention is to always create a new context when there\n is no active context.\n @param setupFunc: Function to create a new JavaStreamingContext and setup DStreams\n " ]
Please provide a description of the function:def awaitTermination(self, timeout=None): if timeout is None: self._jssc.awaitTermination() else: self._jssc.awaitTerminationOrTimeout(int(timeout * 1000))
[ "\n Wait for the execution to stop.\n\n @param timeout: time to wait in seconds\n " ]
Please provide a description of the function:def stop(self, stopSparkContext=True, stopGraceFully=False): self._jssc.stop(stopSparkContext, stopGraceFully) StreamingContext._activeContext = None if stopSparkContext: self._sc.stop()
[ "\n Stop the execution of the streams, with option of ensuring all\n received data has been processed.\n\n @param stopSparkContext: Stop the associated SparkContext or not\n @param stopGracefully: Stop gracefully by waiting for the processing\n of all received data to be completed\n " ]
Please provide a description of the function:def socketTextStream(self, hostname, port, storageLevel=StorageLevel.MEMORY_AND_DISK_2): jlevel = self._sc._getJavaStorageLevel(storageLevel) return DStream(self._jssc.socketTextStream(hostname, port, jlevel), self, UTF8Deserializer())
[ "\n Create an input from TCP source hostname:port. Data is received using\n a TCP socket and receive byte is interpreted as UTF8 encoded ``\\\\n`` delimited\n lines.\n\n @param hostname: Hostname to connect to for receiving data\n @param port: Port to connect to for receiving data\n @param storageLevel: Storage level to use for storing the received objects\n " ]
Please provide a description of the function:def textFileStream(self, directory): return DStream(self._jssc.textFileStream(directory), self, UTF8Deserializer())
[ "\n Create an input stream that monitors a Hadoop-compatible file system\n for new files and reads them as text files. Files must be wrriten to the\n monitored directory by \"moving\" them from another location within the same\n file system. File names starting with . are ignored.\n The text files must be encoded as UTF-8.\n " ]
Please provide a description of the function:def binaryRecordsStream(self, directory, recordLength): return DStream(self._jssc.binaryRecordsStream(directory, recordLength), self, NoOpSerializer())
[ "\n Create an input stream that monitors a Hadoop-compatible file system\n for new files and reads them as flat binary files with records of\n fixed length. Files must be written to the monitored directory by \"moving\"\n them from another location within the same file system.\n File names starting with . are ignored.\n\n @param directory: Directory to load data from\n @param recordLength: Length of each record in bytes\n " ]
Please provide a description of the function:def queueStream(self, rdds, oneAtATime=True, default=None): if default and not isinstance(default, RDD): default = self._sc.parallelize(default) if not rdds and default: rdds = [rdds] if rdds and not isinstance(rdds[0], RDD): rdds = [self._sc.parallelize(input) for input in rdds] self._check_serializers(rdds) queue = self._jvm.PythonDStream.toRDDQueue([r._jrdd for r in rdds]) if default: default = default._reserialize(rdds[0]._jrdd_deserializer) jdstream = self._jssc.queueStream(queue, oneAtATime, default._jrdd) else: jdstream = self._jssc.queueStream(queue, oneAtATime) return DStream(jdstream, self, rdds[0]._jrdd_deserializer)
[ "\n Create an input stream from a queue of RDDs or list. In each batch,\n it will process either one or all of the RDDs returned by the queue.\n\n .. note:: Changes to the queue after the stream is created will not be recognized.\n\n @param rdds: Queue of RDDs\n @param oneAtATime: pick one rdd each time or pick all of them once.\n @param default: The default rdd if no more in rdds\n " ]
Please provide a description of the function:def transform(self, dstreams, transformFunc): jdstreams = [d._jdstream for d in dstreams] # change the final serializer to sc.serializer func = TransformFunction(self._sc, lambda t, *rdds: transformFunc(rdds), *[d._jrdd_deserializer for d in dstreams]) jfunc = self._jvm.TransformFunction(func) jdstream = self._jssc.transform(jdstreams, jfunc) return DStream(jdstream, self, self._sc.serializer)
[ "\n Create a new DStream in which each RDD is generated by applying\n a function on RDDs of the DStreams. The order of the JavaRDDs in\n the transform function parameter will be the same as the order\n of corresponding DStreams in the list.\n " ]
Please provide a description of the function:def union(self, *dstreams): if not dstreams: raise ValueError("should have at least one DStream to union") if len(dstreams) == 1: return dstreams[0] if len(set(s._jrdd_deserializer for s in dstreams)) > 1: raise ValueError("All DStreams should have same serializer") if len(set(s._slideDuration for s in dstreams)) > 1: raise ValueError("All DStreams should have same slide duration") cls = SparkContext._jvm.org.apache.spark.streaming.api.java.JavaDStream jdstreams = SparkContext._gateway.new_array(cls, len(dstreams)) for i in range(0, len(dstreams)): jdstreams[i] = dstreams[i]._jdstream return DStream(self._jssc.union(jdstreams), self, dstreams[0]._jrdd_deserializer)
[ "\n Create a unified DStream from multiple DStreams of the same\n type and same slide duration.\n " ]
Please provide a description of the function:def addStreamingListener(self, streamingListener): self._jssc.addStreamingListener(self._jvm.JavaStreamingListenerWrapper( self._jvm.PythonStreamingListenerWrapper(streamingListener)))
[ "\n Add a [[org.apache.spark.streaming.scheduler.StreamingListener]] object for\n receiving system events related to streaming.\n " ]
Please provide a description of the function:def load_tf_weights_in_gpt2(model, gpt2_checkpoint_path): try: import re import numpy as np import tensorflow as tf except ImportError: print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions.") raise tf_path = os.path.abspath(gpt2_checkpoint_path) print("Converting TensorFlow checkpoint from {}".format(tf_path)) # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] arrays = [] for name, shape in init_vars: print("Loading TF weight {} with shape {}".format(name, shape)) array = tf.train.load_variable(tf_path, name) names.append(name) arrays.append(array.squeeze()) for name, array in zip(names, arrays): name = name[6:] # skip "model/" name = name.split('/') pointer = model for m_name in name: if re.fullmatch(r'[A-Za-z]+\d+', m_name): l = re.split(r'(\d+)', m_name) else: l = [m_name] if l[0] == 'w' or l[0] == 'g': pointer = getattr(pointer, 'weight') elif l[0] == 'b': pointer = getattr(pointer, 'bias') elif l[0] == 'wpe' or l[0] == 'wte': pointer = getattr(pointer, l[0]) pointer = getattr(pointer, 'weight') else: pointer = getattr(pointer, l[0]) if len(l) >= 2: num = int(l[1]) pointer = pointer[num] try: assert pointer.shape == array.shape except AssertionError as e: e.args += (pointer.shape, array.shape) raise print("Initialize PyTorch weight {}".format(name)) pointer.data = torch.from_numpy(array) return model
[ " Load tf checkpoints in a pytorch model\n " ]
Please provide a description of the function:def from_json_file(cls, json_file): with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() return cls.from_dict(json.loads(text))
[ "Constructs a `GPT2Config` from a json file of parameters." ]
Please provide a description of the function: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." ]
Please provide a description of the function:def init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) elif isinstance(module, LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_()
[ " Initialize the weights.\n " ]