Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _get_request(self, auth=None):
''' Return an http request object
auth: Auth data to use
Returns:
A HSRequest object
'''
self.request = HSRequest(auth or self.auth, self.env)
self.request.response_c... | [] |
Please provide a description of the function:def _authenticate(self, email_address=None, password=None, api_key=None, access_token=None, access_token_type=None):
''' Create authentication object to send requests
Args:
email_address (str): Email address of the account to make the req... | [] |
Please provide a description of the function:def _check_required_fields(self, fields=None, either_fields=None):
''' Check the values of the fields
If no value found in `fields`, an exception will be raised.
`either_fields` are the fields that one of them must have a value
Raises:
... | [] |
Please provide a description of the function:def _send_signature_request(self, test_mode=False, client_id=None, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, ... | [] |
Please provide a description of the function:def _send_signature_request_with_template(self, test_mode=False, client_id=None, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=... | [] |
Please provide a description of the function:def _create_unclaimed_draft(self, test_mode=False, client_id=None, is_for_embedded_signing=False, requester_email_address=None, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, requesti... | [] |
Please provide a description of the function:def _add_remove_user_template(self, url, template_id, account_id=None, email_address=None):
''' Add or Remove user from a Template
We use this function for two tasks because they have the same API call
Args:
template_id (str): The ... | [] |
Please provide a description of the function:def _add_remove_team_member(self, url, email_address=None, account_id=None):
''' Add or Remove a team member
We use this function for two different tasks because they have the same
API call
Args:
email_address (str): Email ad... | [] |
Please provide a description of the function:def _create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False):
''' Helper method for creating embedded template d... | [] |
Please provide a description of the function:def _create_embedded_unclaimed_draft_with_template(self, test_mode=False, client_id=None, is_for_embedded_signing=False, template_id=None, template_ids=None, requester_email_address=None, title=None, subject=None, message=None, signers=None, ccs=None, signing_redirect_url=No... | [] |
Please provide a description of the function:def get_file(self, url, path_or_file=None, headers=None, filename=None):
''' Get a file from a url and save it as `filename`
Args:
url (str): URL to send the request to
path_or_file (str or file): A writable File-like object or a pat... | [] |
Please provide a description of the function:def get(self, url, headers=None, parameters=None, get_json=True):
''' Send a GET request with custome headers and parameters
Args:
url (str): URL to send the request to
headers (str, optional): custom headers
parameters (s... | [] |
Please provide a description of the function:def post(self, url, data=None, files=None, headers=None, get_json=True):
''' Make POST request to a url
Args:
url (str): URL to send the request to
data (dict, optional): Data to send
files (dict, optional): Files to send ... | [] |
Please provide a description of the function:def _get_json_response(self, resp):
''' Parse a JSON response '''
if resp is not None and resp.text is not None:
try:
text = resp.text.strip('\n')
if len(text) > 0:
return json.loads(text)
... | [] |
Please provide a description of the function:def _process_json_response(self, response):
''' Process a given response '''
json_response = self._get_json_response(response)
if self.response_callback is not None:
json_response = self.response_callback(json_response)
... | [] |
Please provide a description of the function:def _check_error(self, response, json_response=None):
''' Check for HTTP error code from the response, raise exception if there's any
Args:
response (object): Object returned by requests' `get` and `post`
methods
json... | [] |
Please provide a description of the function:def _check_warnings(self, json_response):
''' Extract warnings from the response to make them accessible
Args:
json_response (dict): JSON response
'''
self.warnings = None
if json_response:
self.warni... | [] |
Please provide a description of the function:def from_response(self, response_data):
''' Builds a new HSAccessTokenAuth straight from response data
Args:
response_data (dict): Response data to use
Returns:
A HSAccessTokenAuth objet
'''
return HSAccessT... | [] |
Please provide a description of the function:def find_response_component(self, api_id=None, signature_id=None):
''' Find one or many repsonse components.
Args:
api_id (str): Api id associated with the component(s) to be retrieved.
signature_id (str): ... | [] |
Please provide a description of the function:def find_signature(self, signature_id=None, signer_email_address=None):
''' Return a signature for the given parameters
Args:
signature_id (str): Id of the signature to retrieve.
signer_email_address (str): ... | [] |
Please provide a description of the function:def _uncamelize(self, s):
''' Convert a camel-cased string to using underscores '''
res = ''
if s:
for i in range(len(s)):
if i > 0 and s[i].lower() != s[i]:
res += '_'
res += s[i].lower... | [] |
Please provide a description of the function:def format_file_params(files):
'''
Utility method for formatting file parameters for transmission
'''
files_payload = {}
if files:
for idx, filename in enumerate(files):
files_payload["file[" + str(idx) ... | [] |
Please provide a description of the function:def format_file_url_params(file_urls):
'''
Utility method for formatting file URL parameters for transmission
'''
file_urls_payload = {}
if file_urls:
for idx, fileurl in enumerate(file_urls):
file_urls_... | [] |
Please provide a description of the function:def format_param_list(listed_params, output_name):
'''
Utility method for formatting lists of parameters for api consumption
Useful for email address lists, etc
Args:
listed_params (list of values) - the list to for... | [] |
Please provide a description of the function:def format_dict_list(list_of_dicts, output_name, key=None):
'''
Utility method for formatting lists of dictionaries for api consumption.
Takes something like [{name: val1, email: val2},{name: val1, email: val2}] for signers
and out... | [] |
Please provide a description of the function:def format_single_dict(dictionary, output_name):
'''
Currently used for metadata fields
'''
output_payload = {}
if dictionary:
for (k, v) in dictionary.items():
output_payload[output_name + '[' + k + ']'... | [] |
Please provide a description of the function:def format_custom_fields(list_of_custom_fields):
'''
Custom fields formatting for submission
'''
output_payload = {}
if list_of_custom_fields:
# custom_field: {"name": value}
for custom_field in list_of_cust... | [] |
Please provide a description of the function:def set_logscale(self,t=True):
if(t == self.get_logscale()):
return
else:
if(t):
self.__image = np.log10(self.__image+1)
self.__logscale_flag = True;
else:
self.__ima... | [
"\n - set_logscale(): If M is the matrix of the image, it defines the image M as log10(M+1).\n "
] |
Please provide a description of the function:def histogram(self,axis=None, **kargs):
if(axis == None):
axis = plt.gca()
axis.hist(self.__image.ravel(), **kargs) | [
"\n - histogram(axis=None, **kargs): It computes and shows the histogram of the image. This is \n usefull for choosing a proper scale to the output, or for clipping some values. If \n axis is None, it selects the current axis to plot the histogram.\n \n Keyword arguments:\n ... |
Please provide a description of the function:def save(self,outputfile,**kargs):
plt.imsave(outputfile, self.__image, **kargs) | [
"\n - Save the image in some common image formats. It uses the pyplot.save \n method. \n outputfile is a string containing a path to a filename, \n of a Python file-like object. If *format* is *None* and\n *fname* is a string, the output format is deduced from\n the extens... |
Please provide a description of the function:def set_autocamera(self,mode='density'):
self.Camera.set_autocamera(self._Particles,mode=mode)
self._camera_params = self.Camera.get_params()
self._x, self._y, self._hsml, self._kview = self.__compute_scene()
self._m = self._Particles... | [
"\n - set_autocamera(mode='density'): By default, Scene defines its \n own Camera. However, there is no a general way for doing so. Scene \n uses a density criterion for getting the point of view. If this is \n not a good option for your problem, you can choose among:\n |'minmax'|... |
Please provide a description of the function:def get_scene(self):
return self._x, self._y, self._hsml, self._m, self._kview | [
"\n - get_scene(): It return the x and y position, the smoothing length \n of the particles and the index of the particles that are active in \n the scene. In principle this is an internal function and you don't \n need this data. \n "
] |
Please provide a description of the function:def update_camera(self,**kargs):
self.Camera.set_params(**kargs)
self._x, self._y, self._hsml, self._kview = self.__compute_scene()
self._m = self._Particles._mass[self._kview] | [
"\n - update_camera(**kwarg): By using this method you can define all \n the new paramenters of the camera. Read the available **kwarg in \n the sphviewer.Camera documentation. \n "
] |
Please provide a description of the function:def plot(self,axis=None,**kargs):
if(axis == None):
axis = plt.gca()
axis.plot(self.__x, self.__y, 'k.', **kargs) | [
"\n - plot(axis=None, **kwarg): Finally, sphviewer.Scene class has its own plotting method. \n It shows the scene as seen by the camera. It is to say, it plots the particles according\n to their aparent coordinates; axis makes a reference to an existing axis. In case axis is None,\n the ... |
Please provide a description of the function:def plot(self,plane,axis=None,**kargs):
if(axis == None):
axis = plt.gca()
if(plane == 'xy'):
axis.plot(self._pos[:,0], self._pos[:,0], 'k.', **kargs)
elif(plane == 'xz'):
axis.plot(self._pos[:,1], self._po... | [
"\n Use this method to plot the set of particles stored by the Particles class.\n In order to plot the distribution of Particles, a *plane* parameter must be given.\n \"plane\" is one of the available orthogonal projections of the particles: \n |'xy'|'xz'|'yz'|. If there is multiple axe... |
Please provide a description of the function:def __det_hsml_old(self, pos, nb):
manager = Manager()
out_hsml = manager.Queue()
size = multiprocessing.cpu_count()
if self.__verbose:
print('Building a KDTree...')
tree = self.__make_kdtree(pos)
inde... | [
"\n Use this function to find the smoothing lengths of the particles.\n hsml = det_hsml(pos, nb)\n "
] |
Please provide a description of the function:def read(fname, fail_silently=False):
try:
filepath = os.path.join(os.path.dirname(__file__), fname)
with io.open(filepath, 'rt', encoding='utf8') as f:
return f.read()
except:
if not fail_silently:... | [
"\n Read the content of the given file. The path is evaluated from the\n directory containing this file.\n "
] |
Please provide a description of the function:def pass_verbosity(f):
def new_func(*args, **kwargs):
kwargs['verbosity'] = click.get_current_context().verbosity
return f(*args, **kwargs)
return update_wrapper(new_func, f) | [
"\n Marks a callback as wanting to receive the verbosity as a keyword argument.\n "
] |
Please provide a description of the function:def run_from_argv(self, argv):
try:
return self.main(args=argv[2:], standalone_mode=False)
except click.ClickException as e:
if getattr(e.ctx, 'traceback', False):
raise
e.show()
sys.exi... | [
"\n Called when run from the command line.\n "
] |
Please provide a description of the function:def execute(self, *args, **kwargs):
# Remove internal Django command handling machinery
kwargs.pop('skip_checks', None)
parent_ctx = click.get_current_context(silent=True)
with self.make_context('', list(args), parent=parent_ctx) as c... | [
"\n Called when run through `call_command`. `args` are passed through,\n while `kwargs` is the __dict__ of the return value of\n `self.create_parser('', name)` updated with the kwargs passed to\n `call_command`.\n "
] |
Please provide a description of the function:def encrypt(data, key):
'''encrypt the data with the key'''
data = __tobytes(data)
data_len = len(data)
data = ffi.from_buffer(data)
key = ffi.from_buffer(__tobytes(key))
out_len = ffi.new('size_t *')
result = lib.xxtea_encrypt(data, data_len, key... | [] |
Please provide a description of the function:def decrypt(data, key):
'''decrypt the data with the key'''
data_len = len(data)
data = ffi.from_buffer(data)
key = ffi.from_buffer(__tobytes(key))
out_len = ffi.new('size_t *')
result = lib.xxtea_decrypt(data, data_len, key, out_len)
ret = ffi.bu... | [] |
Please provide a description of the function:def flaskrun(app, default_host="127.0.0.1", default_port="8000"):
# Set up the command-line options
parser = optparse.OptionParser()
parser.add_option(
"-H",
"--host",
help="Hostname of the Flask app " + "[default %s]" % default_host... | [
"\n Takes a flask.Flask instance and runs it. Parses\n command-line flags to configure the app.\n "
] |
Please provide a description of the function:def get_randomized_guid_sample(self, item_count):
dataset = self.get_whitelist()
random.shuffle(dataset)
return dataset[:item_count] | [
" Fetch a subset of randomzied GUIDs from the whitelist "
] |
Please provide a description of the function:def can_recommend(self, client_data, extra_data={}):
self.logger.info("Curated can_recommend: {}".format(True))
return True | [
"The Curated recommender will always be able to recommend\n something"
] |
Please provide a description of the function:def recommend(self, client_data, limit, extra_data={}):
guids = self._curated_wl.get_randomized_guid_sample(limit)
results = [(guid, 1.0) for guid in guids]
log_data = (client_data["client_id"], str(guids))
self.logger.info(
... | [
"\n Curated recommendations are just random selections\n "
] |
Please provide a description of the function:def can_recommend(self, client_data, extra_data={}):
ensemble_recommend = self._ensemble_recommender.can_recommend(
client_data, extra_data
)
curated_recommend = self._curated_recommender.can_recommend(
client_data, ex... | [
"The ensemble recommender is always going to be\n available if at least one recommender is available"
] |
Please provide a description of the function:def recommend(self, client_data, limit, extra_data={}):
preinstalled_addon_ids = client_data.get("installed_addons", [])
# Compute an extended limit by adding the length of
# the list of any preinstalled addons.
extended_limit = lim... | [
"\n Hybrid recommendations simply select half recommendations from\n the ensemble recommender, and half from the curated one.\n\n Duplicate recommendations are accomodated by rank ordering\n by weight.\n "
] |
Please provide a description of the function:def can_recommend(self, client_data, extra_data={}):
result = sum(
[
self._recommender_map[rkey].can_recommend(client_data)
for rkey in self.RECOMMENDER_KEYS
]
)
self.logger.info("Ensemb... | [
"The ensemble recommender is always going to be\n available if at least one recommender is available"
] |
Please provide a description of the function:def _recommend(self, client_data, limit, extra_data={}):
self.logger.info("Ensemble recommend invoked")
preinstalled_addon_ids = client_data.get("installed_addons", [])
# Compute an extended limit by adding the length of
# the list o... | [
"\n Ensemble recommendations are aggregated from individual\n recommenders. The ensemble recommender applies a weight to\n the recommendation outputs of each recommender to reorder the\n recommendations to be a better fit.\n\n The intuitive understanding is that the total space o... |
Please provide a description of the function:def synchronized(wrapped):
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
self = args[0]
with self._lock:
return wrapped(*args, **kwargs)
return wrapper | [
" Synchronization decorator. "
] |
Please provide a description of the function:def get(self, transform=None):
if not self.has_expired() and self._cached_copy is not None:
return self._cached_copy, False
return self._refresh_cache(transform), True | [
"\n Return the JSON defined at the S3 location in the constructor.\n\n The get method will reload the S3 object after the TTL has\n expired.\n Fetch the JSON object from cache or S3 if necessary\n "
] |
Please provide a description of the function:def hashed_download(url, temp, digest):
# Based on pip 1.4.1's URLOpener but with cert verification removed
def opener():
opener = build_opener(HTTPSHandler())
# Strip out HTTPHandler to prevent MITM spoof:
for handler in opener.handlers:... | [
"Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``,\n and return its path."
] |
Please provide a description of the function:def get_lr(self, score):
# Find the index of the closest value that was precomputed in lr_curves
# This will significantly speed up |get_lr|.
# The lr_curves_cache is a list of scalar distance
# measurements
lr_curves_cache =... | [
"Compute a :float: likelihood ratio from a provided similarity score when compared\n to two probability density functions which are computed and pre-loaded during init.\n\n The numerator indicates the probability density that a particular similarity score\n corresponds to a 'good' addon donor, ... |
Please provide a description of the function:def get_similar_donors(self, client_data):
# Compute the distance between self and any comparable client.
distances = self.compute_clients_dist(client_data)
# Compute the LR based on precomputed distributions that relate the score
# ... | [
"Computes a set of :float: similarity scores between a client and a set of candidate\n donors for which comparable variables have been measured.\n\n A custom similarity metric is defined in this function that combines the Hamming distance\n for categorical variables with the Canberra distance f... |
Please provide a description of the function:def recommend(self, client_id, limit, extra_data={}):
if client_id in TEST_CLIENT_IDS:
data = self._whitelist_data.get()[0]
random.shuffle(data)
samples = data[:limit]
self.logger.info("Test ID detected [{}]".... | [
"Return recommendations for the given client.\n\n The recommendation logic will go through each recommender and\n pick the first one that \"can_recommend\".\n\n :param client_id: the client unique id.\n :param limit: the maximum number of recommendations to return.\n :param extra_... |
Please provide a description of the function:def get_client_profile(self, client_id):
try:
response = self._table.get_item(Key={'client_id': client_id})
compressed_bytes = response['Item']['json_payload'].value
json_byte_data = zlib.decompress(compressed_bytes)
... | [
"This fetches a single client record out of DynamoDB\n "
] |
Please provide a description of the function:def clean_promoted_guids(raw_promoted_guids):
valid = True
for row in raw_promoted_guids:
if len(row) != 2:
valid = False
break
if not (
(isinstance(row[0], str) or isinstance(row[0], unicode))
an... | [
" Verify that the promoted GUIDs are formatted correctly,\n otherwise strip it down into an empty list.\n "
] |
Please provide a description of the function:def configure_plugin(app): # noqa: C901
@app.route(
"/v1/api/client_has_addon/<hashed_client_id>/<addon_id>/", methods=["GET"]
)
def client_has_addon(hashed_client_id, addon_id):
# Use the module global PROXY_MANAGER
global PROXY_MA... | [
"\n This is a factory function that configures all the routes for\n flask given a particular library.\n ",
"Return a list of recommendations provided a telemetry client_id.",
"\n This setter is primarily so that we can instrument the\n cached RecommendationManager implementation u... |
Please provide a description of the function:def login(self):
if self.__logged_in:
return
login = {'userId': self.__username, 'userPassword': self.__password}
header = BASE_HEADERS.copy()
request = requests.post(BASE_URL + 'login',
dat... | [
"Login to Tahoma API."
] |
Please provide a description of the function:def get_user(self):
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
request = requests.get(BASE_URL + 'getEndUser',
headers=header,
timeout=10)
if request.s... | [
"Get the user informations from the server.\n\n :return: a dict with all the informations\n :rtype: dict\n\n raises ValueError in case of protocol issues\n\n :Example:\n\n >>> \"creationTime\": <time>,\n >>> \"lastUpdateTime\": <time>,\n >>> \"userId\": \"<email for ... |
Please provide a description of the function:def _get_setup(self, result):
self.__devices = {}
if ('setup' not in result.keys() or
'devices' not in result['setup'].keys()):
raise Exception(
"Did not find device definition.")
for device_data ... | [
"Internal method which process the results from the server."
] |
Please provide a description of the function:def apply_actions(self, name_of_action, actions):
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
actions_serialized = []
for action in actions:
actions_serialized.append(action.serialize())
data =... | [
"Start to execute an action or a group of actions.\n\n This method takes a bunch of actions and runs them on your\n Tahoma box.\n\n :param name_of_action: the label/name for the action\n :param actions: an array of Action objects\n :return: the execution identifier **************... |
Please provide a description of the function:def get_events(self):
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
request = requests.post(BASE_URL + 'getEvents',
headers=header,
timeout=10)
if reque... | [
"Return a set of events.\n\n Which have been occured since the last call of this method.\n\n This method should be called regulary to get all occuring\n Events. There are three different Event types/classes\n which can be returned:\n\n - DeviceStateChangedEvent, if any device chan... |
Please provide a description of the function:def _get_events(self, result):
events = []
for event_data in result:
event = Event.factory(event_data)
if event is not None:
events.append(event)
if isinstance(event, DeviceStateChangedEvent)... | [
"\"Internal method for being able to run unit tests."
] |
Please provide a description of the function:def get_current_executions(self):
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
request = requests.get(
BASE_URL +
'getCurrentExecutions',
headers=header,
timeout=10)
i... | [
"Get all current running executions.\n\n :return: Returns a set of running Executions or empty list.\n :rtype: list\n\n raises ValueError in case of protocol issues\n\n :Seealso:\n\n - apply_actions\n - launch_action_group\n - get_history\n "
] |
Please provide a description of the function:def get_action_groups(self):
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
request = requests.get(BASE_URL + "getActionGroups",
headers=header,
timeout=10)
... | [
"Get all Action Groups.\n\n :return: List of Action Groups\n "
] |
Please provide a description of the function:def launch_action_group(self, action_id):
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
request = requests.get(
BASE_URL + 'launchActionGroup?oid=' +
action_id,
headers=header,
... | [
"Start action group."
] |
Please provide a description of the function:def get_states(self, devices):
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
json_data = self._create_get_state_request(devices)
request = requests.post(
BASE_URL + 'getStates',
headers=header... | [
"Get States of Devices."
] |
Please provide a description of the function:def _create_get_state_request(self, given_devices):
dev_list = []
if isinstance(given_devices, list):
devices = given_devices
else:
devices = []
for dev_name, item in self.__devices.items():
... | [
"Create state request."
] |
Please provide a description of the function:def _get_states(self, result):
if 'devices' not in result.keys():
return
for device_states in result['devices']:
device = self.__devices[device_states['deviceURL']]
try:
device.set_active_states(de... | [
"Get states of devices."
] |
Please provide a description of the function:def refresh_all_states(self):
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
request = requests.get(
BASE_URL + "refreshAllStates", headers=header, timeout=10)
if request.status_code != 200:
se... | [
"Update all states."
] |
Please provide a description of the function:def set_active_state(self, name, value):
if name not in self.__active_states.keys():
raise ValueError("Can not set unknown state '" + name + "'")
if (isinstance(self.__active_states[name], int) and
isinstance(value, str))... | [
"Set active state."
] |
Please provide a description of the function:def add_command(self, cmd_name, *args):
self.__commands.append(Command(cmd_name, args)) | [
"Add command to action."
] |
Please provide a description of the function:def serialize(self):
commands = []
for cmd in self.commands:
commands.append(cmd.serialize())
out = {'commands': commands, 'deviceURL': self.__device_url}
return out | [
"Serialize action."
] |
Please provide a description of the function:def factory(data):
if data['name'] is "DeviceStateChangedEvent":
return DeviceStateChangedEvent(data)
elif data['name'] is "ExecutionStateChangedEvent":
return ExecutionStateChangedEvent(data)
elif data['name'] is "Com... | [
"Tahoma Event factory."
] |
Please provide a description of the function:def parse(date, dayfirst=True):
'''Parse a `date` into a `FlexiDate`.
@param date: the date to parse - may be a string, datetime.date,
datetime.datetime or FlexiDate.
TODO: support for quarters e.g. Q4 1980 or 1954 Q3
TODO: support latin stuff like M.DC... | [] |
Please provide a description of the function:def isoformat(self, strict=False):
'''Return date in isoformat (same as __str__ but without qualifier).
WARNING: does not replace '?' in dates unless strict=True.
'''
out = self.year
# what do we do when no year ...
for val in... | [] |
Please provide a description of the function:def from_str(self, instr):
'''Undo affect of __str__'''
if not instr:
return FlexiDate()
out = self.our_re.match(instr)
if out is None: # no match TODO: raise Exception?
return None
else:
return Fl... | [] |
Please provide a description of the function:def as_float(self):
'''Get as a float (year being the integer part).
Replace '?' in year with 9 so as to be conservative (e.g. 19?? becomes
1999) and elsewhere (month, day) with 0
@return: float.
'''
if not self.year:
... | [] |
Please provide a description of the function:def as_datetime(self):
'''Get as python datetime.datetime.
Require year to be a valid datetime year. Default month and day to 1 if
do not exist.
@return: datetime.datetime object.
'''
year = int(self.year)
month = int... | [] |
Please provide a description of the function:def parse(self, date, **kwargs):
'''
:param **kwargs: any kwargs accepted by dateutil.parse function.
'''
qualifiers = []
if dateutil_parser is None:
return None
date = orig_date = date.strip()
# various no... | [] |
Please provide a description of the function:def md5sum( string ):
h = hashlib.new( 'md5' )
h.update( string.encode( 'utf-8' ) )
return h.hexdigest() | [
"\n Generate the md5 checksum for a string\n\n Args:\n string (Str): The string to be checksummed.\n\n Returns:\n (Str): The hex checksum.\n "
] |
Please provide a description of the function:def file_md5( filename ):
with zopen( filename, 'r' ) as f:
file_string = f.read()
try: # attempt to decode byte object
file_string = file_string.decode()
except AttributeError:
pass
return( md5sum( file_string ) ) | [
"\n Generate the md5 checksum for a file\n\n Args:\n filename (Str): The file to be checksummed.\n\n Returns:\n (Str): The hex checksum\n\n Notes:\n If the file is gzipped, the md5 checksum returned is\n for the uncompressed ASCII file.\n "
] |
Please provide a description of the function:def match_filename( filename ):
f = next( ( '{}{}'.format( filename, extension ) for extension in [ '', '.gz' ]
if Path( '{}{}'.format( filename, extension ) ).is_file() ), None )
return f | [
"\n Checks whether a file exists, either as named, or as a a gzippped file (filename.gz)\n\n Args:\n (Str): The root filename.\n\n Returns:\n (Str|None): if the file exists (either as the root filename, or gzipped), the return\n value will be the actual filename. If no matching fil... |
Please provide a description of the function:def validate_checksum( filename, md5sum ):
filename = match_filename( filename )
md5_hash = file_md5( filename=filename )
if md5_hash != md5sum:
raise ValueError('md5 checksums are inconsistent: {}'.format( filename )) | [
"\n Compares the md5 checksum of a file with an expected value.\n If the calculated and expected checksum values are not equal, \n ValueError is raised.\n If the filename `foo` is not found, will try to read a gzipped file named\n `foo.gz`. In this case, the checksum is calculated for the unzipped fi... |
Please provide a description of the function:def to_matrix( xx, yy, zz, xy, yz, xz ):
matrix = np.array( [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]] )
return matrix | [
"\n Convert a list of matrix components to a symmetric 3x3 matrix.\n Inputs should be in the order xx, yy, zz, xy, yz, xz.\n\n Args:\n xx (float): xx component of the matrix.\n yy (float): yy component of the matrix.\n zz (float): zz component of the matrix.\n xy (float): xy com... |
Please provide a description of the function:def absorption_coefficient( dielectric ):
energies_in_eV = np.array( dielectric[0] )
real_dielectric = parse_dielectric_data( dielectric[1] )
imag_dielectric = parse_dielectric_data( dielectric[2] )
epsilon_1 = np.mean( real_dielectric, axis=1 )
epsi... | [
"\n Calculate the optical absorption coefficient from an input set of\n pymatgen vasprun dielectric constant data.\n\n Args:\n dielectric (list): A list containing the dielectric response function\n in the pymatgen vasprun format.\n\n | element 0: ... |
Please provide a description of the function:def murnaghan( vol, e0, b0, bp, v0 ):
energy = e0 + b0 * vol / bp * (((v0 / vol)**bp) / (bp - 1) + 1) - v0 * b0 / (bp - 1.0)
return energy | [
"\n Calculate the energy as a function of volume, using the Murnaghan equation of state\n [Murnaghan, Proc. Nat. Acad. Sci. 30, 244 (1944)]\n https://en.wikipedia.org/wiki/Murnaghan_equation_of_state\n cf. Fu and Ho, Phys. Rev. B 28, 5480 (1983).\n\n Args:\n vol (float): this volume.\n ... |
Please provide a description of the function:def add_dr( self, dr ):
this_bin = int( dr / self.dr )
if this_bin > self.number_of_bins:
raise IndexError( 'dr is larger than rdf max_r' )
self.data[ this_bin ] += 1 | [
"\n Add an observed interatomic distance to the g(r) data at dr.\n\n Args:\n dr (Float): the interatomic distance, dr.\n\n Returns:\n None\n "
] |
Please provide a description of the function:def dr( self, atom1, atom2 ):
return self.cell.dr( atom1.r, atom2.r ) | [
"\n Calculate the distance between two atoms.\n\n Args:\n atom1 (vasppy.Atom): Atom 1.\n atom2 (vasppy.Atom): Atom 2.\n\n Returns:\n (float): The distance between Atom 1 and Atom 2.\n "
] |
Please provide a description of the function:def area_of_a_triangle_in_cartesian_space( a, b, c ):
return 0.5 * np.linalg.norm( np.cross( b-a, c-a ) ) | [
"\n Returns the area of a triangle defined by three points in Cartesian space.\n\n Args:\n a (np.array): Cartesian coordinates of point A.\n b (np.array): Cartesian coordinates of point B.\n c (np.array): Cartesian coordinates of point C.\n\n Returns:\n (float): the area of the ... |
Please provide a description of the function:def points_are_in_a_straight_line( points, tolerance=1e-7 ):
a = points[0]
b = points[1]
for c in points[2:]:
if area_of_a_triangle_in_cartesian_space( a, b, c ) > tolerance:
return False
return True | [
"\n Check whether a set of points fall on a straight line.\n Calculates the areas of triangles formed by triplets of the points.\n Returns False is any of these areas are larger than the tolerance.\n\n Args:\n points (list(np.array)): list of Cartesian coordinates for each point.\n toleran... |
Please provide a description of the function:def two_point_effective_mass( cartesian_k_points, eigenvalues ):
assert( cartesian_k_points.shape[0] == 2 )
assert( eigenvalues.size == 2 )
dk = cartesian_k_points[ 1 ] - cartesian_k_points[ 0 ]
mod_dk = np.sqrt( np.dot( dk, dk ) )
delta_e = ( eigenv... | [
"\n Calculate the effective mass given eigenvalues at two k-points.\n Reimplemented from Aron Walsh's original effective mass Fortran code.\n\n Args:\n cartesian_k_points (np.array): 2D numpy array containing the k-points in (reciprocal) Cartesian coordinates.\n eigenvalues (np.array): ... |
Please provide a description of the function:def least_squares_effective_mass( cartesian_k_points, eigenvalues ):
if not points_are_in_a_straight_line( cartesian_k_points ):
raise ValueError( 'k-points are not collinear' )
dk = cartesian_k_points - cartesian_k_points[0]
mod_dk = np.linalg.norm(... | [
"\n Calculate the effective mass using a least squares quadratic fit.\n\n Args:\n cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points\n eigenvalues (np.array): Energy eigenvalues at each k-point to be used in the fit.\n\n Returns:\n (float): The fitt... |
Please provide a description of the function:def read_from_file( self, filename, negative_occupancies='warn' ):
valid_negative_occupancies = [ 'warn', 'raise', 'ignore', 'zero' ]
if negative_occupancies not in valid_negative_occupancies:
raise ValueError( '"{}" is not a valid value ... | [
"\n Reads the projected wavefunction character of each band from a VASP PROCAR file.\n\n Args:\n filename (str): Filename of the PROCAR file.\n negative_occupancies (:obj:Str, optional): Sets the behaviour for handling\n negative occupancies. Default is `warn`. \n\... |
Please provide a description of the function:def stoichiometry( self ):
return Counter( { label: number for label, number in zip( self.atoms, self.atom_numbers ) } ) | [
"\n Stoichiometry for this POSCAR, as a Counter.\n e.g. AB_2O_4 -> Counter( { 'A': 1, 'B': 2, O: 4 } )\n \n Args:\n None\n\n Returns:\n None\n "
] |
Please provide a description of the function:def load_vasp_summary( filename ):
with open( filename, 'r' ) as stream:
docs = yaml.load_all( stream, Loader=yaml.SafeLoader )
data = { d['title']: d for d in docs }
return data | [
"\n Reads a `vasp_summary.yaml` format YAML file and returns\n a dictionary of dictionaries. Each YAML document in the file\n corresponds to one sub-dictionary, with the corresponding\n top-level key given by the `title` value.\n\n Example:\n The file:\n \n ---\n title... |
Please provide a description of the function:def potcar_spec( filename ):
p_spec = {}
with open( filename, 'r' ) as f:
potcars = re.split('(End of Dataset\n)', f.read() )
potcar_md5sums = [ md5sum( ''.join( pair ) ) for pair in zip( potcars[::2], potcars[1:-1:2] ) ]
for this_md5sum in potca... | [
"\n Returns a dictionary specifying the pseudopotentials contained in a POTCAR file.\n\n Args:\n filename (Str): The name of the POTCAR file to process.\n\n Returns:\n (Dict): A dictionary of pseudopotential filename: dataset pairs, e.g.\n { 'Fe_pv': 'PBE_54', 'O', 'PBE_54' }\n... |
Please provide a description of the function:def find_vasp_calculations():
dir_list = [ './' + re.sub( r'vasprun\.xml', '', path ) for path in glob.iglob( '**/vasprun.xml', recursive=True ) ]
gz_dir_list = [ './' + re.sub( r'vasprun\.xml\.gz', '', path ) for path in glob.iglob( '**/vasprun.xml.gz', recursi... | [
"\n Returns a list of all subdirectories that contain either a vasprun.xml file\n or a compressed vasprun.xml.gz file.\n\n Args:\n None\n\n Returns:\n (List): list of all VASP calculation subdirectories.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.