docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Bulk link users by email.
Arguments:
enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance
manage_learners_form (ManageLearnersForm): bound ManageLearners form instance
request (django.http.request.HttpRequest): HTTP Request i... | def _handle_bulk_upload(cls, enterprise_customer, manage_learners_form, request, email_list=None):
errors = []
emails = set()
already_linked_emails = []
duplicate_emails = []
csv_file = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.BULK_UPLOAD]
if e... | 434,773 |
Query the enrollment API and determine if a learner is enrolled in a given course run track.
Args:
user: The user whose enrollment needs to be checked
course_mode: The mode with which the enrollment should be checked
course_id: course id of the course where enrollment should... | def is_user_enrolled(cls, user, course_id, course_mode):
enrollment_client = EnrollmentApiClient()
try:
enrollments = enrollment_client.get_course_enrollment(user.username, course_id)
if enrollments and course_mode == enrollments.get('mode'):
return True
... | 434,775 |
Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't.
Args:
emails: An iterable of email addresses to split between existing and nonexisting
Returns:
users: Queryset of users who exist in the OpenEdX platform and who were in the list o... | def get_users_by_email(cls, emails):
users = User.objects.filter(email__in=emails)
present_emails = users.values_list('email', flat=True)
missing_emails = list(set(emails) - set(present_emails))
return users, missing_emails | 434,776 |
Deduplicate any outgoing message requests, and send the remainder.
Args:
http_request: The HTTP request in whose response we want to embed the messages
message_requests: A list of undeduplicated messages in the form of tuples of message type
and text- for example, ('erro... | def send_messages(cls, http_request, message_requests):
deduplicated_messages = set(message_requests)
for msg_type, text in deduplicated_messages:
message_function = getattr(messages, msg_type)
message_function(http_request, text) | 434,779 |
Notify learners about a program in which they've been enrolled.
Args:
enterprise_customer: The EnterpriseCustomer being linked to
program_details: Details about the specific program the learners were enrolled in
users: An iterable of the users or pending users who were enrol... | def notify_program_learners(cls, enterprise_customer, program_details, users):
program_name = program_details.get('title')
program_branding = program_details.get('type')
program_uuid = program_details.get('uuid')
lms_root_url = get_configuration_value_for_site(
ente... | 434,780 |
Create message for the users who were enrolled in a course or program.
Args:
users: An iterable of users who were successfully enrolled
enrolled_in (str): A string identifier for the course or program the users were enrolled in
Returns:
tuple: A 2-tuple containing a... | def get_success_enrollment_message(cls, users, enrolled_in):
enrolled_count = len(users)
return (
'success',
ungettext(
'{enrolled_count} learner was enrolled in {enrolled_in}.',
'{enrolled_count} learners were enrolled in {enrolled_in}.',... | 434,781 |
Create message for the users who were not able to be enrolled in a course or program.
Args:
users: An iterable of users who were not successfully enrolled
enrolled_in (str): A string identifier for the course or program with which enrollment was attempted
Returns:
tuple... | def get_failed_enrollment_message(cls, users, enrolled_in):
failed_emails = [user.email for user in users]
return (
'error',
_(
'The following learners could not be enrolled in {enrolled_in}: {user_list}'
).format(
enrolled_in=... | 434,782 |
Create message for the users who were enrolled in a course or program.
Args:
users: An iterable of PendingEnterpriseCustomerUsers who were successfully linked with a pending enrollment
enrolled_in (str): A string identifier for the course or program the pending users were linked to
... | def get_pending_enrollment_message(cls, pending_users, enrolled_in):
pending_emails = [pending_user.user_email for pending_user in pending_users]
return (
'warning',
_(
"The following learners do not have an account on "
"{platform_name}. ... | 434,783 |
Handle GET request - render linked learners list and "Link learner" form.
Arguments:
request (django.http.request.HttpRequest): Request instance
customer_uuid (str): Enterprise Customer UUID
Returns:
django.http.response.HttpResponse: HttpResponse | def get(self, request, customer_uuid):
context = self._build_context(request, customer_uuid)
manage_learners_form = ManageLearnersForm(
user=request.user,
enterprise_customer=context[self.ContextParameters.ENTERPRISE_CUSTOMER]
)
context.update({self.Conte... | 434,785 |
Handle POST request - handle form submissions.
Arguments:
request (django.http.request.HttpRequest): Request instance
customer_uuid (str): Enterprise Customer UUID
Returns:
django.http.response.HttpResponse: HttpResponse | def post(self, request, customer_uuid):
enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid) # pylint: disable=no-member
manage_learners_form = ManageLearnersForm(
request.POST,
request.FILES,
user=request.user,
enterprise_cus... | 434,786 |
Handle DELETE request - handle unlinking learner.
Arguments:
request (django.http.request.HttpRequest): Request instance
customer_uuid (str): Enterprise Customer UUID
Returns:
django.http.response.HttpResponse: HttpResponse | def delete(self, request, customer_uuid):
# TODO: pylint acts stupid - find a way around it without suppressing
enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid) # pylint: disable=no-member
email_to_unlink = request.GET["unlink_email"]
try:
En... | 434,787 |
Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI learner analytics.
days (int): Include course enrollment of this n... | def send_xapi_statements(self, lrs_configuration, days):
persistent_course_grades = self.get_course_completions(lrs_configuration.enterprise_customer, days)
users = self.prefetch_users(persistent_course_grades)
course_overviews = self.prefetch_courses(persistent_course_grades)
... | 434,794 |
Get course completions via PersistentCourseGrade for all the learners of given enterprise customer.
Arguments:
enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners
of this enterprise customer.
days (int): Include course enrollment of this num... | def get_course_completions(self, enterprise_customer, days):
return PersistentCourseGrade.objects.filter(
passed_timestamp__gt=datetime.datetime.now() - datetime.timedelta(days=days)
).filter(
user_id__in=enterprise_customer.enterprise_customer_users.values_list('user_id... | 434,795 |
Prefetch Users from the list of user_ids present in the persistent_course_grades.
Arguments:
persistent_course_grades (list): A list of PersistentCourseGrade.
Returns:
(dict): A dictionary containing user_id to user mapping. | def prefetch_users(persistent_course_grades):
users = User.objects.filter(
id__in=[grade.user_id for grade in persistent_course_grades]
)
return {
user.id: user for user in users
} | 434,796 |
Get template of catalog admin url.
URL template will contain a placeholder '{catalog_id}' for catalog id.
Arguments:
mode e.g. change/add.
Returns:
A string containing template for catalog url.
Example:
>>> get_catalog_admin_url_template('change')
"http://localhost:183... | def get_catalog_admin_url_template(mode='change'):
api_base_url = getattr(settings, "COURSE_CATALOG_API_URL", "")
# Extract FQDN (Fully Qualified Domain Name) from API URL.
match = re.match(r"^(?P<fqdn>(?:https?://)?[^/]+)", api_base_url)
if not match:
return ""
# Return matched FQDN... | 434,801 |
Create HTML and plaintext message bodies for a notification.
We receive a context with data we can use to render, as well as an optional site
template configration - if we don't get a template configuration, we'll use the
standard, built-in template.
Arguments:
template_context (dict): A set o... | def build_notification_message(template_context, template_configuration=None):
if (
template_configuration is not None and
template_configuration.html_template and
template_configuration.plaintext_template
):
plain_msg, html_msg = template_configuration.render_al... | 434,802 |
Return enterprise customer instance for given user.
Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model,
1. if given user is associated with any enterprise customer, return enterprise customer.
2. otherwise return `None`.
Arguments:
auth_user (contr... | def get_enterprise_customer_for_user(auth_user):
EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser') # pylint: disable=invalid-name
try:
return EnterpriseCustomerUser.objects.get(user_id=auth_user.id).enterprise_customer # pylint: disable=no-member
except Enterpris... | 434,806 |
Return the object for EnterpriseCustomerUser.
Arguments:
user_id (str): user identifier
enterprise_uuid (UUID): Universally unique identifier for the enterprise customer.
Returns:
(EnterpriseCustomerUser): enterprise customer user record | def get_enterprise_customer_user(user_id, enterprise_uuid):
EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser') # pylint: disable=invalid-name
try:
return EnterpriseCustomerUser.objects.get( # pylint: disable=no-member
enterprise_customer__uuid=enterprise_u... | 434,807 |
Return track selection url for the given course.
Arguments:
course_run (dict): A dictionary containing course run metadata.
query_parameters (dict): A dictionary containing query parameters to be added to course selection url.
Raises:
(KeyError): Raised when course run dict does not ha... | def get_course_track_selection_url(course_run, query_parameters):
try:
course_root = reverse('course_modes_choose', kwargs={'course_id': course_run['key']})
except KeyError:
LOGGER.exception(
"KeyError while parsing course run data.\nCourse Run: \n[%s]", course_run,
)
... | 434,808 |
Return url with updated query parameters.
Arguments:
url (str): Original url whose query parameters need to be updated.
query_parameters (dict): A dictionary containing query parameters to be added to course selection url.
Returns:
(slug): slug identifier for the identity provider that... | def update_query_parameters(url, query_parameters):
scheme, netloc, path, query_string, fragment = urlsplit(url)
url_params = parse_qs(query_string)
# Update url query parameters
url_params.update(query_parameters)
return urlunsplit(
(scheme, netloc, path, urlencode(sorted(url_params.... | 434,809 |
Filter audit course modes out if the enterprise customer has not enabled the 'Enable audit enrollment' flag.
Arguments:
enterprise_customer: The EnterpriseCustomer that the enrollment was created using.
course_modes: iterable with dictionaries containing a required 'mode' key | def filter_audit_course_modes(enterprise_customer, course_modes):
audit_modes = getattr(settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit'])
if not enterprise_customer.enable_audit_enrollment:
return [course_mode for course_mode in course_modes if course_mode['mode'] not in audit_modes]... | 434,810 |
Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404.
Arguments:
enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch.
Returns:
(EnterpriseCustomer): The EnterpriseCustomer given the UUID. | def get_enterprise_customer_or_404(enterprise_uuid):
EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer') # pylint: disable=invalid-name
try:
enterprise_uuid = UUID(enterprise_uuid)
return EnterpriseCustomer.objects.get(uuid=enterprise_uuid) # pylint: disable=no-member
... | 434,811 |
Traverse a paginated API response.
Extracts and concatenates "results" (list of dict) returned by DRF-powered
APIs.
Arguments:
response (Dict): Current response dict from service API
endpoint (slumber Resource object): slumber Resource object from edx-rest-api-client
Returns:
... | def traverse_pagination(response, endpoint):
results = response.get('results', [])
next_page = response.get('next')
while next_page:
querystring = parse_qs(urlparse(next_page).query, keep_blank_values=True)
response = endpoint.get(**querystring)
results += response.get('results... | 434,813 |
Strip all tags from a string except those tags provided in `allowed_tags` parameter.
Args:
text (str): string to strip html tags from
allowed_tags (list): allowed list of html tags
Returns: a string without html tags | def strip_html_tags(text, allowed_tags=None):
if text is None:
return
if allowed_tags is None:
allowed_tags = ALLOWED_TAGS
return bleach.clean(text, tags=allowed_tags, attributes=['id', 'class', 'style', 'href', 'title'], strip=True) | 434,826 |
Initialize :class:`MultipleProgramMatchError`.
Arguments:
programs_matched (int): number of programs matched where one proram was expected.
args (iterable): variable arguments
kwargs (dict): keyword arguments | def __init__(self, programs_matched, *args, **kwargs):
super(MultipleProgramMatchError, self).__init__(*args, **kwargs)
self.programs_matched = programs_matched | 434,829 |
Save xAPI statement.
Arguments:
statement (EnterpriseStatement): xAPI Statement to send to the LRS.
Raises:
ClientError: If xAPI statement fails to save. | def save_statement(self, statement):
response = self.lrs.save_statement(statement)
if not response:
raise ClientError('EnterpriseXAPIClient request failed.') | 434,833 |
Use the ``SAPSuccessFactorsAPIClient`` for content metadata transmission to SAPSF.
Arguments:
enterprise_configuration (required): SAPSF configuration connecting an enterprise to an integrated channel.
client: The REST API client that will fetch data from integrated channel. | def __init__(self, enterprise_configuration, client=SAPSuccessFactorsAPIClient):
self.enterprise_configuration = enterprise_configuration
self.client = client(enterprise_configuration) if client else None | 434,835 |
Return an export csv action.
Arguments:
description (string): action description
fields ([string]): list of model fields to include
header (bool): whether or not to output the column names as the first row | def export_as_csv_action(description="Export selected objects as CSV file", fields=None, header=True):
# adapted from https://gist.github.com/mgerring/3645889
def export_as_csv(modeladmin, request, queryset): # pylint: disable=unused-argument
opts = modeladmin.model._meta
if not ... | 434,845 |
Cleanup the pin by closing and unexporting it.
Args:
pin (int, optional): either the pin to clean up or None (default).
If None, clean up all pins.
assert_exists: if True, raise a ValueError if the pin was not
setup. Otherwise, this function is a NOOP. | def cleanup(pin=None, assert_exists=False):
if pin is None:
# Take a list of keys because we will be deleting from _open
for pin in list(_open):
cleanup(pin)
return
if not isinstance(pin, int):
raise TypeError("pin must be an int, got: {}".format(pin))
... | 434,850 |
Setup pin with mode IN or OUT.
Args:
pin (int):
mode (str): use either gpio.OUT or gpio.IN
pullup (None): rpio compatibility. If anything but None, raises
value Error
pullup (bool, optional): Initial pin value. Default is False | def setup(pin, mode, pullup=None, initial=False):
if pullup is not None:
raise ValueError("sysfs does not support pullups")
if mode not in (IN, OUT, LOW, HIGH):
raise ValueError(mode)
log.debug("Setup {0}: {1}".format(pin, mode))
f = _open[pin].direction
_write(f, mo... | 434,851 |
Get the library version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlib... | def getlibversion():
status, major_v, minor_v, release, info = _C.Hgetlibversion()
_checkErr('getlibversion', status, "cannot get lib version")
return major_v, minor_v, release, info | 435,001 |
Get file version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C... | def getfileversion(self):
status, major_v, minor_v, release, info = _C.Hgetfileversion(self._id)
_checkErr('getfileversion', status, "cannot get file version")
return major_v, minor_v, release, info | 435,003 |
Write a string of data to file by filename and folder.
Args:
folder: Target folder (e.g. c:/ladybug).
fname: File name (e.g. testPts.pts).
data: Any data as string.
mkdir: Set to True to create the directory if doesn't exist (Default: False). | def write_to_file_by_name(folder, fname, data, mkdir=False):
if not os.path.isdir(folder):
if mkdir:
preparedir(folder)
else:
created = preparedir(folder, False)
if not created:
raise ValueError("Failed to find %s." % folder)
file_path = ... | 435,175 |
Write a string of data to file.
Args:
file_path: Full path for a valid file path (e.g. c:/ladybug/testPts.pts)
data: Any data as string
mkdir: Set to True to create the directory if doesn't exist (Default: False) | def write_to_file(file_path, data, mkdir=False):
folder, fname = os.path.split(file_path)
return write_to_file_by_name(folder, fname, data, mkdir) | 435,176 |
Download a file to a directory.
Args:
url: A string to a valid URL.
target_folder: Target folder for download (e.g. c:/ladybug)
file_name: File name (e.g. testPts.zip).
mkdir: Set to True to create the directory if doesn't exist (Default: False) | def download_file_by_name(url, target_folder, file_name, mkdir=False):
# headers to "spoof" the download as coming from a browser (needed for E+ site)
__hdr__ = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 '
'(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
... | 435,181 |
Write a string of data to file.
Args:
url: A string to a valid URL.
file_path: Full path to intended download location (e.g. c:/ladybug/testPts.pts)
mkdir: Set to True to create the directory if doesn't exist (Default: False) | def download_file(url, file_path, mkdir=False):
folder, fname = os.path.split(file_path)
return download_file_by_name(url, folder, fname, mkdir) | 435,182 |
Unzip a compressed file.
Args:
source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip)
dest_dir: Target folder to extract to (e.g. c:/ladybug).
Default is set to the same directory as the source file.
mkdir: Set to True to create the directory if doesn't ... | def unzip_file(source_file, dest_dir=None, mkdir=False):
# set default dest_dir and create it if need be.
if dest_dir is None:
dest_dir, fname = os.path.split(source_file)
elif not os.path.isdir(dest_dir):
if mkdir:
preparedir(dest_dir)
else:
created = pr... | 435,183 |
Load a CSV file into a Python matrix of strings.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) | def csv_to_matrix(csv_file_path):
mtx = []
with open(csv_file_path) as csv_data_file:
for row in csv_data_file:
mtx.append(row.split(','))
return mtx | 435,184 |
Load a CSV file consisting only of numbers into a Python matrix of floats.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) | def csv_to_num_matrix(csv_file_path):
mtx = []
with open(csv_file_path) as csv_data_file:
for row in csv_data_file:
mtx.append([float(val) for val in row.split(',')])
return mtx | 435,185 |
Initalize the class.
Args:
file_path: Address to a local .stat file. | def __init__(self, file_path):
if file_path is not None:
if not os.path.isfile(file_path):
raise ValueError(
'Cannot find an stat file at {}'.format(file_path))
if not file_path.lower().endswith('stat'):
raise TypeError('{} is ... | 435,186 |
Create a data type from a dictionary.
Args:
data: Data as a dictionary.
{
"name": data type name of the data type as a string
"data_type": the class name of the data type as a string
"base_unit": the base unit of the data t... | def from_json(cls, data):
assert 'name' in data, 'Required keyword "name" is missing!'
assert 'data_type' in data, 'Required keyword "data_type" is missing!'
if cls._type_enumeration is None:
cls._type_enumeration = _DataTypeEnumeration(import_modules=False)
if data... | 435,207 |
Check if a certain unit is acceptable for the data type.
Args:
unit: A text string representing the abbreviated unit.
raise_exception: Set to True to raise an exception if not acceptable. | def is_unit_acceptable(self, unit, raise_exception=True):
_is_acceptable = unit in self.units
if _is_acceptable or raise_exception is False:
return _is_acceptable
else:
raise ValueError(
'{0} is not an acceptable unit type for {1}. '
... | 435,208 |
Check if a list of values is within physically/mathematically possible range.
Args:
values: A list of values.
unit: The unit of the values. If not specified, the default metric
unit will be assumed.
raise_exception: Set to True to raise an exception if not i... | def is_in_range(self, values, unit=None, raise_exception=True):
self._is_numeric(values)
if unit is None or unit == self.units[0]:
minimum = self.min
maximum = self.max
else:
namespace = {'self': self}
self.is_unit_acceptable(unit, True)
... | 435,209 |
Initiate Ladybug header for lists.
Args:
data_type: A DataType object. (e.g. Temperature)
unit: data_type unit (Default: None)
analysis_period: A Ladybug analysis period (Defualt: None)
metadata: Optional dictionary of additional metadata,
contain... | def __init__(self, data_type, unit=None,
analysis_period=None, metadata=None):
assert hasattr(data_type, 'isDataType'), \
'data_type must be a Ladybug DataType. Got {}'.format(type(data_type))
if unit is None:
unit = data_type.units[0]
else:
... | 435,216 |
Create a header from a dictionary.
Args:
data: {
"data_type": {}, //Type of data (e.g. Temperature)
"unit": string,
"analysis_period": {} // A Ladybug AnalysisPeriod
"metadata": {}, // A dictionary of metadata
} | def from_json(cls, data):
# assign default values
assert 'data_type' in data, 'Required keyword "data_type" is missing!'
keys = ('data_type', 'unit', 'analysis_period', 'metadata')
for key in keys:
if key not in data:
data[key] = None
data_ty... | 435,217 |
Determine the bins for the DIRINT coefficients.
Args:
ktp : Altitude-independent clearness index
alt : Solar altitude angle
w : precipitable water estimated from surface dew-point temperature
dktp : stability index
Returns:
tuple of ktp_bin, alt_bin, w_bin, dktp_bin | def _dirint_bins(ktp, alt, w, dktp):
it = range(len(ktp))
# Create kt_prime bins
ktp_bin = [-1] * len(ktp)
ktp_bin = [0 if ktp[i] >= 0 and ktp[i] < 0.24 else ktp_bin[i] for i in it]
ktp_bin = [1 if ktp[i] >= 0.24 and ktp[i] < 0.4 else ktp_bin[i] for i in it]
ktp_bin = [2 if ktp[i] >= 0.4 a... | 435,228 |
Calculate Kn for `disc`
Args:
clearness_index : numeric
airmass : numeric
max_airmass : float
airmass > max_airmass is set to max_airmass before being used
in calculating Kn.
Returns:
Kn : numeric
am : numeric
airmass used in the calc... | def _disc_kn(clearness_index, airmass, max_airmass=12):
# short names for equations
kt = clearness_index
am = airmass
am = min(am, max_airmass) # GH 450
# powers of kt will be used repeatedly, so compute only once
kt2 = kt * kt # about the same as kt ** 2
kt3 = kt2 * kt # 5-10x fas... | 435,230 |
Create a Data Collection from a dictionary.
Args:
{
"header": A Ladybug Header,
"values": An array of values,
"datetimes": An array of datetimes,
"validated_a_period": Boolean for whether header analysis_period is valid
} | def from_json(cls, data):
assert 'header' in data, 'Required keyword "header" is missing!'
assert 'values' in data, 'Required keyword "values" is missing!'
assert 'datetimes' in data, 'Required keyword "datetimes" is missing!'
collection = cls(Header.from_json(data['header']), d... | 435,239 |
Filter a Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data | def filter_by_analysis_period(self, analysis_period):
self._check_analysis_period(analysis_period)
_filtered_data = self.filter_by_moys(analysis_period.moys)
_filtered_data.header._analysis_period = analysis_period
return _filtered_data | 435,242 |
Filter the Data Collection based on an analysis period.
Args:
hoys: A List of hours of the year 0..8759
Return:
A new Data Collection with filtered data | def filter_by_hoys(self, hoys):
_moys = tuple(int(hour * 60) for hour in hoys)
return self.filter_by_moys(_moys) | 435,243 |
Filter the Data Collection based on a list of minutes of the year.
Args:
moys: A List of minutes of the year [0..8759 * 60]
Return:
A new Data Collection with filtered data | def filter_by_moys(self, moys):
_filt_values, _filt_datetimes = self._filter_by_moys_slow(moys)
collection = HourlyDiscontinuousCollection(
self.header.duplicate(), _filt_values, _filt_datetimes)
collection._validated_a_period = self._validated_a_period
return collec... | 435,244 |
Initialize hourly discontinuous collection.
Args:
header: A Ladybug Header object. Note that this header
must have an AnalysisPeriod on it that aligns with the
list of values.
values: A list of values. Note that the length of this list
m... | def __init__(self, header, values):
assert isinstance(header, Header), \
'header must be a Ladybug Header object. Got {}'.format(type(header))
assert isinstance(header.analysis_period, AnalysisPeriod), \
'header of {} must have an analysis_period.'.format(self.__class__.... | 435,257 |
Create a Data Collection from a dictionary.
Args:
{
"header": A Ladybug Header,
"values": An array of values,
} | def from_json(cls, data):
assert 'header' in data, 'Required keyword "header" is missing!'
assert 'values' in data, 'Required keyword "values" is missing!'
return cls(Header.from_json(data['header']), data['values']) | 435,258 |
Filter the Data Collection based on a conditional statement.
Args:
statement: A conditional statement as a string (e.g. a > 25 and a%5 == 0).
The variable should always be named as 'a' (without quotations).
Return:
A new Data Collection containing only the filte... | def filter_by_conditional_statement(self, statement):
_filt_values, _filt_datetimes = self._filter_by_statement(statement)
collection = HourlyDiscontinuousCollection(
self.header.duplicate(), _filt_values, _filt_datetimes)
collection._validated_a_period = True
return... | 435,261 |
Filter the Data Collection based on a list of booleans.
Args:
pattern: A list of True/False values. Typically, this is a list
with a length matching the length of the Data Collections values
but it can also be a pattern to be repeated over the Data Collection.
... | def filter_by_pattern(self, pattern):
_filt_values, _filt_datetimes = self._filter_by_pattern(pattern)
collection = HourlyDiscontinuousCollection(
self.header.duplicate(), _filt_values, _filt_datetimes)
collection._validated_a_period = True
return collection | 435,262 |
Filter the Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data | def filter_by_analysis_period(self, analysis_period):
self._check_analysis_period(analysis_period)
analysis_period = self._get_analysis_period_subset(analysis_period)
if analysis_period.st_hour == 0 and analysis_period.end_hour == 23:
# We can still return an Hourly Continu... | 435,263 |
Filter the Data Collection based onva list of hoys.
Args:
hoys: A List of hours of the year 0..8759
Return:
A new Data Collection with filtered data | def filter_by_hoys(self, hoys):
existing_hoys = self.header.analysis_period.hoys
hoys = [h for h in hoys if h in existing_hoys]
_moys = tuple(int(hour * 60) for hour in hoys)
return self.filter_by_moys(_moys) | 435,264 |
Filter the Data Collection based on a list of minutes of the year.
Args:
moys: A List of minutes of the year [0..8759 * 60]
Return:
A new Data Collection with filtered data | def filter_by_moys(self, moys):
t_s = 60 / self.header.analysis_period.timestep
st_ind = self.header.analysis_period.st_time.moy / t_s
if self.header.analysis_period.is_reversed is False:
_filt_indices = [int(moy / t_s - st_ind) for moy in moys]
else:
if ... | 435,265 |
Check if this Data Collection is aligned with another.
Aligned Data Collections are of the same Data Collection class,
have the same number of values and have matching datetimes.
Args:
data_collection: The Data Collection which you want to test if this
collection is... | def is_collection_aligned(self, data_collection):
if self._collection_type != data_collection._collection_type:
return False
elif len(self.values) != len(data_collection.values):
return False
elif self.header.analysis_period != data_collection.header.analysis_per... | 435,269 |
Filter the Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data | def filter_by_analysis_period(self, analysis_period):
self._check_analysis_period(analysis_period)
_filtered_data = self.filter_by_doys(analysis_period.doys_int)
_filtered_data.header._analysis_period = analysis_period
return _filtered_data | 435,273 |
Filter the Data Collection based on a list of days of the year (as integers).
Args:
doys: A List of days of the year [1..365]
Return:
A new Data Collection with filtered data | def filter_by_doys(self, doys):
_filt_values = []
_filt_datetimes = []
for i, d in enumerate(self.datetimes):
if d in doys:
_filt_datetimes.append(d)
_filt_values.append(self._values[i])
_filt_header = self.header.duplicate()
r... | 435,274 |
Filter the Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data | def filter_by_analysis_period(self, analysis_period):
_filtered_data = self.filter_by_months(analysis_period.months_int)
_filtered_data.header._analysis_period = analysis_period
return _filtered_data | 435,278 |
Filter the Data Collection based on a list of months of the year (as integers).
Args:
months: A List of months of the year [1..12]
Return:
A new Data Collection with filtered data | def filter_by_months(self, months):
_filt_values = []
_filt_datetimes = []
for i, d in enumerate(self.datetimes):
if d in months:
_filt_datetimes.append(d)
_filt_values.append(self._values[i])
_filt_header = self.header.duplicate()
... | 435,279 |
Filter the Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data | def filter_by_analysis_period(self, analysis_period):
_filtered_data = self.filter_by_months_per_hour(
analysis_period.months_per_hour)
_filtered_data.header._analysis_period = analysis_period
return _filtered_data | 435,283 |
Filter the Data Collection based on a list of months per hour (as strings).
Args:
months_per_hour: A list of tuples representing months per hour.
Each tuple should possess two values: the first is the month
and the second is the hour. (eg. (12, 23) = December at 11 PM)
... | def filter_by_months_per_hour(self, months_per_hour):
_filt_values = []
_filt_datetimes = []
for i, d in enumerate(self.datetimes):
if d in months_per_hour:
_filt_datetimes.append(d)
_filt_values.append(self._values[i])
return MonthlyP... | 435,284 |
Create a location from a dictionary.
Args:
data: {
"city": "-",
"latitude": 0,
"longitude": 0,
"time_zone": 0,
"elevation": 0} | def from_json(cls, data):
optional_keys = ('city', 'state', 'country', 'latitude', 'longitude',
'time_zone', 'elevation', 'station_id', 'source')
for key in optional_keys:
if key not in data:
data[key] = None
return cls(data['city'],... | 435,293 |
Try to create a Ladybug location from a location string.
Args:
locationString: Location string
Usage:
l = Location.from_location(locationString) | def from_location(cls, location):
if not location:
return cls()
try:
if hasattr(location, 'isLocation'):
# Ladybug location
return location
elif hasattr(location, 'Latitude'):
# Revit's location
... | 435,294 |
Initalize an EPW object from from a local .epw file.
Args:
file_path: Local file address to an .epw file. | def __init__(self, file_path):
self._file_path = os.path.normpath(file_path) if file_path is not None else None
self._is_header_loaded = False
self._is_data_loaded = False
self._is_ip = False # track if collections have been coverted to IP
# placeholders for the EPW da... | 435,303 |
Save epw object as an epw file.
args:
file_path: A string representing the path to write the epw file to. | def save(self, file_path):
# load data if it's not loaded convert to SI if it is in IP
if not self.is_data_loaded:
self._import_data()
originally_ip = False
if self.is_ip is True:
self.convert_to_si()
originally_ip = True
# write the... | 435,325 |
Return a data field by field number.
This is a useful method to get the values for fields that Ladybug
currently doesn't import by default. You can find list of fields by typing
EPWFields.fields
Args:
field_number: a value between 0 to 34 for different available epw fields.... | def _get_data_by_field(self, field_number):
if not self.is_data_loaded:
self._import_data()
# check input data
if not 0 <= field_number < self._num_of_fields:
raise ValueError("Field number should be between 0-%d" % self._num_of_fields)
return self._dat... | 435,327 |
Write an wea file from the epw file.
WEA carries radiation values from epw. Gendaymtx uses these values to
generate the sky. For an annual analysis it is identical to using epw2wea.
args:
file_path: Full file path for output file.
hoys: List of hours of the year. Defaul... | def to_wea(self, file_path, hoys=None):
hoys = hoys or xrange(len(self.direct_normal_radiation.datetimes))
if not file_path.lower().endswith('.wea'):
file_path += '.wea'
originally_ip = False
if self.is_ip is True:
self.convert_to_si()
origin... | 435,330 |
Check if time is included in analysis period.
Return True if time is inside this analysis period,
otherwise return False
Args:
time: A DateTime to be tested
Returns:
A boolean. True if time is included in analysis period | def is_time_included(self, time):
if self._timestamps_data is None:
self._calculate_timestamps()
# time filtering in Ladybug Tools is slightly different than "normal"
# filtering since start hour and end hour will be applied for every day.
# For instance 2/20 9am to ... | 435,347 |
Create wea object from a wea file.
Args:
weafile:Full path to wea file.
timestep: An optional integer to set the number of time steps per hour.
Default is 1 for one value per hour. If the wea file has a time step
smaller than an hour adjust this input acc... | def from_file(cls, weafile, timestep=1, is_leap_year=False):
assert os.path.isfile(weafile), 'Failed to find {}'.format(weafile)
location = Location()
with open(weafile, readmode) as weaf:
first_line = weaf.readline()
assert first_line.startswith('place'), \
... | 435,358 |
Create an ASHRAE Revised Clear Sky wea object from the monthly sky
optical depths in a .stat file.
Args:
statfile: Full path to the .stat file.
timestep: An optional integer to set the number of time steps per
hour. Default is 1 for one value per hour.
... | def from_stat_file(cls, statfile, timestep=1, is_leap_year=False):
stat = STAT(statfile)
# check to be sure the stat file does not have missing tau values
def check_missing(opt_data, data_name):
if opt_data == []:
raise ValueError('Stat file contains no opti... | 435,360 |
Unflatten a falttened generator.
Args:
guide: A guide list to follow the structure
falttened_input: A flattened iterator object
Usage:
guide = [["a"], ["b","c","d"], [["e"]], ["f"]]
input_list = [0, 1, 2, 3, 4, 5, 6, 7]
unflatten(guide, iter(input_list))
>> [[0... | def unflatten(guide, falttened_input):
return [unflatten(sub_list, falttened_input) if isinstance(sub_list, list)
else next(falttened_input) for sub_list in guide] | 435,377 |
Get Sun data for an hour of the year.
Args:
month: An integer between 1-12
day: An integer between 1-31
hour: A positive number between 0..23
is_solar_time: A boolean to indicate if the input hour is solar time.
(Default: False)
Returns:
... | def calculate_sun(self, month, day, hour, is_solar_time=False):
datetime = DateTime(month, day, *self._calculate_hour_and_minute(hour),
leap_year=self.is_leap_year)
return self.calculate_sun_from_date_time(datetime, is_solar_time) | 435,391 |
Get Sun data for an hour of the year.
Args:
datetime: Ladybug datetime
is_solar_time: A boolean to indicate if the input hour is solar time
(Default: False).
Returns:
A sun object for this particular time | def calculate_sun_from_hoy(self, hoy, is_solar_time=False):
datetime = DateTime.from_hoy(hoy, self.is_leap_year)
return self.calculate_sun_from_date_time(datetime, is_solar_time) | 435,392 |
Get Sun for an hour of the year.
This code is originally written by Trygve Wastvedt \
(Trygve.Wastvedt@gmail.com)
based on (NOAA) and modified by Chris Mackey and Mostapha Roudsari
Args:
datetime: Ladybug datetime
is_solar_time: A boolean to indicate if the inp... | def calculate_sun_from_date_time(self, datetime, is_solar_time=False):
# TODO(mostapha): This should be more generic and based on a method
if datetime.year != 2016 and self.is_leap_year:
datetime = DateTime(datetime.month, datetime.day, datetime.hour,
... | 435,393 |
Create a DDY from a dictionary.
Args:
data = {
"location": ladybug Location schema,
"design_days": [] // list of ladybug DesignDay schemas} | def from_json(cls, data):
required_keys = ('location', 'design_days')
for key in required_keys:
assert key in data, 'Required key "{}" is missing!'.format(key)
return cls(Location.from_json(data['location']),
[DesignDay.from_json(des_day) for des_day in d... | 435,421 |
Initalize from a ddy file object from an existing ddy file.
args:
file_path: A string representing a complete path to the .ddy file. | def from_ddy_file(cls, file_path):
# check that the file is there
if not os.path.isfile(file_path):
raise ValueError(
'Cannot find a .ddy file at {}'.format(file_path))
if not file_path.lower().endswith('.ddy'):
raise ValueError(
'... | 435,422 |
Save ddy object as a .ddy file.
args:
file_path: A string representing the path to write the ddy file to. | def save(self, file_path):
# write all data into the file
# write the file
data = self.location.ep_style_location_string + '\n\n'
for d_day in self.design_days:
data = data + d_day.ep_style_string + '\n\n'
write_to_file(file_path, data, True) | 435,423 |
Create a Design Day from a dictionary.
Args:
data = {
"name": string,
"day_type": string,
"location": ladybug Location schema,
"dry_bulb_condition": ladybug DryBulbCondition schema,
"humidity_condition": ladybug HumidityCondition schema,
... | def from_json(cls, data):
required_keys = ('name', 'day_type', 'location', 'dry_bulb_condition',
'humidity_condition', 'wind_condition', 'sky_condition')
for key in required_keys:
assert key in data, 'Required key "{}" is missing!'.format(key)
retur... | 435,430 |
Initalize from an EnergyPlus string of a SizingPeriod:DesignDay.
args:
ep_string: A full string representing a SizingPeriod:DesignDay. | def from_ep_string(cls, ep_string, location):
# format the object into a list of properties
ep_string = ep_string.strip()
if '\n' in ep_string:
ep_lines = ep_string.split('\n')
else:
ep_lines = ep_string.split('\r')
lines = [l.split('!')[0].strip(... | 435,431 |
Create a Humidity Condition from a dictionary.
Args:
data = {
"hum_type": string,
"hum_value": float,
"barometric_pressure": float,
"schedule": string,
"wet_bulb_range": string} | def from_json(cls, data):
# Check required and optional keys
required_keys = ('hum_type', 'hum_value')
optional_keys = {'barometric_pressure': 101325,
'schedule': '', 'wet_bulb_range': ''}
for key in required_keys:
assert key in data, 'Requir... | 435,456 |
Get a list of dew points (C) at each hour over the design day.
args:
dry_bulb_condition: The dry bulb condition for the day. | def hourly_dew_point_values(self, dry_bulb_condition):
hourly_dew_point = []
max_dpt = self.dew_point(dry_bulb_condition.dry_bulb_max)
for db in dry_bulb_condition.hourly_values:
if db >= max_dpt:
hourly_dew_point.append(max_dpt)
else:
... | 435,457 |
Get the dew point (C), which is constant throughout the day (except at saturation).
args:
db: The maximum dry bulb temperature over the day. | def dew_point(self, db):
if self._hum_type == 'Dewpoint':
return self._hum_value
elif self._hum_type == 'Wetbulb':
return dew_point_from_db_wb(
db, self._hum_value, self._barometric_pressure)
elif self._hum_type == 'HumidityRatio':
ret... | 435,458 |
Create a Wind Condition from a dictionary.
Args:
data = {
"wind_speed": float,
"wind_direction": float,
"rain": bool,
"snow_on_ground": bool} | def from_json(cls, data):
# Check required and optional keys
optional_keys = {'wind_direction': 0, 'rain': False, 'snow_on_ground': False}
assert 'wind_speed' in data, 'Required key "wind_speed" is missing!'
for key, val in optional_keys.items():
if key not in data:
... | 435,464 |
Create a Sky Condition from a dictionary.
Args:
data = {
"solar_model": string,
"month": int,
"day_of_month": int,
"daylight_savings_indicator": string // "Yes" or "No"} | def from_json(cls, data):
# Check required and optional keys
required_keys = ('solar_model', 'month', 'day_of_month')
for key in required_keys:
assert key in data, 'Required key "{}" is missing!'.format(key)
if data['solar_model'] == 'ASHRAEClearSky':
re... | 435,471 |
Create a Sky Condition from a dictionary.
Args:
data = {
"solar_model": string,
"month": int,
"day_of_month": int,
"clearness": float,
"daylight_savings_indicator": string // "Yes" or "No"} | def from_json(cls, data):
# Check required and optional keys
required_keys = ('solar_model', 'month', 'day_of_month', 'clearness')
for key in required_keys:
assert key in data, 'Required key "{}" is missing!'.format(key)
if 'daylight_savings_indicator' not in data:
... | 435,480 |
Initialize base collection.
Args:
header: A Ladybug Header object.
values: A list of values.
datetimes: A list of Ladybug DateTime objects that aligns with
the list of values. | def __init__(self, header, values, datetimes):
assert isinstance(header, Header), \
'header must be a Ladybug Header object. Got {}'.format(type(header))
assert isinstance(datetimes, Iterable) \
and not isinstance(datetimes, (str, dict, bytes, bytearray)), \
... | 435,489 |
Create a Data Collection from a dictionary.
Args:
{
"header": A Ladybug Header,
"values": An array of values,
"datetimes": An array of datetimes,
"validated_a_period": Boolean for whether header analysis_period is valid
} | def from_json(cls, data):
assert 'header' in data, 'Required keyword "header" is missing!'
assert 'values' in data, 'Required keyword "values" is missing!'
assert 'datetimes' in data, 'Required keyword "datetimes" is missing!'
coll = cls(Header.from_json(data['header']), data['v... | 435,490 |
Get a value representing a the input percentile of the Data Collection.
Args:
percentile: A float value from 0 to 100 representing the
requested percentile.
Return:
The Data Collection value at the input percentile | def get_percentile(self, percentile):
assert 0 <= percentile <= 100, \
'percentile must be between 0 and 100. Got {}'.format(percentile)
return self._percentile(self._values, percentile) | 435,499 |
Filter the Data Collection based on a conditional statement.
Args:
statement: A conditional statement as a string (e.g. a > 25 and a%5 == 0).
The variable should always be named as 'a' (without quotations).
Return:
A new Data Collection containing only the filte... | def filter_by_conditional_statement(self, statement):
_filt_values, _filt_datetimes = self._filter_by_statement(statement)
if self._enumeration is None:
self._get_mutable_enumeration()
col_obj = self._enumeration['mutable'][self._collection_type]
collection = col_obj... | 435,500 |
Filter the Data Collection based on a list of booleans.
Args:
pattern: A list of True/False values. Typically, this is a list
with a length matching the length of the Data Collections values
but it can also be a pattern to be repeated over the Data Collection.
... | def filter_by_pattern(self, pattern):
_filt_values, _filt_datetimes = self._filter_by_pattern(pattern)
if self._enumeration is None:
self._get_mutable_enumeration()
col_obj = self._enumeration['mutable'][self._collection_type]
collection = col_obj(self.header.duplica... | 435,501 |
Check if this Data Collection is aligned with another.
Aligned Data Collections are of the same Data Collection class, have the
same number of values and have matching datetimes.
Args:
data_collection: The Data Collection which you want to test if this
collection is... | def is_collection_aligned(self, data_collection):
if self._collection_type != data_collection._collection_type:
return False
elif len(self.values) != len(data_collection.values):
return False
elif self.datetimes != data_collection.datetimes:
return Fa... | 435,502 |
Test if a series of Data Collections are aligned with one another.
Aligned Data Collections are of the same Data Collection class, have the
same number of values and have matching datetimes.
Args:
data_collections: A list of Data Collections for which you want to
te... | def are_collections_aligned(data_collections, raise_exception=True):
if len(data_collections) > 1:
first_coll = data_collections[0]
for coll in data_collections[1:]:
if not first_coll.is_collection_aligned(coll):
if raise_exception is True:
... | 435,508 |
Find the percentile of a list of values.
Args:
values: A list of values for which percentiles are desired
percent: A float value from 0 to 100 representing the requested percentile.
key: optional key function to compute value from each element of N.
Return:
... | def _percentile(self, values, percent, key=lambda x: x):
vals = sorted(values)
k = (len(vals) - 1) * (percent / 100)
f = math.floor(k)
c = math.ceil(k)
if f == c:
return key(vals[int(k)])
d0 = key(vals[int(f)]) * (c - k)
d1 = key(vals[int(c)])... | 435,516 |
Create Ladybug datetime.
Args:
month: A value for month between 1-12 (Defualt: 1).
day: A value for day between 1-31 (Defualt: 1).
hour: A value for hour between 0-23 (Defualt: 0).
minute: A value for month between 0-59 (Defualt: 0).
leap_year: A bool... | def __new__(cls, month=1, day=1, hour=0, minute=0, leap_year=False):
year = 2016 if leap_year else 2017
hour, minute = cls._calculate_hour_and_minute(hour + minute / 60.0)
try:
return datetime.__new__(cls, year, month, day, hour, minute)
except ValueError as e:
... | 435,522 |
Creat datetime from a dictionary.
Args:
data: {
'month': A value for month between 1-12. (Defualt: 1)
'day': A value for day between 1-31. (Defualt: 1)
'hour': A value for hour between 0-23. (Defualt: 0)
'minute': A value for month bet... | def from_json(cls, data):
if 'month' not in data:
data['month'] = 1
if 'day' not in data:
data['day'] = 1
if 'hour' not in data:
data['hour'] = 0
if 'minute' not in data:
data['minute'] = 0
if 'year' not in data:
... | 435,523 |
Create Ladybug Datetime from an hour of the year.
Args:
hoy: A float value 0 <= and < 8760 | def from_hoy(cls, hoy, leap_year=False):
return cls.from_moy(round(hoy * 60), leap_year) | 435,524 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.