sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def separate_walks_turns(data, window=[1, 1, 1]):
""" Will separate peaks into the clusters by following the trend in the clusters array.
This is usedful because scipy's k-mean clustering will give us a continous clusters
array.
:param clusters array: A continous array representing ... | Will separate peaks into the clusters by following the trend in the clusters array.
This is usedful because scipy's k-mean clustering will give us a continous clusters
array.
:param clusters array: A continous array representing different classes.
:param peaks array: The peaks t... | entailment |
def centroid_sort(centroids):
"""
Sort centroids. This is required so that the same cluster centroid is always the 0th one. It should also be the \
most negative. Order defined by the Euclidean distance between the centroid and an arbitrary "small" point \
[-100, -100] (in each dimension) to... | Sort centroids. This is required so that the same cluster centroid is always the 0th one. It should also be the \
most negative. Order defined by the Euclidean distance between the centroid and an arbitrary "small" point \
[-100, -100] (in each dimension) to account for possible negatives. Cluster 0 is ... | entailment |
def non_zero_index(arr):
"""
Raises:
ValueError: If no-non-zero rows can be found.
0. Empty array raises.
>>> arr = array([])
>>> non_zero_index(arr)
1. Array with zero values raises.
>>> arr = array([
... [0, 0],
... | Raises:
ValueError: If no-non-zero rows can be found.
0. Empty array raises.
>>> arr = array([])
>>> non_zero_index(arr)
1. Array with zero values raises.
>>> arr = array([
... [0, 0],
... [0, 0],
... [0, 0... | entailment |
def non_zero_row(arr):
"""
0. Empty row returns False.
>>> arr = array([])
>>> non_zero_row(arr)
False
1. Row with a zero returns False.
>>> arr = array([1, 4, 3, 0, 5, -1, -2])
>>> non_zero_row(arr)
False
2. Row... | 0. Empty row returns False.
>>> arr = array([])
>>> non_zero_row(arr)
False
1. Row with a zero returns False.
>>> arr = array([1, 4, 3, 0, 5, -1, -2])
>>> non_zero_row(arr)
False
2. Row with no zeros returns True.
... | entailment |
def window_features(idx, window_size=100, overlap=10):
""" Generate indexes for a sliding window with overlap
:param array idx: The indexes that need to be windowed.
:param int window_size: The size of the window.
:param int overlap: How much should each window overlap.
... | Generate indexes for a sliding window with overlap
:param array idx: The indexes that need to be windowed.
:param int window_size: The size of the window.
:param int overlap: How much should each window overlap.
:return array view: The indexes for the windows with overlap. | entailment |
def get_pypi_version():
"""
Returns the version info from pypi for this app.
"""
try:
response = requests.get(PYPI_URL, timeout=HALF_SECOND_TIMEOUT)
response.raise_for_status()
data = response.json()
version_str = data["info"]["version"]
return _parse_version_str(... | Returns the version info from pypi for this app. | entailment |
def get_project_by_id(self, project_id):
"""
Get details about project with the specified uuid
:param project_id: str: uuid of the project to fetch
:return: Project
"""
return self._create_item_response(
self.data_service.get_project_by_id(project_id),
... | Get details about project with the specified uuid
:param project_id: str: uuid of the project to fetch
:return: Project | entailment |
def create_project(self, name, description):
"""
Create a new project with the specified name and description
:param name: str: name of the project to create
:param description: str: description of the project to create
:return: Project
"""
return self._create_ite... | Create a new project with the specified name and description
:param name: str: name of the project to create
:param description: str: description of the project to create
:return: Project | entailment |
def create_folder(self, folder_name, parent_kind_str, parent_uuid):
"""
Create a folder under a particular parent
:param folder_name: str: name of the folder to create
:param parent_kind_str: str: kind of the parent of this folder
:param parent_uuid: str: uuid of the parent of th... | Create a folder under a particular parent
:param folder_name: str: name of the folder to create
:param parent_kind_str: str: kind of the parent of this folder
:param parent_uuid: str: uuid of the parent of this folder (project or another folder)
:return: Folder: folder metadata | entailment |
def get_project_children(self, project_id, name_contains=None):
"""
Get direct files and folders of a project.
:param project_id: str: uuid of the project to list contents
:param name_contains: str: filter children based on a pattern
:return: [File|Folder]: list of Files/Folders ... | Get direct files and folders of a project.
:param project_id: str: uuid of the project to list contents
:param name_contains: str: filter children based on a pattern
:return: [File|Folder]: list of Files/Folders contained by the project | entailment |
def get_folder_children(self, folder_id, name_contains=None):
"""
Get direct files and folders of a folder.
:param folder_id: str: uuid of the folder
:param name_contains: str: filter children based on a pattern
:return: File|Folder
"""
return self._create_array_r... | Get direct files and folders of a folder.
:param folder_id: str: uuid of the folder
:param name_contains: str: filter children based on a pattern
:return: File|Folder | entailment |
def get_file_download(self, file_id):
"""
Get a file download object that contains temporary url settings needed to download the contents of a file.
:param file_id: str: uuid of the file
:return: FileDownload
"""
return self._create_item_response(
self.data_se... | Get a file download object that contains temporary url settings needed to download the contents of a file.
:param file_id: str: uuid of the file
:return: FileDownload | entailment |
def upload_file(self, local_path, project_id, parent_data, existing_file_id=None, remote_filename=None):
"""
Upload a file under a specific location in DDSConnection possibly replacing an existing file.
:param local_path: str: path to a local file to upload
:param project_id: str: uuid o... | Upload a file under a specific location in DDSConnection possibly replacing an existing file.
:param local_path: str: path to a local file to upload
:param project_id: str: uuid of the project to add this file to
:param parent_data: ParentData: info about the parent of this file
:param e... | entailment |
def _folder_or_file_constructor(dds_connection, data_dict):
"""
Create a File or Folder based on the kind value in data_dict
:param dds_connection: DDSConnection
:param data_dict: dict: payload received from DDSConnection API
:return: File|Folder
"""
kind = data_d... | Create a File or Folder based on the kind value in data_dict
:param dds_connection: DDSConnection
:param data_dict: dict: payload received from DDSConnection API
:return: File|Folder | entailment |
def get_folder_by_id(self, folder_id):
"""
Get folder details for a folder id.
:param folder_id: str: uuid of the folder
:return: Folder
"""
return self._create_item_response(
self.data_service.get_folder(folder_id),
Folder
) | Get folder details for a folder id.
:param folder_id: str: uuid of the folder
:return: Folder | entailment |
def get_file_by_id(self, file_id):
"""
Get folder details for a file id.
:param file_id: str: uuid of the file
:return: File
"""
return self._create_item_response(
self.data_service.get_file(file_id),
File
) | Get folder details for a file id.
:param file_id: str: uuid of the file
:return: File | entailment |
def save_to_path(self, file_path, chunk_size=DOWNLOAD_FILE_CHUNK_SIZE):
"""
Save the contents of the remote file to a local path.
:param file_path: str: file path
:param chunk_size: chunk size used to write local file
"""
response = self._get_download_response()
w... | Save the contents of the remote file to a local path.
:param file_path: str: file path
:param chunk_size: chunk size used to write local file | entailment |
def get_child(self):
"""
Find file or folder at the remote_path
:return: File|Folder
"""
path_parts = self.remote_path.split(os.sep)
return self._get_child_recurse(path_parts, self.node) | Find file or folder at the remote_path
:return: File|Folder | entailment |
def execute_task_async(task_func, task_id, context):
"""
Global function run for Task. multiprocessing requires a top level function.
:param task_func: function: function to run (must be pickle-able)
:param task_id: int: unique id of this task
:param context: object: single argument to task_func (mu... | Global function run for Task. multiprocessing requires a top level function.
:param task_func: function: function to run (must be pickle-able)
:param task_id: int: unique id of this task
:param context: object: single argument to task_func (must be pickle-able)
:return: (task_id, object): return passed ... | entailment |
def add(self, task):
"""
Add this task to the lookup based on it's wait_for_task_id property.
:param task: Task: task to add to the list
"""
wait_id = task.wait_for_task_id
task_list = self.wait_id_to_task.get(wait_id, [])
task_list.append(task)
self.wait_... | Add this task to the lookup based on it's wait_for_task_id property.
:param task: Task: task to add to the list | entailment |
def add(self, parent_task_id, command):
"""
Create a task for the command that will wait for parent_task_id before starting.
:param parent_task_id: int: id of task to wait for or None if it can start immediately
:param command: TaskCommand: contains data function to run
:return: ... | Create a task for the command that will wait for parent_task_id before starting.
:param parent_task_id: int: id of task to wait for or None if it can start immediately
:param command: TaskCommand: contains data function to run
:return: int: task id we created for this command | entailment |
def run(self):
"""
Runs all tasks in this runner on the executor.
Blocks until all tasks have been completed.
:return:
"""
for task in self.get_next_tasks(None):
self.executor.add_task(task, None)
while not self.executor.is_done():
done_tas... | Runs all tasks in this runner on the executor.
Blocks until all tasks have been completed.
:return: | entailment |
def _add_sub_tasks_to_executor(self, parent_task, parent_task_result):
"""
Add all subtasks for parent_task to the executor.
:param parent_task: Task: task that has just finished
:param parent_task_result: object: result of task that is finished
"""
for sub_task in self.w... | Add all subtasks for parent_task to the executor.
:param parent_task: Task: task that has just finished
:param parent_task_result: object: result of task that is finished | entailment |
def add_task(self, task, parent_task_result):
"""
Add a task to run with the specified result from this tasks parent(can be None)
:param task: Task: task that should be run
:param parent_task_result: object: value to be passed to task for setup
"""
self.tasks.append((task... | Add a task to run with the specified result from this tasks parent(can be None)
:param task: Task: task that should be run
:param parent_task_result: object: value to be passed to task for setup | entailment |
def wait_for_tasks(self):
"""
Wait for one or more tasks to finish or return empty list if we are done.
Starts new tasks if we have less than task_at_once currently running.
:return: [(Task,object)]: list of (task,result) for finished tasks
"""
finished_tasks_and_results ... | Wait for one or more tasks to finish or return empty list if we are done.
Starts new tasks if we have less than task_at_once currently running.
:return: [(Task,object)]: list of (task,result) for finished tasks | entailment |
def start_tasks(self):
"""
Start however many tasks we can based on our limits and what we have left to finish.
"""
while self.tasks_at_once > len(self.pending_results) and self._has_more_tasks():
task, parent_result = self.tasks.popleft()
self.execute_task(task, ... | Start however many tasks we can based on our limits and what we have left to finish. | entailment |
def execute_task(self, task, parent_result):
"""
Run a single task in another process saving the result to our list of pending results.
:param task: Task: function and data we can run in another process
:param parent_result: object: result from our parent task
"""
task.be... | Run a single task in another process saving the result to our list of pending results.
:param task: Task: function and data we can run in another process
:param parent_result: object: result from our parent task | entailment |
def process_single_message_from_queue(self):
"""
Tries to read a single message from the queue and let the associated task process it.
:return: bool: True if we processed a message, otherwise False
"""
try:
message = self.message_queue.get_nowait()
task_id... | Tries to read a single message from the queue and let the associated task process it.
:return: bool: True if we processed a message, otherwise False | entailment |
def get_finished_results(self):
"""
Go through pending results and retrieve the results if they are done.
Then start child tasks for the task that finished.
"""
task_and_results = []
for pending_result in self.pending_results:
if pending_result.ready():
... | Go through pending results and retrieve the results if they are done.
Then start child tasks for the task that finished. | entailment |
def to_xml(body_element):
"""
Serialize a L{twisted.web.template.Tag} to a UTF-8 encoded XML document
with an XML doctype header.
"""
doctype = b"""<?xml version="1.0" encoding="UTF-8"?>\n"""
if body_element is None:
return succeed(b"")
d = flattenString(None, body_element)
d.add... | Serialize a L{twisted.web.template.Tag} to a UTF-8 encoded XML document
with an XML doctype header. | entailment |
def get_route53_client(agent, region, cooperator=None):
"""
Get a non-registration Route53 client.
"""
if cooperator is None:
cooperator = task
return region.get_client(
_Route53Client,
agent=agent,
creds=region.creds,
region=REGION_US_EAST_1,
endpoint... | Get a non-registration Route53 client. | entailment |
def _route53_op(body=None, **kw):
"""
Construct an L{_Operation} representing a I{Route53} service API call.
"""
op = _Operation(service=b"route53", **kw)
if body is None:
return succeed(op)
d = to_xml(body)
d.addCallback(lambda body: attr.assoc(op, body=body))
return d | Construct an L{_Operation} representing a I{Route53} service API call. | entailment |
def hostedzone_from_element(zone):
"""
Construct a L{HostedZone} instance from a I{HostedZone} XML element.
"""
return HostedZone(
name=maybe_bytes_to_unicode(zone.find("Name").text).encode("ascii").decode("idna"),
identifier=maybe_bytes_to_unicode(zone.find("Id").text).replace(u"/hosted... | Construct a L{HostedZone} instance from a I{HostedZone} XML element. | entailment |
def to_element(change):
"""
@param change: An L{txaws.route53.interface.IRRSetChange} provider.
@return: The L{twisted.web.template} element which describes this
change.
"""
return tags.Change(
tags.Action(
change.action,
),
tags.ResourceRecordSet(
... | @param change: An L{txaws.route53.interface.IRRSetChange} provider.
@return: The L{twisted.web.template} element which describes this
change. | entailment |
def add(self, method_class, action, version=None):
"""Add a method class to the regitry.
@param method_class: The method class to add
@param action: The action that the method class can handle
@param version: The version that the method class can handle
"""
by_version = ... | Add a method class to the regitry.
@param method_class: The method class to add
@param action: The action that the method class can handle
@param version: The version that the method class can handle | entailment |
def check(self, action, version=None):
"""Check if the given action is supported in the given version.
@raises APIError: If there's no method class registered for handling
the given action or version.
"""
if action not in self._by_action:
raise APIError(400, "Inv... | Check if the given action is supported in the given version.
@raises APIError: If there's no method class registered for handling
the given action or version. | entailment |
def get(self, action, version=None):
"""Get the method class handing the given action and version."""
by_version = self._by_action[action]
if version in by_version:
return by_version[version]
else:
return by_version[None] | Get the method class handing the given action and version. | entailment |
def scan(self, module, onerror=None, ignore=None):
"""Scan the given module object for L{Method}s and register them."""
from venusian import Scanner
scanner = Scanner(registry=self)
kwargs = {"onerror": onerror, "categories": ["method"]}
if ignore is not None:
# Only ... | Scan the given module object for L{Method}s and register them. | entailment |
def calculate_parameters(self, independentTs, dependentTs):
"""Calculate and return the parameters for the regression line
Return the parameter for the line describing the relationship
between the input variables.
:param Timeseries independentTs: The Timeseries used for the
... | Calculate and return the parameters for the regression line
Return the parameter for the line describing the relationship
between the input variables.
:param Timeseries independentTs: The Timeseries used for the
independent variable (x-axis). The Timeseries must have
at... | entailment |
def calculate_parameters_with_confidence(self, independentTs, dependentTs, confidenceLevel, samplePercentage=.1):
"""Same functionality as calculate_parameters, just that additionally
the confidence interval for a given confidenceLevel is calculated.
This is done based on a sample of the depende... | Same functionality as calculate_parameters, just that additionally
the confidence interval for a given confidenceLevel is calculated.
This is done based on a sample of the dependentTs training data that is validated
against the prediction. The signed error of the predictions and the sample is th... | entailment |
def predict(self, timeseriesX, n, m):
"""
Calculates the dependent timeseries Y for the given parameters
and independent timeseries. (y=m*x + n)
:param TimeSeries timeseriesX: the independent Timeseries.
:param float n: The interception with the x access
that has be... | Calculates the dependent timeseries Y for the given parameters
and independent timeseries. (y=m*x + n)
:param TimeSeries timeseriesX: the independent Timeseries.
:param float n: The interception with the x access
that has been calculated during regression
:param float m: T... | entailment |
def match_time_series(self, timeseries1, timeseries2):
"""Return two lists of the two input time series with matching dates
:param TimeSeries timeseries1: The first timeseries
:param TimeSeries timeseries2: The second timeseries
:return: Two two dimensional lists containing the match... | Return two lists of the two input time series with matching dates
:param TimeSeries timeseries1: The first timeseries
:param TimeSeries timeseries2: The second timeseries
:return: Two two dimensional lists containing the matched values,
:rtype: two List | entailment |
def lstsq(cls, a, b):
"""Return the least-squares solution to a linear matrix equation.
:param Matrix a: Design matrix with the values of the independent variables.
:param Matrix b: Matrix with the "dependent variable" values.
b can only have one column.
... | Return the least-squares solution to a linear matrix equation.
:param Matrix a: Design matrix with the values of the independent variables.
:param Matrix b: Matrix with the "dependent variable" values.
b can only have one column.
:raise: Raises an ... | entailment |
def _calculate(self, startingPercentage, endPercentage, startDate, endDate):
"""This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. Th... | This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. This has to be a value in [0.0, 100.0].
It represents the value, where the err... | entailment |
def local_error(self, originalValue, calculatedValue):
"""Calculates the error between the two given values.
:param list originalValue: List containing the values of the original data.
:param list calculatedValue: List containing the values of the calculated TimeSeries that
co... | Calculates the error between the two given values.
:param list originalValue: List containing the values of the original data.
:param list calculatedValue: List containing the values of the calculated TimeSeries that
corresponds to originalValue.
:return: Returns the error... | entailment |
def _get_historic_means(self, timeSeries):
"""Calculates the mean value for the history of the MeanAbsoluteScaledError.
:param TimeSeries timeSeries: Original TimeSeries used to calculate the mean historic values.
:return: Returns a list containing the historic means.
:rtype: lis... | Calculates the mean value for the history of the MeanAbsoluteScaledError.
:param TimeSeries timeSeries: Original TimeSeries used to calculate the mean historic values.
:return: Returns a list containing the historic means.
:rtype: list | entailment |
def initialize(self, originalTimeSeries, calculatedTimeSeries):
"""Initializes the ErrorMeasure.
During initialization, all :py:meth:`BaseErrorMeasure.local_error()` are calculated.
:param TimeSeries originalTimeSeries: TimeSeries containing the original data.
:param TimeSeries calc... | Initializes the ErrorMeasure.
During initialization, all :py:meth:`BaseErrorMeasure.local_error()` are calculated.
:param TimeSeries originalTimeSeries: TimeSeries containing the original data.
:param TimeSeries calculatedTimeSeries: TimeSeries containing calculated data.
Cal... | entailment |
def _calculate(self, startingPercentage, endPercentage, startDate, endDate):
"""This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. Th... | This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. This has to be a value in [0.0, 100.0].
It represents the value, where the err... | entailment |
def __train(self, n_clusters=4):
"""
Calculate cluster's centroids and standard deviations. If there are at least the number of threshold rows \
then:
* Observations will be normalised.
* Standard deviations will be returned.
* Clusters will be retu... | Calculate cluster's centroids and standard deviations. If there are at least the number of threshold rows \
then:
* Observations will be normalised.
* Standard deviations will be returned.
* Clusters will be returned.
* Centroids are ordered based on their... | entailment |
def get_single_score(self, point, centroids=None, sd=None):
"""
Get a single score is a wrapper around the result of classifying a Point against a group of centroids. \
Attributes:
observation_score (dict): Original received point and normalised point.
:Example:... | Get a single score is a wrapper around the result of classifying a Point against a group of centroids. \
Attributes:
observation_score (dict): Original received point and normalised point.
:Example:
>>> { "original": [0.40369016, 0.65217912], "normalised": [1.65915104,... | entailment |
def write_model(self, filename='scores', filepath='', output_format='csv'):
"""
This method calculates the scores and writes them to a file the data frame received. If the output format
is other than 'csv' it will print the scores.
:param filename: the name to give to the fi... | This method calculates the scores and writes them to a file the data frame received. If the output format
is other than 'csv' it will print the scores.
:param filename: the name to give to the file
:type filename: string
:param filepath: the path to save the file
... | entailment |
def score(self, measurement, output_format='array'):
"""
Method to score/classify a measurement against the trained knn clusters
:param measurement: the point to classify
:type measurement: pandas.DataFrame
:param output_format: the format to return the scores ('... | Method to score/classify a measurement against the trained knn clusters
:param measurement: the point to classify
:type measurement: pandas.DataFrame
:param output_format: the format to return the scores ('array' or 'str')
:type output_format: string
:return ... | entailment |
def download_file_part_run(download_context):
"""
Function run by CreateProjectCommand to create the project.
Runs in a background process.
:param download_context: UploadContext: contains data service setup and project name to create.
"""
destination_dir, file_url_data_dict, seek_amt, bytes_to_... | Function run by CreateProjectCommand to create the project.
Runs in a background process.
:param download_context: UploadContext: contains data service setup and project name to create. | entailment |
def run(self):
"""
Download the contents of the specified project name or id to dest_directory.
"""
files_to_download = self.get_files_to_download()
total_files_size = self.get_total_files_size(files_to_download)
if self.file_download_pre_processor:
self.run_p... | Download the contents of the specified project name or id to dest_directory. | entailment |
def run_preprocessor(self, files_to_download):
"""
Run file_download_pre_processor for each file we are about to download.
:param files_to_download: [ProjectFile]: files that will be downloaded
"""
for project_file in files_to_download:
self.file_download_pre_processo... | Run file_download_pre_processor for each file we are about to download.
:param files_to_download: [ProjectFile]: files that will be downloaded | entailment |
def try_create_dir(self, path):
"""
Try to create a directory if it doesn't exist and raise error if there is a non-directory with the same name.
:param path: str path to the directory
"""
if not os.path.exists(path):
os.mkdir(path)
elif not os.path.isdir(path... | Try to create a directory if it doesn't exist and raise error if there is a non-directory with the same name.
:param path: str path to the directory | entailment |
def _get_parent_remote_paths(self):
"""
Get list of remote folders based on the list of all file urls
:return: set([str]): set of remote folders (that contain files)
"""
parent_paths = set([item.get_remote_parent_path() for item in self.file_urls])
if '' in parent_paths:
... | Get list of remote folders based on the list of all file urls
:return: set([str]): set of remote folders (that contain files) | entailment |
def make_local_directories(self):
"""
Create directories necessary to download the files into dest_directory
"""
for remote_path in self._get_parent_remote_paths():
local_path = os.path.join(self.dest_directory, remote_path)
self._assure_dir_exists(local_path) | Create directories necessary to download the files into dest_directory | entailment |
def make_big_empty_files(self):
"""
Write out a empty file so the workers can seek to where they should write and write their data.
"""
for file_url in self.file_urls:
local_path = file_url.get_local_path(self.dest_directory)
with open(local_path, "wb") as outfile... | Write out a empty file so the workers can seek to where they should write and write their data. | entailment |
def make_ranges(self, file_url):
"""
Divides file_url size into an array of ranges to be downloaded by workers.
:param: file_url: ProjectFileUrl: file url to download
:return: [(int,int)]: array of (start, end) tuples
"""
size = file_url.size
bytes_per_chunk = sel... | Divides file_url size into an array of ranges to be downloaded by workers.
:param: file_url: ProjectFileUrl: file url to download
:return: [(int,int)]: array of (start, end) tuples | entailment |
def determine_bytes_per_chunk(self, size):
"""
Calculate the size of chunk a worker should download.
The last worker may download less than this depending on file size.
:return: int: byte size for a worker
"""
workers = self.settings.config.download_workers
if not... | Calculate the size of chunk a worker should download.
The last worker may download less than this depending on file size.
:return: int: byte size for a worker | entailment |
def split_file_urls_by_size(self, size):
"""
Return tuple that contains a list large files and a list of small files based on size parameter
:param size: int: size (in bytes) that determines if a file is large or small
:return: ([ProjectFileUrl],[ProjectFileUrl]): (large file urls, small... | Return tuple that contains a list large files and a list of small files based on size parameter
:param size: int: size (in bytes) that determines if a file is large or small
:return: ([ProjectFileUrl],[ProjectFileUrl]): (large file urls, small file urls) | entailment |
def check_downloaded_files_sizes(self):
"""
Make sure the files sizes are correct. Since we manually create the files this will only catch overruns.
Raises ValueError if there is a problematic file.
"""
for file_url in self.file_urls:
local_path = file_url.get_local_p... | Make sure the files sizes are correct. Since we manually create the files this will only catch overruns.
Raises ValueError if there is a problematic file. | entailment |
def check_file_size(file_size, path):
"""
Raise an error if we didn't get all of the file.
:param file_size: int: size of this file
:param path: str path where we downloaded the file to
"""
stat_info = os.stat(path)
if stat_info.st_size != file_size:
f... | Raise an error if we didn't get all of the file.
:param file_size: int: size of this file
:param path: str path where we downloaded the file to | entailment |
def create_context(self, message_queue, task_id):
"""
Create data needed by upload_project_run(DukeDS connection info).
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly
... | Create data needed by upload_project_run(DukeDS connection info).
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly | entailment |
def get_url_and_headers_for_range(self, file_download):
"""
Return url and headers to use for downloading part of a file, adding range headers.
:param file_download: FileDownload: contains data about file we will download
:return: str, dict: url to download and headers to use
"""... | Return url and headers to use for downloading part of a file, adding range headers.
:param file_download: FileDownload: contains data about file we will download
:return: str, dict: url to download and headers to use | entailment |
def download_chunk(self, url, headers):
"""
Download part of a file and write to our file
:param url: str: URL to download this file
:param headers: dict: headers used to download this file chunk
"""
response = requests.get(url, headers=headers, stream=True)
if re... | Download part of a file and write to our file
:param url: str: URL to download this file
:param headers: dict: headers used to download this file chunk | entailment |
def _write_response_to_file(self, response):
"""
Write response to the appropriate section of the file at self.local_path.
:param response: requests.Response: response containing stream-able data
"""
with open(self.local_path, 'r+b') as outfile: # open file for read/write (no tr... | Write response to the appropriate section of the file at self.local_path.
:param response: requests.Response: response containing stream-able data | entailment |
def _on_bytes_read(self, num_bytes_read):
"""
Record our progress so we can validate that we receive all the data
:param num_bytes_read: int: number of bytes we received as part of one chunk
"""
self.actual_bytes_read += num_bytes_read
if self.actual_bytes_read > self.byt... | Record our progress so we can validate that we receive all the data
:param num_bytes_read: int: number of bytes we received as part of one chunk | entailment |
def _verify_download_complete(self):
"""
Make sure we received all the data
"""
if self.actual_bytes_read > self.bytes_to_read:
raise TooLargeChunkDownloadError(self.actual_bytes_read, self.bytes_to_read, self.local_path)
elif self.actual_bytes_read < self.bytes_to_re... | Make sure we received all the data | entailment |
def optimize(self, timeSeries, forecastingMethods=None, startingPercentage=0.0, endPercentage=100.0):
"""Runs the optimization of the given TimeSeries.
:param TimeSeries timeSeries: TimeSeries instance that requires an optimized forecast.
:param list forecastingMethods: List of forecastin... | Runs the optimization of the given TimeSeries.
:param TimeSeries timeSeries: TimeSeries instance that requires an optimized forecast.
:param list forecastingMethods: List of forecastingMethods that will be used for optimization.
:param float startingPercentage: Defines the start of the in... | entailment |
def _generate_next_parameter_value(self, parameter, forecastingMethod):
"""Generator for a specific parameter of the given forecasting method.
:param string parameter: Name of the parameter the generator is used for.
:param BaseForecastingMethod forecastingMethod: Instance of a Forecastin... | Generator for a specific parameter of the given forecasting method.
:param string parameter: Name of the parameter the generator is used for.
:param BaseForecastingMethod forecastingMethod: Instance of a ForecastingMethod.
:return: Creates a generator used to iterate over possible par... | entailment |
def optimize_forecasting_method(self, timeSeries, forecastingMethod):
"""Optimizes the parameters for the given timeSeries and forecastingMethod.
:param TimeSeries timeSeries: TimeSeries instance, containing hte original data.
:param BaseForecastingMethod forecastingMethod: ForecastingMet... | Optimizes the parameters for the given timeSeries and forecastingMethod.
:param TimeSeries timeSeries: TimeSeries instance, containing hte original data.
:param BaseForecastingMethod forecastingMethod: ForecastingMethod that is used to optimize the parameters.
:return: Returns a tuple co... | entailment |
def optimization_loop(self, timeSeries, forecastingMethod, remainingParameters, currentParameterValues=None):
"""The optimization loop.
This function is called recursively, until all parameter values were evaluated.
:param TimeSeries timeSeries: TimeSeries instance that requires an optimize... | The optimization loop.
This function is called recursively, until all parameter values were evaluated.
:param TimeSeries timeSeries: TimeSeries instance that requires an optimized forecast.
:param BaseForecastingMethod forecastingMethod: ForecastingMethod that is used to optimize the par... | entailment |
def energy_data():
"""
Connects to the database and loads Readings for device 8.
"""
cur = db.cursor().execute("""SELECT timestamp, current FROM Readings""")
original = TimeSeries()
original.initialize_from_sql_cursor(cur)
original.normalize("day", fusionMethod = "sum")
return itty.R... | Connects to the database and loads Readings for device 8. | entailment |
def optimize(request):
"""
Performs Holt Winters Parameter Optimization on the given post data.
Expects the following values set in the post of the request:
seasonLength - integer
valuesToForecast - integer
data - two dimensional array of [timestamp, value]
"""
#Parse argumen... | Performs Holt Winters Parameter Optimization on the given post data.
Expects the following values set in the post of the request:
seasonLength - integer
valuesToForecast - integer
data - two dimensional array of [timestamp, value] | entailment |
def holtWinters(request):
"""
Performs Holt Winters Smoothing on the given post data.
Expects the following values set in the post of the request:
smoothingFactor - float
trendSmoothingFactor - float
seasonSmoothingFactor - float
seasonLength - integer
valuesToForecas... | Performs Holt Winters Smoothing on the given post data.
Expects the following values set in the post of the request:
smoothingFactor - float
trendSmoothingFactor - float
seasonSmoothingFactor - float
seasonLength - integer
valuesToForecast - integer
data - two dimensi... | entailment |
def parse(self, schema, strict=True):
"""Update C{args} and C{rest}, parsing the raw request arguments.
@param schema: The L{Schema} the parameters must be extracted with.
@param strict: If C{True} an error is raised if parameters not included
in the schema are found, otherwise the ... | Update C{args} and C{rest}, parsing the raw request arguments.
@param schema: The L{Schema} the parameters must be extracted with.
@param strict: If C{True} an error is raised if parameters not included
in the schema are found, otherwise the extra parameters will be
saved in the... | entailment |
def _name_to_child_map(children):
"""
Create a map of name to child based on a list.
:param children [LocalFolder/LocalFile] list of children:
:return: map child.name -> child
"""
name_to_child = {}
for child in children:
name_to_child[child.name] = child
return name_to_child | Create a map of name to child based on a list.
:param children [LocalFolder/LocalFile] list of children:
:return: map child.name -> child | entailment |
def _update_remote_children(remote_parent, children):
"""
Update remote_ids based on on parent matching up the names of children.
:param remote_parent: RemoteProject/RemoteFolder who has children
:param children: [LocalFolder,LocalFile] children to set remote_ids based on remote children
"""
nam... | Update remote_ids based on on parent matching up the names of children.
:param remote_parent: RemoteProject/RemoteFolder who has children
:param children: [LocalFolder,LocalFile] children to set remote_ids based on remote children | entailment |
def _build_project_tree(path, followsymlinks, file_filter):
"""
Build a tree of LocalFolder with children or just a LocalFile based on a path.
:param path: str path to a directory to walk
:param followsymlinks: bool should we follow symlinks when walking
:param file_filter: FileFilter: include metho... | Build a tree of LocalFolder with children or just a LocalFile based on a path.
:param path: str path to a directory to walk
:param followsymlinks: bool should we follow symlinks when walking
:param file_filter: FileFilter: include method returns True if we should include a file/folder
:return: the top n... | entailment |
def _build_folder_tree(top_abspath, followsymlinks, file_filter):
"""
Build a tree of LocalFolder with children based on a path.
:param top_abspath: str path to a directory to walk
:param followsymlinks: bool should we follow symlinks when walking
:param file_filter: FileFilter: include method retur... | Build a tree of LocalFolder with children based on a path.
:param top_abspath: str path to a directory to walk
:param followsymlinks: bool should we follow symlinks when walking
:param file_filter: FileFilter: include method returns True if we should include a file/folder
:return: the top node of the tr... | entailment |
def add_path(self, path):
"""
Add the path and any children files/folders to the list of content.
:param path: str path to add
"""
abspath = os.path.abspath(path)
self.children.append(_build_project_tree(abspath, self.followsymlinks, self.file_filter)) | Add the path and any children files/folders to the list of content.
:param path: str path to add | entailment |
def update_remote_ids(self, remote_project):
"""
Compare against remote_project saving off the matching uuids of of matching content.
:param remote_project: RemoteProject project to compare against
"""
if remote_project:
self.remote_id = remote_project.id
... | Compare against remote_project saving off the matching uuids of of matching content.
:param remote_project: RemoteProject project to compare against | entailment |
def update_remote_ids(self, remote_folder):
"""
Set remote id based on remote_folder and check children against this folder's children.
:param remote_folder: RemoteFolder to compare against
"""
self.remote_id = remote_folder.id
_update_remote_children(remote_folder, self.... | Set remote id based on remote_folder and check children against this folder's children.
:param remote_folder: RemoteFolder to compare against | entailment |
def update_remote_ids(self, remote_file):
"""
Based on a remote file try to assign a remote_id and compare hash info.
:param remote_file: RemoteFile remote data pull remote_id from
"""
self.remote_id = remote_file.id
hash_data = self.path_data.get_hash()
if hash_d... | Based on a remote file try to assign a remote_id and compare hash info.
:param remote_file: RemoteFile remote data pull remote_id from | entailment |
def count_chunks(self, bytes_per_chunk):
"""
Based on the size of the file determine how many chunks we will need to upload.
For empty files 1 chunk is returned (DukeDS requires an empty chunk for empty files).
:param bytes_per_chunk: int: how many bytes should chunks to spglit the file ... | Based on the size of the file determine how many chunks we will need to upload.
For empty files 1 chunk is returned (DukeDS requires an empty chunk for empty files).
:param bytes_per_chunk: int: how many bytes should chunks to spglit the file into
:return: int: number of chunks that will need to... | entailment |
def matches(self, hash_alg, hash_value):
"""
Does our algorithm and hash value match the specified arguments.
:param hash_alg: str: hash algorithm
:param hash_value: str: hash value
:return: boolean
"""
return self.alg == hash_alg and self.value == hash_value | Does our algorithm and hash value match the specified arguments.
:param hash_alg: str: hash algorithm
:param hash_value: str: hash value
:return: boolean | entailment |
def mime_type(self):
"""
Guess the mimetype of a file or 'application/octet-stream' if unable to guess.
:return: str: mimetype
"""
mime_type, encoding = mimetypes.guess_type(self.path)
if not mime_type:
mime_type = 'application/octet-stream'
return mim... | Guess the mimetype of a file or 'application/octet-stream' if unable to guess.
:return: str: mimetype | entailment |
def read_whole_file(self):
"""
Slurp the whole file into memory.
Should only be used with relatively small files.
:return: str: file contents
"""
chunk = None
with open(self.path, 'rb') as infile:
chunk = infile.read()
return chunk | Slurp the whole file into memory.
Should only be used with relatively small files.
:return: str: file contents | entailment |
def add_file(self, filename, block_size=4096):
"""
Add an entire file to this hash.
:param filename: str filename of the file to hash
:param block_size: int size of chunks when reading the file
"""
with open(filename, "rb") as f:
for chunk in iter(lambda: f.re... | Add an entire file to this hash.
:param filename: str filename of the file to hash
:param block_size: int size of chunks when reading the file | entailment |
def get(cls, parent=None, id=None, data=None):
"""Inherit info from parent and return new object"""
# TODO - allow fetching of parent based on child?
if parent is not None:
route = copy(parent.route)
else:
route = {}
if id is not None and cls.ID_NAME is ... | Inherit info from parent and return new object | entailment |
def get_all(cls, parent=None, **params):
if parent is not None:
route = copy(parent.route)
else:
route = {}
if cls.ID_NAME is not None:
# Empty string triggers "get all resources"
route[cls.ID_NAME] = ""
base_obj = cls(key=parent.key, rou... | Perform a read request against the resource | entailment |
def _url(self):
"""Get the URL for the resource"""
if self.ID_NAME not in self.route.keys() and "id" in self.data.keys():
self.route[self.ID_NAME] = self.data["id"]
return self.config.BASE + self.PATH.format(**self.route) | Get the URL for the resource | entailment |
def _handle_request_exception(request):
"""Raise the proper exception based on the response"""
try:
data = request.json()
except:
data = {}
code = request.status_code
if code == requests.codes.bad:
raise BadRequestException(response=data)
... | Raise the proper exception based on the response | entailment |
def fetch(self):
"""Perform a read request against the resource"""
start = datetime.now()
r = requests.get(self._url(), auth=(self.key, ""))
self._delay_for_ratelimits(start)
if r.status_code not in self.TRUTHY_CODES:
return self._handle_request_exception(r)
... | Perform a read request against the resource | entailment |
def _process_meta(self, response):
"""Process additional data sent in response"""
for key in self.META_ENVELOPES:
self.meta[key] = response.get(key) | Process additional data sent in response | entailment |
def delete(self):
"""Delete the object"""
start = datetime.now()
r = requests.delete(self._url(), auth=(self.key, ""))
self._delay_for_ratelimits(start)
if r.status_code not in self.TRUTHY_CODES:
return self._handle_request_exception(r) | Delete the object | entailment |
def patch(self, **kwargs):
"""Change attributes of the item"""
start = datetime.now()
r = requests.patch(self._url(), auth=(self.key, ""), data=kwargs)
self._delay_for_ratelimits(start)
if r.status_code not in self.TRUTHY_CODES:
return self._handle_request_exception(... | Change attributes of the item | entailment |
def create(cls, parent=None, **kwargs):
"""Create an object and return it"""
if parent is None:
raise Exception("Parent class is required")
route = copy(parent.route)
if cls.ID_NAME is not None:
route[cls.ID_NAME] = ""
obj = cls(key=parent.key, route=ro... | Create an object and return it | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.