Code
stringlengths
103
85.9k
Summary
listlengths
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._inferSch...
[ "\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_dty...
[ "\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 correctio...
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 ...
[ "\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_min...
[ "\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(...
[ "\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("...
[ "\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)...
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,...
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 ...
[ "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:]] ...
[ "\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)...
[ " 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): ...
[ "\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 isinsta...
[ "\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: ...
[ "\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._...
[ "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 ...
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...
[ "\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 sel...
[ "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 ...
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 ...
[ "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 :cl...
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, ...
[ "\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 ...
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 ``...
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 on...
[ "\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 t...
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, n...
[ "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...
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(ou...
[ "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...
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) ...
[ "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 = s...
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 Va...
[ "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 mi...
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 ...
[ "\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 ...
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 = ForeachBatchFunctio...
[ "\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 ...
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: ...
[ "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...
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 t...
[ "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 re...
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_fun...
[ "\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 ne...
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 inst...
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 = ...
[ "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...
[ "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 com...
[ "\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_varname...
[ "\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 i...
[ " 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 cach...
[ "\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 ...
[ " 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. ...
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...
[ "\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...
[ "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.item...
[ "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.__getat...
[ "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()) ...
[ "\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 Ty...
[ "\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 TypeEr...
[ "\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) fo...
[ "\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)): ...
[ "\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: ...
[ "\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: s...
[ "\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 n...
[ "\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 p...
[ "\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 < ext...
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...
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._param...
[ "\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 re...
[ "\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: ...
[ "\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) ...
[ "\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....
[ "\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 ...
[ "\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...
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 ...
[ " 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 ...
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 wrappe...
[ "\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: rai...
[ "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-...
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.s...
[ "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 ...
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...
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().tryRecover...
[ "\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 b...
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 cont...
[ "\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 ...
[ "\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 dat...
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 receive...
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, UTF8Deseria...
[ "\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 ...
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 ...
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 F...
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[...
[ "\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 oneAt...
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),...
[ "\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: ...
[ "\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...
[ " 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 mo...
[ " Initialize the weights.\n " ]