sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _do_highlight(content, query, tag='em'):
"""
Highlight `query` terms in `content` with html `tag`.
This method assumes that the input text (`content`) does not contain
any special formatting. That is, it does not contain any html tags
or similar markup that could be screwed... | Highlight `query` terms in `content` with html `tag`.
This method assumes that the input text (`content`) does not contain
any special formatting. That is, it does not contain any html tags
or similar markup that could be screwed up by the highlighting.
Required arguments:
... | entailment |
def _prepare_facet_field_spies(self, facets):
"""
Returns a list of spies based on the facets
used to count frequencies.
"""
spies = []
for facet in facets:
slot = self.column[facet]
spy = xapian.ValueCountMatchSpy(slot)
# add attribute... | Returns a list of spies based on the facets
used to count frequencies. | entailment |
def _process_facet_field_spies(self, spies):
"""
Returns a dict of facet names with lists of
tuples of the form (term, term_frequency)
from a list of spies that observed the enquire.
"""
facet_dict = {}
for spy in spies:
field = self.schema[spy.slot]
... | Returns a dict of facet names with lists of
tuples of the form (term, term_frequency)
from a list of spies that observed the enquire. | entailment |
def _do_multivalued_field_facets(self, results, field_facets):
"""
Implements a multivalued field facet on the results.
This is implemented using brute force - O(N^2) -
because Xapian does not have it implemented yet
(see http://trac.xapian.org/ticket/199)
"""
fa... | Implements a multivalued field facet on the results.
This is implemented using brute force - O(N^2) -
because Xapian does not have it implemented yet
(see http://trac.xapian.org/ticket/199) | entailment |
def _do_date_facets(results, date_facets):
"""
Private method that facets a document by date ranges
Required arguments:
`results` -- A list SearchResults to facet
`date_facets` -- A dictionary containing facet parameters:
{'field': {'start_date': ..., 'en... | Private method that facets a document by date ranges
Required arguments:
`results` -- A list SearchResults to facet
`date_facets` -- A dictionary containing facet parameters:
{'field': {'start_date': ..., 'end_date': ...: 'gap_by': '...', 'gap_amount': n}}
... | entailment |
def _do_query_facets(self, results, query_facets):
"""
Private method that facets a document by query
Required arguments:
`results` -- A list SearchResults to facet
`query_facets` -- A dictionary containing facet parameters:
{'field': 'query', [...]}
... | Private method that facets a document by query
Required arguments:
`results` -- A list SearchResults to facet
`query_facets` -- A dictionary containing facet parameters:
{'field': 'query', [...]}
For each query in `query_facets`, generates a dictionary entry wit... | entailment |
def _do_spelling_suggestion(database, query, spelling_query):
"""
Private method that returns a single spelling suggestion based on
`spelling_query` or `query`.
Required arguments:
`database` -- The database to check spelling against
`query` -- The query to check... | Private method that returns a single spelling suggestion based on
`spelling_query` or `query`.
Required arguments:
`database` -- The database to check spelling against
`query` -- The query to check
`spelling_query` -- If not None, this will be checked instead of `que... | entailment |
def _database(self, writable=False):
"""
Private method that returns a xapian.Database for use.
Optional arguments:
``writable`` -- Open the database in read/write mode (default=False)
Returns an instance of a xapian.Database or xapian.WritableDatabase
"""
i... | Private method that returns a xapian.Database for use.
Optional arguments:
``writable`` -- Open the database in read/write mode (default=False)
Returns an instance of a xapian.Database or xapian.WritableDatabase | entailment |
def _get_enquire_mset(database, enquire, start_offset, end_offset, checkatleast=DEFAULT_CHECK_AT_LEAST):
"""
A safer version of Xapian.enquire.get_mset
Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`,
attempting a `database.reopen` as needed.
Requ... | A safer version of Xapian.enquire.get_mset
Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`,
attempting a `database.reopen` as needed.
Required arguments:
`database` -- The database to be read
`enquire` -- An instance of an Xapian.enquire o... | entailment |
def _get_document_data(database, document):
"""
A safer version of Xapian.document.get_data
Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`,
attempting a `database.reopen` as needed.
Required arguments:
`database` -- The database to be... | A safer version of Xapian.document.get_data
Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`,
attempting a `database.reopen` as needed.
Required arguments:
`database` -- The database to be read
`document` -- An instance of an Xapian.documen... | entailment |
def _get_hit_count(self, database, enquire):
"""
Given a database and enquire instance, returns the estimated number
of matches.
Required arguments:
`database` -- The database to be queried
`enquire` -- The enquire instance
"""
return self._get_en... | Given a database and enquire instance, returns the estimated number
of matches.
Required arguments:
`database` -- The database to be queried
`enquire` -- The enquire instance | entailment |
def _multi_value_field(self, field):
"""
Private method that returns `True` if a field is multi-valued, else
`False`.
Required arguemnts:
`field` -- The field to lookup
Returns a boolean value indicating whether the field is multi-valued.
"""
for fie... | Private method that returns `True` if a field is multi-valued, else
`False`.
Required arguemnts:
`field` -- The field to lookup
Returns a boolean value indicating whether the field is multi-valued. | entailment |
def _query_from_term(self, term, field_name, filter_type, is_not):
"""
Uses arguments to construct a list of xapian.Query's.
"""
if field_name != 'content' and field_name not in self.backend.column:
raise InvalidIndexError('field "%s" not indexed' % field_name)
# It ... | Uses arguments to construct a list of xapian.Query's. | entailment |
def _filter_contains(self, term, field_name, field_type, is_not):
"""
Splits the sentence in terms and join them with OR,
using stemmed and un-stemmed.
Assumes term is not a list.
"""
if field_type == 'text':
term_list = term.split()
else:
... | Splits the sentence in terms and join them with OR,
using stemmed and un-stemmed.
Assumes term is not a list. | entailment |
def _filter_in(self, term_list, field_name, field_type, is_not):
"""
Returns a query that matches exactly ANY term in term_list.
Notice that:
A in {B,C} <=> (A = B or A = C)
~(A in {B,C}) <=> ~(A = B or A = C)
Because OP_AND_NOT(C, D) <=> (C and ~D), then D=(A in {B,C}... | Returns a query that matches exactly ANY term in term_list.
Notice that:
A in {B,C} <=> (A = B or A = C)
~(A in {B,C}) <=> ~(A = B or A = C)
Because OP_AND_NOT(C, D) <=> (C and ~D), then D=(A in {B,C}) requires `is_not=False`.
Assumes term is a list. | entailment |
def _filter_exact(self, term, field_name, field_type, is_not):
"""
Returns a query that matches exactly the un-stemmed term
with positional order.
Assumes term is not a list.
"""
if field_type == 'text' and field_name not in (DJANGO_CT,):
term = '^ %s $' % te... | Returns a query that matches exactly the un-stemmed term
with positional order.
Assumes term is not a list. | entailment |
def _filter_startswith(self, term, field_name, field_type, is_not):
"""
Returns a startswith query on the un-stemmed term.
Assumes term is not a list.
"""
if field_type == 'text':
if len(term.split()) == 1:
term = '^ %s*' % term
query ... | Returns a startswith query on the un-stemmed term.
Assumes term is not a list. | entailment |
def _or_query(self, term_list, field, field_type):
"""
Joins each item of term_list decorated by _term_query with an OR.
"""
term_list = [self._term_query(term, field, field_type) for term in term_list]
return xapian.Query(xapian.Query.OP_OR, term_list) | Joins each item of term_list decorated by _term_query with an OR. | entailment |
def _phrase_query(self, term_list, field_name, field_type):
"""
Returns a query that matches exact terms with
positional order (i.e. ["this", "thing"] != ["thing", "this"])
and no stem.
If `field_name` is not `None`, restrict to the field.
"""
term_list = [self._... | Returns a query that matches exact terms with
positional order (i.e. ["this", "thing"] != ["thing", "this"])
and no stem.
If `field_name` is not `None`, restrict to the field. | entailment |
def _term_query(self, term, field_name, field_type, stemmed=True):
"""
Constructs a query of a single term.
If `field_name` is not `None`, the term is search on that field only.
If exact is `True`, the search is restricted to boolean matches.
"""
constructor = '{prefix}{... | Constructs a query of a single term.
If `field_name` is not `None`, the term is search on that field only.
If exact is `True`, the search is restricted to boolean matches. | entailment |
def _filter_gte(self, term, field_name, field_type, is_not):
"""
Private method that returns a xapian.Query that searches for any term
that is greater than `term` in a specified `field`.
"""
vrp = XHValueRangeProcessor(self.backend)
pos, begin, end = vrp('%s:%s' % (field_... | Private method that returns a xapian.Query that searches for any term
that is greater than `term` in a specified `field`. | entailment |
def get(company='', company_uri=''):
"""Performs a HTTP GET for a glassdoor page and returns json"""
if not company and not company_uri:
raise Exception("glassdoor.gd.get(company='', company_uri=''): "\
" company or company_uri required")
payload = {}
if not company_u... | Performs a HTTP GET for a glassdoor page and returns json | entailment |
def parse_suggestions(soup):
"""Suggests similar/related companies to query"""
selector_comps = {'class': 'companyData'}
companies = soup.findAll('div', selector_comps)
def is_exact_match(c):
"""Determines if this company suggestion has an [exact match]
html label or whether its name ma... | Suggests similar/related companies to query | entailment |
def parse(soup):
"""Parses the results for a company search and return the results
if is_direct_match. If no company is found, a list of suggestions
are returned as dict. If one such recommendation is found to be an
exact match, re-perform request for this exact match
"""
if is_direct_match(sou... | Parses the results for a company search and return the results
if is_direct_match. If no company is found, a list of suggestions
are returned as dict. If one such recommendation is found to be an
exact match, re-perform request for this exact match | entailment |
def init_app(self, app):
"""
Register this extension with the flask app.
:param app: A flask application
"""
# Save this so we can use it later in the extension
if not hasattr(app, 'extensions'): # pragma: no cover
app.extensions = {}
app.extensions[... | Register this extension with the flask app.
:param app: A flask application | entailment |
def _set_default__configuration_options(app):
"""
Sets the default configuration options used by this extension
"""
app.config.setdefault('JWT_TOKEN_ARGUMENT_NAME', "token") # Name of token argument in GraphQL request resolver
app.config.setdefault('JWT_REFRESH_TOKEN_ARGUMENT_NA... | Sets the default configuration options used by this extension | entailment |
def decode_jwt(encoded_token, secret, algorithm, identity_claim_key,
user_claims_key):
"""
Decodes an encoded JWT
:param encoded_token: The encoded JWT string to decode
:param secret: Secret key used to encode the JWT
:param algorithm: Algorithm used to encode the JWT
:param iden... | Decodes an encoded JWT
:param encoded_token: The encoded JWT string to decode
:param secret: Secret key used to encode the JWT
:param algorithm: Algorithm used to encode the JWT
:param identity_claim_key: expected key that contains the identity
:param user_claims_key: expected key that contains the... | entailment |
def get_jwt_data(token, token_type):
"""
Decodes encoded JWT token by using extension setting and validates token type
:param token: The encoded JWT string to decode
:param token_type: JWT type for type validation (access or refresh)
:return: Dictionary containing contents of the JWT
"""
jw... | Decodes encoded JWT token by using extension setting and validates token type
:param token: The encoded JWT string to decode
:param token_type: JWT type for type validation (access or refresh)
:return: Dictionary containing contents of the JWT | entailment |
def query_jwt_required(fn):
"""
A decorator to protect a query resolver.
If you decorate an resolver with this, it will ensure that the requester
has a valid access token before allowing the resolver to be called. This
does not check the freshness of the access token.
"""
@wraps(fn)
def... | A decorator to protect a query resolver.
If you decorate an resolver with this, it will ensure that the requester
has a valid access token before allowing the resolver to be called. This
does not check the freshness of the access token. | entailment |
def mutation_jwt_required(fn):
"""
A decorator to protect a mutation.
If you decorate a mutation with this, it will ensure that the requester
has a valid access token before allowing the mutation to be called. This
does not check the freshness of the access token.
"""
@wraps(fn)
def wra... | A decorator to protect a mutation.
If you decorate a mutation with this, it will ensure that the requester
has a valid access token before allowing the mutation to be called. This
does not check the freshness of the access token. | entailment |
def mutation_jwt_refresh_token_required(fn):
"""
A decorator to protect a mutation.
If you decorate anmutation with this, it will ensure that the requester
has a valid refresh token before allowing the mutation to be called.
"""
@wraps(fn)
def wrapper(cls, *args, **kwargs):
token = ... | A decorator to protect a mutation.
If you decorate anmutation with this, it will ensure that the requester
has a valid refresh token before allowing the mutation to be called. | entailment |
def _hid_enumerate(vendor_id=0, product_id=0):
"""
Enumerates all the hid devices for VID:PID. Returns a list of `HIDDevice`
objects. If vid is 0, then match any vendor id. Similarly, if pid is 0,
match any product id. If both are zero, enumerate all HID devices.
"""
start = hidapi.hid_enumerat... | Enumerates all the hid devices for VID:PID. Returns a list of `HIDDevice`
objects. If vid is 0, then match any vendor id. Similarly, if pid is 0,
match any product id. If both are zero, enumerate all HID devices. | entailment |
def open(self):
"""
Open the HID device for reading and writing.
"""
if self._is_open:
raise HIDException("Failed to open device: HIDDevice already open")
path = self.path.encode('utf-8')
dev = hidapi.hid_open_path(path)
if dev:
self._is_... | Open the HID device for reading and writing. | entailment |
def close(self):
"""
Closes the hid device
"""
if self._is_open:
self._is_open = False
hidapi.hid_close(self._device) | Closes the hid device | entailment |
def write(self, data, report_id=0):
"""
Writes data to the HID device on its endpoint.
Parameters:
data: data to send on the HID endpoint
report_id: the report ID to use.
Returns:
The number of bytes written including the report ID.
"""
... | Writes data to the HID device on its endpoint.
Parameters:
data: data to send on the HID endpoint
report_id: the report ID to use.
Returns:
The number of bytes written including the report ID. | entailment |
def read(self, size=64, timeout=None):
"""
Read from the hid device on its endpoint.
Parameters:
size: number of bytes to read
timeout: length to wait in milliseconds
Returns:
The HID report read from the device. The first byte in the result
... | Read from the hid device on its endpoint.
Parameters:
size: number of bytes to read
timeout: length to wait in milliseconds
Returns:
The HID report read from the device. The first byte in the result
will be the report ID if used. | entailment |
def is_connected(self):
"""
Checks if the USB device is still connected
"""
if self._is_open:
err = hidapi.hid_read_timeout(self._device, ffi.NULL, 0, 0)
if err == -1:
return False
else:
return True
else:
... | Checks if the USB device is still connected | entailment |
def send_feature_report(self, data, report_id=0x00):
"""
Send a Feature report to a HID device.
Feature reports are sent over the Control endpoint as a Set_Report
transfer.
Parameters:
data The data to send
Returns:
This function returns the ... | Send a Feature report to a HID device.
Feature reports are sent over the Control endpoint as a Set_Report
transfer.
Parameters:
data The data to send
Returns:
This function returns the actual number of bytes written | entailment |
def get_feature_report(self, size, report_id=0x00):
"""
Get a feature report from a HID device.
Feature reports are sent over the Control endpoint as a Get_Report
transfer.
Parameters:
size The number of bytes to read.
report_id The report id to... | Get a feature report from a HID device.
Feature reports are sent over the Control endpoint as a Get_Report
transfer.
Parameters:
size The number of bytes to read.
report_id The report id to read
Returns:
They bytes read from the HID report | entailment |
def get_error(self):
"""
Get an error string from the device
"""
err_str = hidapi.hid_error(self._device)
if err_str == ffi.NULL:
return None
else:
return ffi.string(err_str) | Get an error string from the device | entailment |
def get_indexed_string(self, index):
"""
Get the string with the given index from the device
"""
max_len = 128
str_buf = ffi.new("wchar_t[]", str(bytearray(max_len)))
ret = hidapi.hid_get_indexed_string(self._device, index, str_buf, max_len)
if ret < 0:
... | Get the string with the given index from the device | entailment |
def description(self):
"""
Get a string describing the HID descriptor.
"""
return \
"""HIDDevice:
{} | {:x}:{:x} | {} | {} | {}
release_number: {}
usage_page: {}
usage: {}
interface_number: {}\
""".format(self.path,
self.vendor_id,
self.product_i... | Get a string describing the HID descriptor. | entailment |
def find(self, vid=None, pid=None, serial=None, interface=None, \
path=None, release_number=None, manufacturer=None,
product=None, usage=None, usage_page=None):
"""
Attempts to open a device in this `Enumeration` object. Optional
arguments can be provided to filter the re... | Attempts to open a device in this `Enumeration` object. Optional
arguments can be provided to filter the resulting list based on various
parameters of the HID devices.
Args:
vid: filters by USB Vendor ID
pid: filters by USB Product ID
serial: filters by USB s... | entailment |
def get_tracks(self):
"""
Retrieves all the tracks of the album if they haven't been retrieved yet
:return: List. Tracks of the current album
"""
if not self._track_list:
tracks = itunespy.lookup(id=self.collection_id, entity=itunespy.entities['song'])[1:]
... | Retrieves all the tracks of the album if they haven't been retrieved yet
:return: List. Tracks of the current album | entailment |
def get_album_time(self, round_number=2):
"""
Retrieves all of the track's length and returns the sum of all
:param round_number: Int. Number of decimals to round the sum
:return: Int. Sum of all the track's length
"""
if not self._track_list:
self.get_tracks(... | Retrieves all of the track's length and returns the sum of all
:param round_number: Int. Number of decimals to round the sum
:return: Int. Sum of all the track's length | entailment |
def get_movies(self):
"""
Retrieves all the movies published by the artist
:return: List. Movies published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['movie'])[1:] | Retrieves all the movies published by the artist
:return: List. Movies published by the artist | entailment |
def solarcalcs(self):
""" Solar Calculation
Mutates RSM, BEM, and UCM objects based on following parameters:
UCM # Urban Canopy - Building Energy Model object
BEM # Building Energy Model object
simTime # Simulation time bbject
RSM ... | Solar Calculation
Mutates RSM, BEM, and UCM objects based on following parameters:
UCM # Urban Canopy - Building Energy Model object
BEM # Building Energy Model object
simTime # Simulation time bbject
RSM # Rural Site & Vertical Diffusi... | entailment |
def solarangles (self):
"""
Calculation based on NOAA. Solves for zenith angle, tangent of zenithal angle,
and critical canyon angle based on following parameters:
canAspect # aspect Ratio of canyon
simTime # simulation parameters
RSM.lon ... | Calculation based on NOAA. Solves for zenith angle, tangent of zenithal angle,
and critical canyon angle based on following parameters:
canAspect # aspect Ratio of canyon
simTime # simulation parameters
RSM.lon # longitude (deg)
RSM.lat ... | entailment |
def psychrometrics (Tdb_in, w_in, P):
"""
Modified version of Psychometrics by Tea Zakula
MIT Building Technology Lab
Input: Tdb_in, w_in, P
Output: Tdb, w, phi, h, Tdp, v
where:
Tdb_in = [K] dry bulb temperature
w_in = [kgv/kgda] Humidity Ratio
P = [P] Atmospheric Station Pressure
... | Modified version of Psychometrics by Tea Zakula
MIT Building Technology Lab
Input: Tdb_in, w_in, P
Output: Tdb, w, phi, h, Tdp, v
where:
Tdb_in = [K] dry bulb temperature
w_in = [kgv/kgda] Humidity Ratio
P = [P] Atmospheric Station Pressure
Tdb: [C] dry bulb temperature
w: [kgv/kgd... | entailment |
def search(term, country='US', media='all', entity=None, attribute=None, limit=50):
"""
Returns the result of the search of the specified term in an array of result_item(s)
:param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson.
The method will take ... | Returns the result of the search of the specified term in an array of result_item(s)
:param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson.
The method will take care of spaces so you don't have to.
:param country: String. The two-letter country code for... | entailment |
def lookup(id=None, artist_amg_id=None, upc=None, country='US', media='all', entity=None, attribute=None, limit=50):
"""
Returns the result of the lookup of the specified id, artist_amg_id or upc in an array of result_item(s)
:param id: String. iTunes ID of the artist, album, track, ebook or software
:p... | Returns the result of the lookup of the specified id, artist_amg_id or upc in an array of result_item(s)
:param id: String. iTunes ID of the artist, album, track, ebook or software
:param artist_amg_id: String. All Music Guide ID of the artist
:param upc: String. UPCs/EANs
:param country: String. The tw... | entailment |
def _get_result_list(json):
"""
Analyzes the provided JSON data and returns an array of result_item(s) based on its content
:param json: Raw JSON data to analyze
:return: An array of result_item(s) from the provided JSON data
"""
result_list = []
for item in json:
if 'wrapperType' i... | Analyzes the provided JSON data and returns an array of result_item(s) based on its content
:param json: Raw JSON data to analyze
:return: An array of result_item(s) from the provided JSON data | entailment |
def _url_search_builder(term, country='US', media='all', entity=None, attribute=None, limit=50):
"""
Builds the URL to perform the search based on the provided data
:param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson.
The method will take care of ... | Builds the URL to perform the search based on the provided data
:param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson.
The method will take care of spaces so you don't have to.
:param country: String. The two-letter country code for the store you want t... | entailment |
def _url_lookup_builder(id=None, artist_amg_id=None, upc=None, country='US', media='music', entity=None, attribute=None,
limit=50):
"""
Builds the URL to perform the lookup based on the provided data
:param id: String. iTunes ID of the artist, album, track, ebook or software
:par... | Builds the URL to perform the lookup based on the provided data
:param id: String. iTunes ID of the artist, album, track, ebook or software
:param artist_amg_id: String. All Music Guide ID of the artist
:param upc: String. UPCs/EANs
:param country: String. The two-letter country code for the store you w... | entailment |
def get_albums(self):
"""
Retrieves all the albums by the artist
:return: List. Albums published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['album'])[1:] | Retrieves all the albums by the artist
:return: List. Albums published by the artist | entailment |
def str2fl(x):
"""Recurses through lists and converts lists of string to float
Args:
x: string or list of strings
"""
def helper_to_fl(s_):
""" deals with odd string imports converts to float"""
if s_ == "":
return "null"
elif "," in s_:
s_ = s_.r... | Recurses through lists and converts lists of string to float
Args:
x: string or list of strings | entailment |
def procMat(materials, max_thickness, min_thickness):
""" Processes material layer so that a material with single
layer thickness is divided into two and material layer that is too
thick is subdivided
"""
newmat = []
newthickness = []
k = materials.layerThermalCond
Vhc = material... | Processes material layer so that a material with single
layer thickness is divided into two and material layer that is too
thick is subdivided | entailment |
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longit... | Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT ... | entailment |
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^... | Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic ... | entailment |
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the... | Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there. | entailment |
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_w... | Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total... | entailment |
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc ... | Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
... | entailment |
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999. | Section 6 - HVAC Autosizing (unlimited cooling & heating) | entailment |
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weathe... | Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# ... | entailment |
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] ... | Section 8 - Writing new EPW file | entailment |
def SurfFlux(self,forc,parameter,simTime,humRef,tempRef,windRef,boundCond,intFlux):
""" Calculate net heat flux, and update element layer temperatures
"""
# Calculated per unit area (m^2)
dens = forc.pres/(1000*0.287042*tempRef*(1.+1.607858*humRef)) # air density (kgd m-3)
self.... | Calculate net heat flux, and update element layer temperatures | entailment |
def Conduction(self, dt, flx1, bc, temp2, flx2):
"""
Solve the conductance of heat based on of the element layers.
arg:
flx1 : net heat flux on surface
bc : boundary condition parameter (1 or 2)
temp2 : deep soil temperature (ave of air temperature)
... | Solve the conductance of heat based on of the element layers.
arg:
flx1 : net heat flux on surface
bc : boundary condition parameter (1 or 2)
temp2 : deep soil temperature (ave of air temperature)
flx2 : surface flux (sum of absorbed, emitted, etc.)
... | entailment |
def qsat(self,temp,pres,parameter):
"""
Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep).
"""
gamw = (parameter.cl - parameter.cpv) / parameter.rv
betaw = (parameter.... | Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep). | entailment |
def invert(self,nz,A,C):
"""
Inversion and resolution of a tridiagonal matrix
A X = C
Input:
nz number of layers
a(*,1) lower diagonal (Ai,i-1)
a(*,2) principal diagonal (Ai,i)
a(*,3) upper diagonal (Ai,i+1)
c
Output
... | Inversion and resolution of a tridiagonal matrix
A X = C
Input:
nz number of layers
a(*,1) lower diagonal (Ai,i-1)
a(*,2) principal diagonal (Ai,i)
a(*,3) upper diagonal (Ai,i+1)
c
Output
x results | entailment |
def readDOE(serialize_output=True):
"""
Read csv files of DOE buildings
Sheet 1 = BuildingSummary
Sheet 2 = ZoneSummary
Sheet 3 = LocationSummary
Sheet 4 = Schedules
Note BLD8 & 10 = school
Then make matrix of ref data as nested nested lists [16, 3, 16]:
matrix refDOE = Building ob... | Read csv files of DOE buildings
Sheet 1 = BuildingSummary
Sheet 2 = ZoneSummary
Sheet 3 = LocationSummary
Sheet 4 = Schedules
Note BLD8 & 10 = school
Then make matrix of ref data as nested nested lists [16, 3, 16]:
matrix refDOE = Building objs
matrix Schedule = SchDef objs
matrix ... | entailment |
def readPlist(pathOrFile):
"""Raises NotBinaryPlistException, InvalidPlistException"""
didOpen = False
result = None
if isinstance(pathOrFile, (bytes, unicode)):
pathOrFile = open(pathOrFile, 'rb')
didOpen = True
try:
reader = PlistReader(pathOrFile)
result = reader.p... | Raises NotBinaryPlistException, InvalidPlistException | entailment |
def getSizedInteger(self, data, byteSize, as_number=False):
"""Numbers of 8 bytes are signed integers when they refer to numbers, but unsigned otherwise."""
result = 0
if byteSize == 0:
raise InvalidPlistException("Encountered integer with byte size of 0.")
# 1, 2, and 4 byte... | Numbers of 8 bytes are signed integers when they refer to numbers, but unsigned otherwise. | entailment |
def writeRoot(self, root):
"""
Strategy is:
- write header
- wrap root object so everything is hashable
- compute size of objects which will be written
- need to do this in order to know how large the object refs
will be in the list/dict/set reference lists
... | Strategy is:
- write header
- wrap root object so everything is hashable
- compute size of objects which will be written
- need to do this in order to know how large the object refs
will be in the list/dict/set reference lists
- write objects
- keep object... | entailment |
def writeObjectReference(self, obj, output):
"""Tries to write an object reference, adding it to the references
table. Does not write the actual object bytes or set the reference
position. Returns a tuple of whether the object was a new reference
(True if it was, False if it alr... | Tries to write an object reference, adding it to the references
table. Does not write the actual object bytes or set the reference
position. Returns a tuple of whether the object was a new reference
(True if it was, False if it already was in the reference table)
and the new ... | entailment |
def writeObject(self, obj, output, setReferencePosition=False):
"""Serializes the given object to the output. Returns output.
If setReferencePosition is True, will set the position the
object was written.
"""
def proc_variable_length(format, length):
result = b'... | Serializes the given object to the output. Returns output.
If setReferencePosition is True, will set the position the
object was written. | entailment |
def writeOffsetTable(self, output):
"""Writes all of the object reference offsets."""
all_positions = []
writtenReferences = list(self.writtenReferences.items())
writtenReferences.sort(key=lambda x: x[1])
for obj,order in writtenReferences:
# Porting note: Elsewhere w... | Writes all of the object reference offsets. | entailment |
def intSize(self, obj):
"""Returns the number of bytes necessary to store the given integer."""
# SIGNED
if obj < 0: # Signed integer, always 8 bytes
return 8
# UNSIGNED
elif obj <= 0xFF: # 1 byte
return 1
elif obj <= 0xFFFF: # 2 bytes
... | Returns the number of bytes necessary to store the given integer. | entailment |
def load_z_meso(self,z_meso_path):
""" Open the z_meso.txt file and return heights as list """
self.z_meso = []
z_meso_file_path = os.path.join(z_meso_path, self.Z_MESO_FILE_NAME)
# Check if exists
if not os.path.exists(z_meso_file_path):
raise Exception("z_meso.txt... | Open the z_meso.txt file and return heights as list | entailment |
def urbflux(UCM, UBL, BEM, forc, parameter, simTime, RSM):
"""
Calculate the surface heat fluxes
Output: [UCM,UBL,BEM]
"""
T_can = UCM.canTemp
Cp = parameter.cp
UCM.Q_roof = 0.
sigma = 5.67e-8 # Stephan-Boltzman constant
UCM.roofTemp = 0. # Average urban roof temperatur... | Calculate the surface heat fluxes
Output: [UCM,UBL,BEM] | entailment |
def get_books(self):
"""
Retrieves all the books published by the artist
:return: List. Books published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['ebook'])[1:] | Retrieves all the books published by the artist
:return: List. Books published by the artist | entailment |
def get_tasks(task_id='', completed=True):
""" Get a list of tasks, optionally filtered by task id.
The task_id can be the abbrevated. Example: If a task named 'sleep' is
scaled to 3 in marathon, there will be be 3 tasks starting with 'sleep.'
:param task_id: task ID
:type task_id:... | Get a list of tasks, optionally filtered by task id.
The task_id can be the abbrevated. Example: If a task named 'sleep' is
scaled to 3 in marathon, there will be be 3 tasks starting with 'sleep.'
:param task_id: task ID
:type task_id: str
:param completed: include completed ta... | entailment |
def get_task(task_id, completed=True):
""" Get a task by task id where a task_id is required.
:param task_id: task ID
:type task_id: str
:param completed: include completed tasks?
:type completed: bool
:return: a task
:rtype: obj
"""
tasks = get_tasks(task_i... | Get a task by task id where a task_id is required.
:param task_id: task ID
:type task_id: str
:param completed: include completed tasks?
:type completed: bool
:return: a task
:rtype: obj | entailment |
def task_completed(task_id):
""" Check whether a task has completed.
:param task_id: task ID
:type task_id: str
:return: True if completed, False otherwise
:rtype: bool
"""
tasks = get_tasks(task_id=task_id)
completed_states = ('TASK_FINISHED',
... | Check whether a task has completed.
:param task_id: task ID
:type task_id: str
:return: True if completed, False otherwise
:rtype: bool | entailment |
def task_property_present_predicate(service, task, prop):
""" True if the json_element passed is present for the task specified.
"""
try:
response = get_service_task(service, task)
except Exception as e:
pass
return (response is not None) and (prop in response) | True if the json_element passed is present for the task specified. | entailment |
def wait_for_task(service, task, timeout_sec=120):
"""Waits for a task which was launched to be launched"""
return time_wait(lambda: task_predicate(service, task), timeout_seconds=timeout_sec) | Waits for a task which was launched to be launched | entailment |
def wait_for_task_property(service, task, prop, timeout_sec=120):
"""Waits for a task to have the specified property"""
return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec) | Waits for a task to have the specified property | entailment |
def copy_file(
host,
file_path,
remote_path='.',
username=None,
key_path=None,
action='put'
):
""" Copy a file via SCP, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param fi... | Copy a file via SCP, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param file_path: the local path to the file to be copied
:type file_path: str
:param remote_path: the remote path to copy the file to
:... | entailment |
def copy_file_to_master(
file_path,
remote_path='.',
username=None,
key_path=None
):
""" Copy a file to the Mesos master
"""
return copy_file(shakedown.master_ip(), file_path, remote_path, username, key_path) | Copy a file to the Mesos master | entailment |
def copy_file_to_agent(
host,
file_path,
remote_path='.',
username=None,
key_path=None
):
""" Copy a file to a Mesos agent, proxied through the master
"""
return copy_file(host, file_path, remote_path, username, key_path) | Copy a file to a Mesos agent, proxied through the master | entailment |
def copy_file_from_master(
remote_path,
file_path='.',
username=None,
key_path=None
):
""" Copy a file to the Mesos master
"""
return copy_file(shakedown.master_ip(), file_path, remote_path, username, key_path, 'get') | Copy a file to the Mesos master | entailment |
def copy_file_from_agent(
host,
remote_path,
file_path='.',
username=None,
key_path=None
):
""" Copy a file to a Mesos agent, proxied through the master
"""
return copy_file(host, file_path, remote_path, username, key_path, 'get') | Copy a file to a Mesos agent, proxied through the master | entailment |
def __metadata_helper(json_path):
""" Returns json for specific cluster metadata. Important to realize that
this was introduced in dcos-1.9. Clusters prior to 1.9 and missing metadata
will return None
"""
url = shakedown.dcos_url_path('dcos-metadata/{}'.format(json_path))
try:
... | Returns json for specific cluster metadata. Important to realize that
this was introduced in dcos-1.9. Clusters prior to 1.9 and missing metadata
will return None | entailment |
def _get_resources(rtype='resources'):
""" resource types from state summary include: resources, used_resources
offered_resources, reserved_resources, unreserved_resources
The default is resources.
:param rtype: the type of resources to return
:type rtype: str
:param role: the name of the role... | resource types from state summary include: resources, used_resources
offered_resources, reserved_resources, unreserved_resources
The default is resources.
:param rtype: the type of resources to return
:type rtype: str
:param role: the name of the role if for reserved and if None all reserved
:... | entailment |
def get_reserved_resources(role=None):
""" resource types from state summary include: reserved_resources
:param role: the name of the role if for reserved and if None all reserved
:type role: str
:return: resources(cpu,mem)
:rtype: Resources
"""
rtype = 'reserved_resources'
cpus = 0.0
... | resource types from state summary include: reserved_resources
:param role: the name of the role if for reserved and if None all reserved
:type role: str
:return: resources(cpu,mem)
:rtype: Resources | entailment |
def log_decl_method(func):
"""Decorate do_declartion methods for debug logging."""
from functools import wraps
@wraps(func)
def with_logging(*args, **kwargs):
self = args[0]
decl = args[2]
log(DEBUG, u" {}: {} {}".format(
self.state['current_step'], decl.name,
... | Decorate do_declartion methods for debug logging. | entailment |
def css_to_func(css, flags, css_namespaces, lang):
"""Convert a css selector to an xpath, supporting pseudo elements."""
from cssselect import parse, HTMLTranslator
from cssselect.parser import FunctionalPseudoElement
# FIXME HACK need lessc to support functional-pseudo-selectors instead
# of mark... | Convert a css selector to an xpath, supporting pseudo elements. | entailment |
def append_string(t, string):
"""Append a string to a node, as text or tail of last child."""
node = t.tree
if string:
if len(node) == 0:
if node.text is not None:
node.text += string
else:
node.text = string
else: # Get last child
... | Append a string to a node, as text or tail of last child. | entailment |
def prepend_string(t, string):
"""Prepend a string to a target node as text."""
node = t.tree
if node.text is not None:
node.text += string
else:
node.text = string | Prepend a string to a target node as text. | entailment |
def grouped_insert(t, value):
"""Insert value into the target tree 't' with correct grouping."""
collator = Collator.createInstance(Locale(t.lang) if t.lang else Locale())
if value.tail is not None:
val_prev = value.getprevious()
if val_prev is not None:
val_prev.tail = (val_prev... | Insert value into the target tree 't' with correct grouping. | entailment |
def insert_sort(node, target):
"""Insert node into sorted position in target tree.
Uses sort function and language from target"""
sort = target.sort
lang = target.lang
collator = Collator.createInstance(Locale(lang) if lang else Locale())
for child in target.tree:
if collator.compare(so... | Insert node into sorted position in target tree.
Uses sort function and language from target | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.