sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def freeze_of_gait(self, x): """ This method assess freeze of gait following :cite:`g-BachlinPRMHGT10`. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return freeze_time: What times do freeze ...
This method assess freeze of gait following :cite:`g-BachlinPRMHGT10`. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return freeze_time: What times do freeze of gait events occur. [measured in time (h:m:s)] ...
entailment
def frequency_of_peaks(self, x, start_offset=100, end_offset=100): """ This method assess the frequency of the peaks on any given 1-dimensional time series. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series ...
This method assess the frequency of the peaks on any given 1-dimensional time series. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param start_offset: Signal to leave out (of calculations) from the begining of t...
entailment
def speed_of_gait(self, x, wavelet_type='db3', wavelet_level=6): """ This method assess the speed of gait following :cite:`g-MartinSB11`. It extracts the gait speed from the energies of the approximation coefficients of wavelet functions. Prefferably you should use the magn...
This method assess the speed of gait following :cite:`g-MartinSB11`. It extracts the gait speed from the energies of the approximation coefficients of wavelet functions. Prefferably you should use the magnitude of x, y and z (mag_acc_sum) here, as the time series. :param x: The tim...
entailment
def walk_regularity_symmetry(self, data_frame): """ This method extracts the step and stride regularity and also walk symmetry. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :return step_regularity: Reg...
This method extracts the step and stride regularity and also walk symmetry. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :return step_regularity: Regularity of steps on [x, y, z] coordinates, defined as the consistency of ...
entailment
def walk_direction_preheel(self, data_frame): """ Estimate local walk (not cardinal) direction with pre-heel strike phase. Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors" :param data_frame: The data f...
Estimate local walk (not cardinal) direction with pre-heel strike phase. Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors" :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame:...
entailment
def heel_strikes(self, x): """ Estimate heel strike times between sign changes in accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return strikes: Heel strike timings measured in seconds....
Estimate heel strike times between sign changes in accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return strikes: Heel strike timings measured in seconds. :rtype striles: numpy.ndar...
entailment
def gait_regularity_symmetry(self, x, average_step_duration='autodetect', average_stride_duration='autodetect', unbias=1, normalize=2): """ Compute step and stride regularity and symmetry from accelerometer data with the help of steps and strides. :param x: The time series to assess fr...
Compute step and stride regularity and symmetry from accelerometer data with the help of steps and strides. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param average_step_duration: Average duration of each step...
entailment
def gait(self, x): """ Extract gait features from estimated heel strikes and accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return number_of_steps: Estimated number of step...
Extract gait features from estimated heel strikes and accelerometer data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return number_of_steps: Estimated number of steps based on heel strikes [number of steps]. ...
entailment
def separate_into_sections(self, data_frame, labels_col='anno', labels_to_keep=[1,2], min_labels_in_sequence=100): """ Helper function to separate a time series into multiple sections based on a labeled column. :param data_frame: The data frame. It should have x, y, and z columns. ...
Helper function to separate a time series into multiple sections based on a labeled column. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :param labels_col: The column which has the labels we would like to separate ...
entailment
def bellman_segmentation(self, x, states): """ Divide a univariate time-series, data_frame, into states contiguous segments, using Bellman k-segmentation algorithm on the peak prominences of the data. :param x: The time series to assess freeze of gait on. This could be x, y, z ...
Divide a univariate time-series, data_frame, into states contiguous segments, using Bellman k-segmentation algorithm on the peak prominences of the data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :para...
entailment
def sklearn_segmentation(self, x, cluster_fn): """ Divide a univariate time-series, data_frame, into states contiguous segments, using sk-learn clustering algorithms on the peak prominences of the data. :param x: The time series to assess freeze of gait on. This could be x, y, ...
Divide a univariate time-series, data_frame, into states contiguous segments, using sk-learn clustering algorithms on the peak prominences of the data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :param ...
entailment
def add_manual_segmentation_to_data_frame(self, data_frame, segmentation_dictionary): """ Utility method to store manual segmentation of gait time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :...
Utility method to store manual segmentation of gait time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :param segmentation_dictionary: A dictionary of the form {'signal_type': [(from, to), (from, to)], ..., 'signal_...
entailment
def plot_segmentation_dictionary(self, x, segmentation_dictionary, figsize=(10, 5)): """ Utility method used to visualize how the segmentation dictionary interacts with the time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame:...
Utility method used to visualize how the segmentation dictionary interacts with the time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :param segmentation_dictionary: A dictionary of the form {'signal_type': [(from,...
entailment
def plot_segmentation_data_frame(self, segmented_data_frame, axis='mag_sum_acc', figsize=(10, 5)): """ Utility method used to visualize how the segmentation dictionary interacts with the time series. :param segmented_data_frame: The segmented data frame. It should have x, y, z and segm...
Utility method used to visualize how the segmentation dictionary interacts with the time series. :param segmented_data_frame: The segmented data frame. It should have x, y, z and segmentation columns. :type segmented_data_frame: pandas.DataFrame :param axis: The axis which we want t...
entailment
def error_wrapper(error, errorClass): """ We want to see all error messages from cloud services. Amazon's EC2 says that their errors are accompanied either by a 400-series or 500-series HTTP response code. As such, the first thing we want to do is check to see if the error is in that range. If it is...
We want to see all error messages from cloud services. Amazon's EC2 says that their errors are accompanied either by a 400-series or 500-series HTTP response code. As such, the first thing we want to do is check to see if the error is in that range. If it is, we then need to see if the error message is ...
entailment
def _get_joined_path(ctx): """ @type ctx: L{_URLContext} @param ctx: A URL context. @return: The path component, un-urlencoded, but joined by slashes. @rtype: L{bytes} """ return b'/' + b'/'.join(seg.encode('utf-8') for seg in ctx.path)
@type ctx: L{_URLContext} @param ctx: A URL context. @return: The path component, un-urlencoded, but joined by slashes. @rtype: L{bytes}
entailment
def get_page(self, url, *args, **kwds): """ Define our own get_page method so that we can easily override the factory when we need to. This was copied from the following: * twisted.web.client.getPage * twisted.web.client._makeGetterFactory """ contextFacto...
Define our own get_page method so that we can easily override the factory when we need to. This was copied from the following: * twisted.web.client.getPage * twisted.web.client._makeGetterFactory
entailment
def _headers(self, headers_dict): """ Convert dictionary of headers into twisted.web.client.Headers object. """ return Headers(dict((k,[v]) for (k,v) in headers_dict.items()))
Convert dictionary of headers into twisted.web.client.Headers object.
entailment
def _unpack_headers(self, headers): """ Unpack twisted.web.client.Headers object to dict. This is to provide backwards compatability. """ return dict((k,v[0]) for (k,v) in headers.getAllRawHeaders())
Unpack twisted.web.client.Headers object to dict. This is to provide backwards compatability.
entailment
def get_request_headers(self, *args, **kwds): """ A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications. """ ...
A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications.
entailment
def _handle_response(self, response): """ Handle the HTTP response by memoing the headers and then delivering bytes. """ self.client.status = response.code self.response_headers = response.headers # XXX This workaround (which needs to be improved at that) for poss...
Handle the HTTP response by memoing the headers and then delivering bytes.
entailment
def get_response_headers(self, *args, **kwargs): """ A convenience method for obtaining the headers that were sent from the S3 server. The AWS S3 API depends upon setting headers. This method is used by the head_object API call for getting a S3 object's metadata. """ ...
A convenience method for obtaining the headers that were sent from the S3 server. The AWS S3 API depends upon setting headers. This method is used by the head_object API call for getting a S3 object's metadata.
entailment
def create_jwt_token(secret, client_id): """ Create JWT token for GOV.UK Notify Tokens have standard header: { "typ": "JWT", "alg": "HS256" } Claims consist of: iss: identifier for the client iat: issued at in epoch seconds (UTC) :param secret: Application signing ...
Create JWT token for GOV.UK Notify Tokens have standard header: { "typ": "JWT", "alg": "HS256" } Claims consist of: iss: identifier for the client iat: issued at in epoch seconds (UTC) :param secret: Application signing secret :param client_id: Identifier for the clien...
entailment
def get_token_issuer(token): """ Issuer of a token is the identifier used to recover the secret Need to extract this from token to ensure we can proceed to the signature validation stage Does not check validity of the token :param token: signed JWT token :return issuer: iss field of the JWT toke...
Issuer of a token is the identifier used to recover the secret Need to extract this from token to ensure we can proceed to the signature validation stage Does not check validity of the token :param token: signed JWT token :return issuer: iss field of the JWT token :raises TokenIssuerError: if iss fi...
entailment
def decode_jwt_token(token, secret): """ Validates and decodes the JWT token Token checked for - signature of JWT token - token issued date is valid :param token: jwt token :param secret: client specific secret :return boolean: True if valid token, False otherwise :raises To...
Validates and decodes the JWT token Token checked for - signature of JWT token - token issued date is valid :param token: jwt token :param secret: client specific secret :return boolean: True if valid token, False otherwise :raises TokenIssuerError: if iss field not present :rai...
entailment
def parse(stream, with_text=False): # type: (Iterator[str], bool) -> Iterator[Union[Tuple[str, LexicalUnit], LexicalUnit]] """Generates lexical units from a character stream. Args: stream (Iterator[str]): A character stream containing lexical units, superblanks and other text. with_text (Optio...
Generates lexical units from a character stream. Args: stream (Iterator[str]): A character stream containing lexical units, superblanks and other text. with_text (Optional[bool]): A boolean defining whether to output preceding text with each lexical unit. Yields: :class:`LexicalUnit`: ...
entailment
def to_gnuplot_datafile(self, datafilepath): """Dumps the TimeSeries into a gnuplot compatible data file. :param string datafilepath: Path used to create the file. If that file already exists, it will be overwritten! :return: Returns :py:const:`True` if the data could be writt...
Dumps the TimeSeries into a gnuplot compatible data file. :param string datafilepath: Path used to create the file. If that file already exists, it will be overwritten! :return: Returns :py:const:`True` if the data could be written, :py:const:`False` otherwise. :rtype: bool...
entailment
def from_twodim_list(cls, datalist, tsformat=None): """Creates a new TimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefine...
Creates a new TimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second represents the value. All othe...
entailment
def initialize_from_sql_cursor(self, sqlcursor): """Initializes the TimeSeries's data from the given SQL cursor. You need to set the time stamp format using :py:meth:`TimeSeries.set_timeformat`. :param SQLCursor sqlcursor: Cursor that was holds the SQL result for any given "SELE...
Initializes the TimeSeries's data from the given SQL cursor. You need to set the time stamp format using :py:meth:`TimeSeries.set_timeformat`. :param SQLCursor sqlcursor: Cursor that was holds the SQL result for any given "SELECT timestamp, value, ... FROM ..." SQL query. On...
entailment
def convert_timestamp_to_epoch(cls, timestamp, tsformat): """Converts the given timestamp into a float representing UNIX-epochs. :param string timestamp: Timestamp in the defined format. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp ...
Converts the given timestamp into a float representing UNIX-epochs. :param string timestamp: Timestamp in the defined format. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp into UNIX epochs. For valid examples take a look into the...
entailment
def convert_epoch_to_timestamp(cls, timestamp, tsformat): """Converts the given float representing UNIX-epochs into an actual timestamp. :param float timestamp: Timestamp as UNIX-epochs. :param string tsformat: Format of the given timestamp. This is used to convert the timesta...
Converts the given float representing UNIX-epochs into an actual timestamp. :param float timestamp: Timestamp as UNIX-epochs. :param string tsformat: Format of the given timestamp. This is used to convert the timestamp from UNIX epochs. For valid examples take a look into the ...
entailment
def add_entry(self, timestamp, data): """Adds a new data entry to the TimeSeries. :param timestamp: Time stamp of the data. This has either to be a float representing the UNIX epochs or a string containing a timestamp in the given format. :param numeric data: Actua...
Adds a new data entry to the TimeSeries. :param timestamp: Time stamp of the data. This has either to be a float representing the UNIX epochs or a string containing a timestamp in the given format. :param numeric data: Actual data value.
entailment
def sort_timeseries(self, ascending=True): """Sorts the data points within the TimeSeries according to their occurrence inline. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. If this is set to descending once, the ordered parameter defined in...
Sorts the data points within the TimeSeries according to their occurrence inline. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. If this is set to descending once, the ordered parameter defined in :py:meth:`TimeSeries.__init__` will be se...
entailment
def sorted_timeseries(self, ascending=True): """Returns a sorted copy of the TimeSeries, preserving the original one. As an assumption this new TimeSeries is not ordered anymore if a new value is added. :param boolean ascending: Determines if the TimeSeries will be ordered ascending ...
Returns a sorted copy of the TimeSeries, preserving the original one. As an assumption this new TimeSeries is not ordered anymore if a new value is added. :param boolean ascending: Determines if the TimeSeries will be ordered ascending or descending. :return: Returns a new T...
entailment
def normalize(self, normalizationLevel="minute", fusionMethod="mean", interpolationMethod="linear"): """Normalizes the TimeSeries data points. If this function is called, the TimeSeries gets ordered ascending automatically. The new timestamps will represent the center of each time bucke...
Normalizes the TimeSeries data points. If this function is called, the TimeSeries gets ordered ascending automatically. The new timestamps will represent the center of each time bucket. Within a normalized TimeSeries, the temporal distance between two consecutive data points is constant. ...
entailment
def _check_normalization(self): """Checks, if the TimeSeries is normalized. :return: Returns :py:const:`True` if all data entries of the TimeSeries have an equal temporal distance, :py:const:`False` otherwise. """ lastDistance = None distance = None fo...
Checks, if the TimeSeries is normalized. :return: Returns :py:const:`True` if all data entries of the TimeSeries have an equal temporal distance, :py:const:`False` otherwise.
entailment
def apply(self, method): """Applies the given ForecastingAlgorithm or SmoothingMethod from the :py:mod:`pycast.methods` module to the TimeSeries. :param BaseMethod method: Method that should be used with the TimeSeries. For more information about the methods take a look into their c...
Applies the given ForecastingAlgorithm or SmoothingMethod from the :py:mod:`pycast.methods` module to the TimeSeries. :param BaseMethod method: Method that should be used with the TimeSeries. For more information about the methods take a look into their corresponding documentation. ...
entailment
def sample(self, percentage): """Samples with replacement from the TimeSeries. Returns the sample and the remaining timeseries. The original timeseries is not changed. :param float percentage: How many percent of the original timeseries should be in the sample :return: A tuple conta...
Samples with replacement from the TimeSeries. Returns the sample and the remaining timeseries. The original timeseries is not changed. :param float percentage: How many percent of the original timeseries should be in the sample :return: A tuple containing (sample, rest) as two TimeSeries. ...
entailment
def add_entry(self, timestamp, data): """Adds a new data entry to the TimeSeries. :param timestamp: Time stamp of the data. This has either to be a float representing the UNIX epochs or a string containing a timestamp in the given format. :param list data: A list c...
Adds a new data entry to the TimeSeries. :param timestamp: Time stamp of the data. This has either to be a float representing the UNIX epochs or a string containing a timestamp in the given format. :param list data: A list containing the actual dimension values. :...
entailment
def to_twodim_list(self): """Serializes the MultiDimensionalTimeSeries data into a two dimensional list of [timestamp, [values]] pairs. :return: Returns a two dimensional list containing [timestamp, [values]] pairs. :rtype: list """ if self._timestampFormat is None: ...
Serializes the MultiDimensionalTimeSeries data into a two dimensional list of [timestamp, [values]] pairs. :return: Returns a two dimensional list containing [timestamp, [values]] pairs. :rtype: list
entailment
def from_twodim_list(cls, datalist, tsformat=None, dimensions=1): """Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used...
Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list. :param list datalist: List containing multiple iterables with at least two values. The first item will always be used as timestamp in the predefined format, the second is a list, con...
entailment
def to_gnuplot_datafile(self, datafilepath): """Dumps the TimeSeries into a gnuplot compatible data file. :param string datafilepath: Path used to create the file. If that file already exists, it will be overwritten! :return: Returns :py:const:`True` if the data could be writt...
Dumps the TimeSeries into a gnuplot compatible data file. :param string datafilepath: Path used to create the file. If that file already exists, it will be overwritten! :return: Returns :py:const:`True` if the data could be written, :py:const:`False` otherwise. :rtype: boolean
entailment
def include(self, filename, is_file): """ Determines if a file should be included in a project for uploading. If file_exclude_regex is empty it will include everything. :param filename: str: filename to match it should not include directory :param is_file: bool: is this a file if...
Determines if a file should be included in a project for uploading. If file_exclude_regex is empty it will include everything. :param filename: str: filename to match it should not include directory :param is_file: bool: is this a file if not this will always return true :return: boolean...
entailment
def add_filename_pattern(self, dir_name, pattern): """ Adds a Unix shell-style wildcard pattern underneath the specified directory :param dir_name: str: directory that contains the pattern :param pattern: str: Unix shell-style wildcard pattern """ full_pattern = '{}{}{}'....
Adds a Unix shell-style wildcard pattern underneath the specified directory :param dir_name: str: directory that contains the pattern :param pattern: str: Unix shell-style wildcard pattern
entailment
def include(self, path): """ Returns False if any pattern matches the path :param path: str: filename path to test :return: boolean: True if we should include this path """ for regex_item in self.regex_list: if regex_item.match(path): return Fa...
Returns False if any pattern matches the path :param path: str: filename path to test :return: boolean: True if we should include this path
entailment
def load_directory(self, top_path, followlinks): """ Traverse top_path directory and save patterns in any .ddsignore files found. :param top_path: str: directory name we should traverse looking for ignore files :param followlinks: boolean: should we traverse symbolic links """ ...
Traverse top_path directory and save patterns in any .ddsignore files found. :param top_path: str: directory name we should traverse looking for ignore files :param followlinks: boolean: should we traverse symbolic links
entailment
def add_patterns(self, dir_name, pattern_lines): """ Add patterns the should apply below dir_name :param dir_name: str: directory that contained the patterns :param pattern_lines: [str]: array of patterns """ for pattern_line in pattern_lines: self.pattern_lis...
Add patterns the should apply below dir_name :param dir_name: str: directory that contained the patterns :param pattern_lines: [str]: array of patterns
entailment
def include(self, path, is_file): """ Returns False if any pattern matches the path :param path: str: filename path to test :return: boolean: True if we should include this path """ return self.pattern_list.include(path) and self.file_filter.include(os.path.basename(path)...
Returns False if any pattern matches the path :param path: str: filename path to test :return: boolean: True if we should include this path
entailment
def create_project(self, name, description): """ Create a project with the specified name and description :param name: str: unique name for this project :param description: str: long description of this project :return: str: name of the project """ self._cache_pro...
Create a project with the specified name and description :param name: str: unique name for this project :param description: str: long description of this project :return: str: name of the project
entailment
def delete_project(self, project_name): """ Delete a project with the specified name. Raises ItemNotFound if no such project exists :param project_name: str: name of the project to delete :return: """ project = self._get_project_for_name(project_name) project.dele...
Delete a project with the specified name. Raises ItemNotFound if no such project exists :param project_name: str: name of the project to delete :return:
entailment
def list_files(self, project_name): """ Return a list of file paths that make up project_name :param project_name: str: specifies the name of the project to list contents of :return: [str]: returns a list of remote paths for all files part of the specified project qq """ ...
Return a list of file paths that make up project_name :param project_name: str: specifies the name of the project to list contents of :return: [str]: returns a list of remote paths for all files part of the specified project qq
entailment
def download_file(self, project_name, remote_path, local_path=None): """ Download a file from a project When local_path is None the file will be downloaded to the base filename :param project_name: str: name of the project to download a file from :param remote_path: str: remote p...
Download a file from a project When local_path is None the file will be downloaded to the base filename :param project_name: str: name of the project to download a file from :param remote_path: str: remote path specifying which file to download :param local_path: str: optional argument t...
entailment
def upload_file(self, project_name, local_path, remote_path=None): """ Upload a file into project creating a new version if it already exists. Will also create project and parent folders if they do not exist. :param project_name: str: name of the project to upload a file to :para...
Upload a file into project creating a new version if it already exists. Will also create project and parent folders if they do not exist. :param project_name: str: name of the project to upload a file to :param local_path: str: path to download the file into :param remote_path: str: remo...
entailment
def delete_file(self, project_name, remote_path): """ Delete a file or folder from a project :param project_name: str: name of the project containing a file we will delete :param remote_path: str: remote path specifying file to delete """ project = self._get_or_create_pro...
Delete a file or folder from a project :param project_name: str: name of the project containing a file we will delete :param remote_path: str: remote path specifying file to delete
entailment
def _determineLength(self, fObj): """ Determine how many bytes can be read out of C{fObj} (assuming it is not modified from this point on). If the determination cannot be made, return C{UNKNOWN_LENGTH}. """ try: seek = fObj.seek tell = fObj.tell ...
Determine how many bytes can be read out of C{fObj} (assuming it is not modified from this point on). If the determination cannot be made, return C{UNKNOWN_LENGTH}.
entailment
def startProducing(self, consumer): """ Start a cooperative task which will read bytes from the input file and write them to C{consumer}. Return a L{Deferred} which fires after all bytes have been written. @param consumer: Any L{IConsumer} provider """ self._tas...
Start a cooperative task which will read bytes from the input file and write them to C{consumer}. Return a L{Deferred} which fires after all bytes have been written. @param consumer: Any L{IConsumer} provider
entailment
def _writeloop(self, consumer): """ Return an iterator which reads one chunk of bytes from the input file and writes them to the consumer for each time it is iterated. """ while True: bytes = self._inputFile.read(self._readSize) if not bytes: ...
Return an iterator which reads one chunk of bytes from the input file and writes them to the consumer for each time it is iterated.
entailment
def _count_differences(self): """ Count how many things we will be sending. :param local_project: LocalProject project we will send data from :return: LocalOnlyCounter contains counts for various items """ different_items = LocalOnlyCounter(self.config.upload_bytes_per_ch...
Count how many things we will be sending. :param local_project: LocalProject project we will send data from :return: LocalOnlyCounter contains counts for various items
entailment
def run(self): """ Upload different items within local_project to remote store showing a progress bar. """ progress_printer = ProgressPrinter(self.different_items.total_items(), msg_verb='sending') upload_settings = UploadSettings(self.config, self.remote_store.data_service, prog...
Upload different items within local_project to remote store showing a progress bar.
entailment
def dry_run_report(self): """ Returns text displaying the items that need to be uploaded or a message saying there are no files/folders to upload. :return: str: report text """ project_uploader = ProjectUploadDryRun() project_uploader.run(self.local_project) ...
Returns text displaying the items that need to be uploaded or a message saying there are no files/folders to upload. :return: str: report text
entailment
def get_upload_report(self): """ Generate and print a report onto stdout. """ project = self.remote_store.fetch_remote_project(self.project_name_or_id, must_exist=True, inclu...
Generate and print a report onto stdout.
entailment
def get_url_msg(self): """ Print url to view the project via dds portal. """ msg = 'URL to view project' project_id = self.local_project.remote_id url = '{}: https://{}/#/project/{}'.format(msg, self.config.get_portal_url_base(), project_id) return url
Print url to view the project via dds portal.
entailment
def visit_file(self, item, parent): """ Increments counter if item needs to be sent. :param item: LocalFile :param parent: LocalFolder/LocalProject """ if item.need_to_send: self.files += 1 self.chunks += item.count_chunks(self.bytes_per_chunk)
Increments counter if item needs to be sent. :param item: LocalFile :param parent: LocalFolder/LocalProject
entailment
def result_str(self): """ Return a string representing the totals contained herein. :return: str counts/types string """ return '{}, {}, {}'.format(LocalOnlyCounter.plural_fmt('project', self.projects), LocalOnlyCounter.plural_fmt('folder', self...
Return a string representing the totals contained herein. :return: str counts/types string
entailment
def plural_fmt(name, cnt): """ pluralize name if necessary and combine with cnt :param name: str name of the item type :param cnt: int number items of this type :return: str name and cnt joined """ if cnt == 1: return '{} {}'.format(cnt, name) ...
pluralize name if necessary and combine with cnt :param name: str name of the item type :param cnt: int number items of this type :return: str name and cnt joined
entailment
def visit_folder(self, item, parent): """ Add folder to the report if it was sent. :param item: LocalFolder folder to possibly add :param parent: LocalFolder/LocalContent not used here """ if item.sent_to_remote: self._add_report_item(item.path, item.remote_id...
Add folder to the report if it was sent. :param item: LocalFolder folder to possibly add :param parent: LocalFolder/LocalContent not used here
entailment
def visit_file(self, item, parent): """ Add file to the report if it was sent. :param item: LocalFile file to possibly add. :param parent: LocalFolder/LocalContent not used here """ if item.sent_to_remote: self._add_report_item(item.path, item.remote_id, item....
Add file to the report if it was sent. :param item: LocalFile file to possibly add. :param parent: LocalFolder/LocalContent not used here
entailment
def str_with_sizes(self, max_name, max_remote_id, max_size): """ Create string for report based on internal properties using sizes to line up columns. :param max_name: int width of the name column :param max_remote_id: int width of the remote_id column :return: str info from this...
Create string for report based on internal properties using sizes to line up columns. :param max_name: int width of the name column :param max_remote_id: int width of the remote_id column :return: str info from this report item
entailment
def upload_async(data_service_auth_data, config, upload_id, filename, index, num_chunks_to_send, progress_queue): """ Method run in another process called from ParallelChunkProcessor.make_and_start_process. :param data_service_auth_data: tuple of auth data for rebuilding DataServiceAuth ...
Method run in another process called from ParallelChunkProcessor.make_and_start_process. :param data_service_auth_data: tuple of auth data for rebuilding DataServiceAuth :param config: dds.Config configuration settings to use during upload :param upload_id: uuid unique id of the 'upload' we are uploading ch...
entailment
def upload(self, project_id, parent_kind, parent_id): """ Upload file contents to project within a specified parent. :param project_id: str project uuid :param parent_kind: str type of parent ('dds-project' or 'dds-folder') :param parent_id: str uuid of parent :return: st...
Upload file contents to project within a specified parent. :param project_id: str project uuid :param parent_kind: str type of parent ('dds-project' or 'dds-folder') :param parent_id: str uuid of parent :return: str uuid of the newly uploaded file
entailment
def _create_upload(self, project_id, path_data, hash_data, remote_filename=None, storage_provider_id=None, chunked=True): """ Create upload for uploading multiple chunks or the non-chunked variety (includes upload url). :param project_id: str: uuid of the project :...
Create upload for uploading multiple chunks or the non-chunked variety (includes upload url). :param project_id: str: uuid of the project :param path_data: PathData: holds file system data about the file we are uploading :param hash_data: HashData: contains hash alg and value for the file we are...
entailment
def create_upload(self, project_id, path_data, hash_data, remote_filename=None, storage_provider_id=None): """ Create a chunked upload id to pass to create_file_chunk_url to create upload urls. :param project_id: str: uuid of the project :param path_data: PathData: holds file system data...
Create a chunked upload id to pass to create_file_chunk_url to create upload urls. :param project_id: str: uuid of the project :param path_data: PathData: holds file system data about the file we are uploading :param hash_data: HashData: contains hash alg and value for the file we are uploading ...
entailment
def create_upload_and_chunk_url(self, project_id, path_data, hash_data, remote_filename=None, storage_provider_id=None): """ Create an non-chunked upload that returns upload id and upload url. This type of upload doesn't allow additional upload urls. For singl...
Create an non-chunked upload that returns upload id and upload url. This type of upload doesn't allow additional upload urls. For single chunk files this method is more efficient than create_upload/create_file_chunk_url. :param project_id: str: uuid of the project :param path_data: PathD...
entailment
def create_file_chunk_url(self, upload_id, chunk_num, chunk): """ Create a url for uploading a particular chunk to the datastore. :param upload_id: str: uuid of the upload this chunk is for :param chunk_num: int: where in the file does this chunk go (0-based index) :param chunk: ...
Create a url for uploading a particular chunk to the datastore. :param upload_id: str: uuid of the upload this chunk is for :param chunk_num: int: where in the file does this chunk go (0-based index) :param chunk: bytes: data we are going to upload :return:
entailment
def send_file_external(self, url_json, chunk): """ Send chunk to external store specified in url_json. Raises ValueError on upload failure. :param data_service: data service to use for sending chunk :param url_json: dict contains where/how to upload chunk :param chunk: da...
Send chunk to external store specified in url_json. Raises ValueError on upload failure. :param data_service: data service to use for sending chunk :param url_json: dict contains where/how to upload chunk :param chunk: data to be uploaded
entailment
def _send_file_external_with_retry(self, http_verb, host, url, http_headers, chunk): """ Send chunk to host, url using http_verb. If http_verb is PUT and a connection error occurs retry a few times. Pauses between retries. Raises if unsuccessful. """ count = 0 retry_times...
Send chunk to host, url using http_verb. If http_verb is PUT and a connection error occurs retry a few times. Pauses between retries. Raises if unsuccessful.
entailment
def _show_retry_warning(host): """ Displays a message on stderr that we lost connection to a host and will retry. :param host: str: name of the host we are trying to communicate with """ sys.stderr.write("\nConnection to {} failed. Retrying.\n".format(host)) sys.stderr.fl...
Displays a message on stderr that we lost connection to a host and will retry. :param host: str: name of the host we are trying to communicate with
entailment
def finish_upload(self, upload_id, hash_data, parent_data, remote_file_id): """ Complete the upload and create or update the file. :param upload_id: str: uuid of the upload we are completing :param hash_data: HashData: hash info about the file :param parent_data: ParentData: info...
Complete the upload and create or update the file. :param upload_id: str: uuid of the upload we are completing :param hash_data: HashData: hash info about the file :param parent_data: ParentData: info about the parent of this file :param remote_file_id: str: uuid of this file if it alrea...
entailment
def run(self): """ Sends contents of a local file to a remote data service. """ processes = [] progress_queue = ProgressQueue(Queue()) num_chunks = ParallelChunkProcessor.determine_num_chunks(self.config.upload_bytes_per_chunk, ...
Sends contents of a local file to a remote data service.
entailment
def determine_num_chunks(chunk_size, file_size): """ Figure out how many pieces we are sending the file in. NOTE: duke-data-service requires an empty chunk to be uploaded for empty files. """ if file_size == 0: return 1 return int(math.ceil(float(file_size) / ...
Figure out how many pieces we are sending the file in. NOTE: duke-data-service requires an empty chunk to be uploaded for empty files.
entailment
def make_work_parcels(upload_workers, num_chunks): """ Make groups so we can split up num_chunks into similar sizes. Rounds up trying to keep work evenly split so sometimes it will not use all workers. For very small numbers it can result in (upload_workers-1) total workers. For ...
Make groups so we can split up num_chunks into similar sizes. Rounds up trying to keep work evenly split so sometimes it will not use all workers. For very small numbers it can result in (upload_workers-1) total workers. For example if there are two few items to distribute. :param upload...
entailment
def divide_work(list_of_indexes, batch_size): """ Given a sequential list of indexes split them into num_parts. :param list_of_indexes: [int] list of indexes to be divided up :param batch_size: number of items to put in batch(not exact obviously) :return: [(int,int)] list of (ind...
Given a sequential list of indexes split them into num_parts. :param list_of_indexes: [int] list of indexes to be divided up :param batch_size: number of items to put in batch(not exact obviously) :return: [(int,int)] list of (index, num_items) to be processed
entailment
def make_and_start_process(self, index, num_items, progress_queue): """ Create and start a process to upload num_items chunks from our file starting at index. :param index: int offset into file(must be multiplied by upload_bytes_per_chunk to get actual location) :param num_items: int num...
Create and start a process to upload num_items chunks from our file starting at index. :param index: int offset into file(must be multiplied by upload_bytes_per_chunk to get actual location) :param num_items: int number chunks to send :param progress_queue: ProgressQueue queue to send notificati...
entailment
def send(self): """ For each chunk we need to send, create upload url and send bytes. Raises exception on error. """ sent_chunks = 0 chunk_num = self.index with open(self.filename, 'rb') as infile: infile.seek(self.index * self.chunk_size) while se...
For each chunk we need to send, create upload url and send bytes. Raises exception on error.
entailment
def _send_chunk(self, chunk, chunk_num): """ Send a single chunk to the remote service. :param chunk: bytes data we are uploading :param chunk_num: int number associated with this chunk """ url_info = self.upload_operations.create_file_chunk_url(self.upload_id, chunk_num,...
Send a single chunk to the remote service. :param chunk: bytes data we are uploading :param chunk_num: int number associated with this chunk
entailment
def _in_valid_interval(self, parameter, value): """Returns if the parameter is within its valid interval. :param string parameter: Name of the parameter that has to be checked. :param numeric value: Value of the parameter. :return: Returns :py:const:`True` it the value for t...
Returns if the parameter is within its valid interval. :param string parameter: Name of the parameter that has to be checked. :param numeric value: Value of the parameter. :return: Returns :py:const:`True` it the value for the given parameter is valid, :py:const:`False` ...
entailment
def _get_value_error_message_for_invalid_prarameter(self, parameter, value): """Returns the ValueError message for the given parameter. :param string parameter: Name of the parameter the message has to be created for. :param numeric value: Value outside the parameters interval. :...
Returns the ValueError message for the given parameter. :param string parameter: Name of the parameter the message has to be created for. :param numeric value: Value outside the parameters interval. :return: Returns a string containing hte message. :rtype: string
entailment
def set_parameter(self, name, value): """Sets a parameter for the BaseMethod. :param string name: Name of the parameter that has to be checked. :param numeric value: Value of the parameter. """ if not self._in_valid_interval(name, value): raise ValueError(sel...
Sets a parameter for the BaseMethod. :param string name: Name of the parameter that has to be checked. :param numeric value: Value of the parameter.
entailment
def can_be_executed(self): """Returns if the method can already be executed. :return: Returns :py:const:`True` if all required parameters where already set, False otherwise. :rtype: boolean """ missingParams = filter(lambda rp: rp not in self._parameters, self._requiredParame...
Returns if the method can already be executed. :return: Returns :py:const:`True` if all required parameters where already set, False otherwise. :rtype: boolean
entailment
def set_parameter(self, name, value): """Sets a parameter for the BaseForecastingMethod. :param string name: Name of the parameter. :param numeric value: Value of the parameter. """ # set the furecast until variable to None if necessary if name == "valuesToForecast...
Sets a parameter for the BaseForecastingMethod. :param string name: Name of the parameter. :param numeric value: Value of the parameter.
entailment
def forecast_until(self, timestamp, tsformat=None): """Sets the forecasting goal (timestamp wise). This function enables the automatic determination of valuesToForecast. :param timestamp: timestamp containing the end date of the forecast. :param string tsformat: Format of the tim...
Sets the forecasting goal (timestamp wise). This function enables the automatic determination of valuesToForecast. :param timestamp: timestamp containing the end date of the forecast. :param string tsformat: Format of the timestamp. This is used to convert the timestamp from ...
entailment
def _calculate_values_to_forecast(self, timeSeries): """Calculates the number of values, that need to be forecasted to match the goal set in forecast_until. This sets the parameter "valuesToForecast" and should be called at the beginning of the :py:meth:`BaseMethod.execute` implementation. :pa...
Calculates the number of values, that need to be forecasted to match the goal set in forecast_until. This sets the parameter "valuesToForecast" and should be called at the beginning of the :py:meth:`BaseMethod.execute` implementation. :param TimeSeries timeSeries: Should be a sorted and normalized ...
entailment
def execute(self, timeSeries): """Creates a new TimeSeries containing the SMA values for the predefined windowsize. :param TimeSeries timeSeries: The TimeSeries used to calculate the simple moving average values. :return: TimeSeries object containing the smooth moving average. :r...
Creates a new TimeSeries containing the SMA values for the predefined windowsize. :param TimeSeries timeSeries: The TimeSeries used to calculate the simple moving average values. :return: TimeSeries object containing the smooth moving average. :rtype: TimeSeries :raise: Ra...
entailment
def add(self, child, min_occurs=1): """Add a child node. @param child: The schema for the child node. @param min_occurs: The minimum number of times the child node must occur, if C{None} is given the default is 1. """ if not min_occurs in (0, 1): raise Ru...
Add a child node. @param child: The schema for the child node. @param min_occurs: The minimum number of times the child node must occur, if C{None} is given the default is 1.
entailment
def _create_child(self, tag): """Create a new child element with the given tag.""" return etree.SubElement(self._root, self._get_namespace_tag(tag))
Create a new child element with the given tag.
entailment
def _find_child(self, tag): """Find the child C{etree.Element} with the matching C{tag}. @raises L{WSDLParseError}: If more than one such elements are found. """ tag = self._get_namespace_tag(tag) children = self._root.findall(tag) if len(children) > 1: raise...
Find the child C{etree.Element} with the matching C{tag}. @raises L{WSDLParseError}: If more than one such elements are found.
entailment
def _check_value(self, tag, value): """Ensure that the element matching C{tag} can have the given C{value}. @param tag: The tag to consider. @param value: The value to check @return: The unchanged L{value}, if valid. @raises L{WSDLParseError}: If the value is invalid. ""...
Ensure that the element matching C{tag} can have the given C{value}. @param tag: The tag to consider. @param value: The value to check @return: The unchanged L{value}, if valid. @raises L{WSDLParseError}: If the value is invalid.
entailment
def _get_tag(self, name): """Get the L{NodeItem} attribute name for the given C{tag}.""" if name.endswith("_"): if name[:-1] in self._schema.reserved: return name[:-1] return name
Get the L{NodeItem} attribute name for the given C{tag}.
entailment
def _get_namespace_tag(self, tag): """Return the given C{tag} with the namespace prefix added, if any.""" if self._namespace is not None: tag = "{%s}%s" % (self._namespace, tag) return tag
Return the given C{tag} with the namespace prefix added, if any.
entailment
def _get_schema(self, tag): """Return the child schema for the given C{tag}. @raises L{WSDLParseError}: If the tag doesn't belong to the schema. """ schema = self._schema.children.get(tag) if not schema: raise WSDLParseError("Unknown tag '%s'" % tag) return s...
Return the child schema for the given C{tag}. @raises L{WSDLParseError}: If the tag doesn't belong to the schema.
entailment