INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Update the IP info. Args: since_days (int): if checked less than this number of days ago, don't check again (default to 10 days). save (bool): whether to save anyway or not. force (bool): whether to update ip_info to last checked one. Returns: ...
def update_ip_info(self, since_days=10, save=False, force=False): """ Update the IP info. Args: since_days (int): if checked less than this number of days ago, don't check again (default to 10 days). save (bool): whether to save anyway or not. ...
Start a thread to continuously read log files and append lines in DB. Work in progress. Currently the thread doesn't append anything, it only print the information parsed from each line read. Returns: thread: the started thread.
def start_daemon(): """ Start a thread to continuously read log files and append lines in DB. Work in progress. Currently the thread doesn't append anything, it only print the information parsed from each line read. Returns: thread: the started thread. """ ...
Construct a ChemKED instance directly from a ReSpecTh file. Arguments: filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported file_author (`str`, optional): File author to be added to the list generated from the XML file file_author_...
def from_respecth(cls, filename_xml, file_author='', file_author_orcid=''): """Construct a ChemKED instance directly from a ReSpecTh file. Arguments: filename_xml (`str`): Filename of the ReSpecTh-formatted XML file to be imported file_author (`str`, optional): File author to be...
Validate the parsed YAML file for adherance to the ChemKED format. Arguments: properties (`dict`): Dictionary created from the parsed YAML file Raises: `ValueError`: If the YAML file cannot be validated, a `ValueError` is raised whose string contains the errors ...
def validate_yaml(self, properties): """Validate the parsed YAML file for adherance to the ChemKED format. Arguments: properties (`dict`): Dictionary created from the parsed YAML file Raises: `ValueError`: If the YAML file cannot be validated, a `ValueError` is raised w...
Get a Pandas DataFrame of the datapoints in this instance. Arguments: output_columns (`list`, optional): List of strings specifying the columns to include in the output DataFrame. The default is `None`, which outputs all of the columns. Options include (not case sens...
def get_dataframe(self, output_columns=None): """Get a Pandas DataFrame of the datapoints in this instance. Arguments: output_columns (`list`, optional): List of strings specifying the columns to include in the output DataFrame. The default is `None`, which outputs all of th...
Write new ChemKED YAML file based on object. Arguments: filename (`str`): Filename for target YAML file overwrite (`bool`, optional): Whether to overwrite file with given name if present. Must be supplied as a keyword-argument. Raises: `NameError`: I...
def write_file(self, filename, *, overwrite=False): """Write new ChemKED YAML file based on object. Arguments: filename (`str`): Filename for target YAML file overwrite (`bool`, optional): Whether to overwrite file with given name if present. Must be supplied as ...
Convert ChemKED record to ReSpecTh XML file. This converter uses common information in a ChemKED file to generate a ReSpecTh XML file. Note that some information may be lost, as ChemKED stores some additional attributes. Arguments: filename (`str`): Filename for output ReSp...
def convert_to_ReSpecTh(self, filename): """Convert ChemKED record to ReSpecTh XML file. This converter uses common information in a ChemKED file to generate a ReSpecTh XML file. Note that some information may be lost, as ChemKED stores some additional attributes. Arguments: ...
Process the uncertainty information from a given quantity and return it
def process_quantity(self, properties): """Process the uncertainty information from a given quantity and return it """ quant = Q_(properties[0]) if len(properties) > 1: unc = properties[1] uncertainty = unc.get('uncertainty', False) upper_uncertainty =...
Get the composition in a string format suitable for input to Cantera. Returns a formatted string no matter the type of composition. As such, this method is not recommended for end users; instead, prefer the `get_cantera_mole_fraction` or `get_cantera_mass_fraction` methods. Arguments: ...
def get_cantera_composition_string(self, species_conversion=None): """Get the composition in a string format suitable for input to Cantera. Returns a formatted string no matter the type of composition. As such, this method is not recommended for end users; instead, prefer the `get_cantera_mole_...
Get the mole fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not...
def get_cantera_mole_fraction(self, species_conversion=None): """Get the mole fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when ...
Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not...
def get_cantera_mass_fraction(self, species_conversion=None): """Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when ...
Only runs the method if the lockfile is not acquired. You should create a setting ``LOCKFILE_PATH`` which points to ``/home/username/tmp/``. In your management command, use it like so:: LOCKFILE = os.path.join( settings.LOCKFILE_FOLDER, 'command_name') class Command(NoArgsCom...
def lockfile(lockfile_name, lock_wait_timeout=-1): """ Only runs the method if the lockfile is not acquired. You should create a setting ``LOCKFILE_PATH`` which points to ``/home/username/tmp/``. In your management command, use it like so:: LOCKFILE = os.path.join( settings.LO...
Checks if a string is a email adress or not.
def get_username(identifier): """Checks if a string is a email adress or not.""" pattern = re.compile('.+@\w+\..+') if pattern.match(identifier): try: user = User.objects.get(email=identifier) except: raise Http404 else: return user.username el...
Creates a payload with no none values. :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: a payload. :rtype: dict
def _create_payload(self, symbols): """ Creates a payload with no none values. :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: a payload. :rtype: dict """ payload = {'access_key': self.access_key} ...
Get historical rates for any day since `date`. :param date: a date :type date: date or str :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: the historical rates for any day since `date`. :rtype: dict :rais...
def historical_rates(self, date, symbols=None): """ Get historical rates for any day since `date`. :param date: a date :type date: date or str :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: the historica...
load requirements from a pip requirements file
def parse_requirements(filename): """ load requirements from a pip requirements file """ with open(filename, 'r') as f: lineiter = list(line.strip() for line in f) return [line for line in lineiter if line and not line.startswith("#")]
:DEPRECATED: Periodically save the state of the environment and the agents.
def save_state(self): ''' :DEPRECATED: Periodically save the state of the environment and the agents. ''' self._save_state() while self.peek() != simpy.core.Infinity: delay = max(self.peek() - self.now, self.interval) utils.logger.debug('Step: {}'....
Return a list where the duplicates have been removed. Args: l (list): the list to filter. Returns: list: the same list without duplicates.
def distinct(l): """ Return a list where the duplicates have been removed. Args: l (list): the list to filter. Returns: list: the same list without duplicates. """ seen = set() seen_add = seen.add return (_ for _ in l if not (_ in seen or seen_add(_)))
Does the heavy lifting of finding format modules.
def iter_format_modules(lang): """ Does the heavy lifting of finding format modules. """ if check_for_language(lang): format_locations = [] for path in CUSTOM_FORMAT_MODULE_PATHS: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') ...
Returns a list of the format modules found
def get_format_modules(lang=None, reverse=False): """ Returns a list of the format modules found """ if lang is None: lang = get_language() modules = _format_modules_cache.setdefault(lang, list( iter_format_modules(lang))) if reverse: return list(reversed(modules)) r...
For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settin...
def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the...
Main entry point for a request-response process.
def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " ...
Get the context.
def context(self): """Get the context.""" stats = status_codes_by_date_stats() attacks_data = [{ 'type': 'line', 'zIndex': 9, 'name': _('Attacks'), 'data': [(v[0], v[1]['attacks']) for v in stats] }] codes_dat...
Get the items.
def widgets(self): """Get the items.""" widgets = [] for i, chart in enumerate(most_visited_pages_charts()): widgets.append(Widget(html_id='most_visited_chart_%d' % i, content=json.dumps(chart), template='meerkat/wid...
查询单词
def word(self, word, url='https://api.shanbay.com/bdc/search/'): """查询单词""" params = { 'word': word } return self._request(url, params=params).json()
添加单词
def add_word(self, word_id, url='https://api.shanbay.com/bdc/learning/'): """添加单词""" data = { 'id': word_id } return self._request(url, method='post', data=data).json()
获取单词的例句
def examples(self, word_id, type=None, url='https://api.shanbay.com/bdc/example/'): """获取单词的例句""" params = { 'vocabulary_id': word_id } if type is not None: params['type'] = type return self._request(url, params=params).json()
创建例句
def add_example(self, word_id, original, translation, url='https://api.shanbay.com/bdc/example/'): """创建例句""" data = { 'vocabulary': word_id, 'original': original, 'translation': translation } return self._request(url, method='post'...
收藏例句
def favorite_example(self, example_id, url='https://api.shanbay.com/bdc/learning_example/'): """收藏例句""" data = { 'example_id': example_id } return self._request(url, method='post', data=data).json()
删除例句
def delete_example(self, example_id, url='https://api.shanbay.com/bdc/example/{example_id}/'): """删除例句""" url = url.format(example_id=example_id) return self._request(url, method='delete').json()
获取笔记
def notes(self, word_id, url='https://api.shanbay.com/bdc/note/'): """获取笔记""" params = { 'vocabulary_id': word_id } return self._request(url, params=params).json()
创建笔记
def add_note(self, word_id, note, url='https://api.shanbay.com/bdc/note/'): """创建笔记""" data = { 'vocabulary': word_id, 'note': note } return self._request(url, method='post', data=data).json()
收藏笔记
def favorite_note(self, note_id, url='https://api.shanbay.com/bdc/learning_note/'): """收藏笔记""" data = { 'note_id': note_id } return self._request(url, method='post', data=data).json()
删除笔记
def delete_note(self, note_id, url='https://api.shanbay.com/bdc/note/{note_id}/'): """删除笔记""" url = url.format(note_id=note_id) return self._request(url, method='delete').json()
Returns a JSON response, transforming 'context' to make the payload.
def render_to_response(self, context, **response_kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ response_kwargs['content_type'] = 'application/json' return self.response_class( self.convert_context_to_json(context), ...
Retrieves a scale representation from it's string representation :param str_representation: scale string representation to be retrieved :type str_representation: string :raises: ScaleFormatError :returns: scale representation :rtype: ScaleRepresentation
def get(self, str_representation): """Retrieves a scale representation from it's string representation :param str_representation: scale string representation to be retrieved :type str_representation: string :raises: ScaleFormatError :returns: scale representation :rt...
Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string
def valid_token(token): """Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string """ is_scale = False # Check if the token represents a scale # If it doesn't set a flag accordingly try: Scale(token)...
Extracts durations tokens from a duration representation. Parses the string representation incrementaly and raises on first error met. :param representation: duration representation :type representation: string
def extract_tokens(representation, separators=SEPARATOR_CHARACTERS): """Extracts durations tokens from a duration representation. Parses the string representation incrementaly and raises on first error met. :param representation: duration representation :type representation: string """ ...
Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided.
def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789', repetitions=False): """ Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided. ...
Loads and returns a class for a given fully qualified name.
def load_member(fqn): """Loads and returns a class for a given fully qualified name.""" modulename, member_name = split_fqn(fqn) module = __import__(modulename, globals(), locals(), member_name) return getattr(module, member_name)
Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string.
def split_fqn(fqn): """ Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string. """ if hasattr(fqn, '__call__'): fqn_string = fqn() else: fqn_string = fqn return...
小组信息 :return: 小组信息 :rtype: dict 返回值示例 :: { 'title': u'title', # 标题 'leader': u'leader', # 组长 'date_created': datetime.datetime(2013, 10, 6, 0, 0), # 创建日期 'rank': 1000, # 排名 'number': 10, # 当前成员数 ...
def info(self): """小组信息 :return: 小组信息 :rtype: dict 返回值示例 :: { 'title': u'title', # 标题 'leader': u'leader', # 组长 'date_created': datetime.datetime(2013, 10, 6, 0, 0), # 创建日期 'rank': 1000, # 排名 'number':...
更新成员加入条件 :rtype: bool
def update_limit(self, days, kind=2, condition='>='): """更新成员加入条件 :rtype: bool """ url = 'http://www.shanbay.com/team/setqualification/%s' % self.team_id data = { 'kind': kind, 'condition': condition, 'value': days, 'team': self.te...
获取小组所有成员的信息列表
def members(self): """获取小组所有成员的信息列表""" all_members = [] for page in range(1, self.max_page() + 1): all_members.extend(self.single_page_members(page)) return all_members
获取小组成员管理页面的最大页数
def max_page(self): """获取小组成员管理页面的最大页数""" html = self.request(self.dismiss_url).text soup = BeautifulSoup(html) # 分页所在 div try: pagination = soup.find_all(class_='pagination')[0] except IndexError as e: logger.exception(e) return 1 ...
获取单个页面内的小组成员信息 :param page_number: 页码 :return: 包含小组成员信息的列表 返回值示例: :: [{ 'id': 123, # member_id 'username': 'jim', # username 'nickname': 'Jim', # 昵称 'role': u'小组长', # 身份 ...
def single_page_members(self, page_number=1): """获取单个页面内的小组成员信息 :param page_number: 页码 :return: 包含小组成员信息的列表 返回值示例: :: [{ 'id': 123, # member_id 'username': 'jim', # username 'nickname': 'Jim', ...
踢人. 注意别把自己给踢了. :param member_ids: 组员 ids :return: bool
def dismiss(self, member_ids): """踢人. 注意别把自己给踢了. :param member_ids: 组员 ids :return: bool """ url = 'http://www.shanbay.com/api/v1/team/member/' data = { 'action': 'dispel', } if isinstance(member_ids, (list, tuple)): data['ids'] = ...
小组发帖要用的 forum_id
def forum_id(self): """小组发帖要用的 forum_id""" html = self.request(self.team_url).text soup = BeautifulSoup(html) return soup.find(id='forum_id').attrs['value']
小组发贴 :return: 帖子 id 或 ``None``
def new_topic(self, title, content): """小组发贴 :return: 帖子 id 或 ``None`` """ data = { 'title': title, 'body': content, 'csrfmiddlewaretoken': self._request.cookies.get('csrftoken') } url = 'http://www.shanbay.com/api/v1/forum/%s/thread/'...
小组回帖 :return: 帖子 id 或 ``None``
def reply_topic(self, topic_id, content): """小组回帖 :return: 帖子 id 或 ``None`` """ data = { 'body': content, 'csrfmiddlewaretoken': self._request.cookies.get('csrftoken') } url = 'http://www.shanbay.com/api/v1/forum/thread/%s/post/' % topic_id ...
Connects to the server. :param origin: (Optional) The origin.
def connect(self, origin=None): """ Connects to the server. :param origin: (Optional) The origin. """ self.logger.debug('Establish connection...') if self.connected: self.logger.warning('Connection already established. Return...') return ...
Closes the connection.
def disconnect(self): """ Closes the connection. """ self.logger.debug('Close connection...') self.auto_reconnect = False if self.websocket is not None: self.websocket.close()
Sends data to the server.
def send(self, data): """ Sends data to the server. """ self.logger.debug('Send data: {}'.format(data)) if not self.connected: self.logger.warning('Connection not established. Return...') return self.websocket.send(json.dumps(data))
Called aways when a message arrives.
def _on_message(self, socket, message): """ Called aways when a message arrives. """ data = json.loads(message) message_type = None identifier = None subscription = None if 'type' in data: message_type = data['type'] if 'identifier' i...
Called when the connection was closed.
def _on_close(self, socket): """ Called when the connection was closed. """ self.logger.debug('Connection closed.') for subscription in self.subscriptions.values(): if subscription.state == 'subscribed': subscription.state = 'connection_pending'
If connected to server.
def connected(self): """ If connected to server. """ return self.websocket is not None and \ self.websocket.sock is not None and \ self.websocket.sock.connected
Finds a subscription by it's identifier.
def find_subscription(self, identifier): """ Finds a subscription by it's identifier. """ for subscription in self.subscriptions.values(): if subscription.identifier == identifier: return subscription
Subscribes at the server.
def create(self): """ Subscribes at the server. """ self.logger.debug('Create subscription on server...') if not self.connection.connected: self.state = 'connection_pending' return data = { 'command': 'subscribe', 'identif...
Removes the subscription.
def remove(self): """ Removes the subscription. """ self.logger.debug('Remove subscription from server...') data = { 'command': 'unsubscribe', 'identifier': self._identifier_string() } self.connection.send(data) self.state = 'unsu...
Sends data to the server on the subscription channel. :param data: The JSON data to send.
def send(self, message): """ Sends data to the server on the subscription channel. :param data: The JSON data to send. """ self.logger.debug('Send message: {}'.format(message)) if self.state == 'pending' or self.state == 'connection_pending': self.lo...
API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message
def received(self, data): """ API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message """ self.logger.debug('Data received: {}'.format(data)) message_type = None ...
Called when the subscription was accepted successfully.
def _subscribed(self): """ Called when the subscription was accepted successfully. """ self.logger.debug('Subscription confirmed.') self.state = 'subscribed' for message in self.message_queue: self.send(message)
Handle the command line options
def cli_opts(): """ Handle the command line options """ parser = argparse.ArgumentParser() parser.add_argument( "--homeassistant-config", type=str, required=False, dest="config", help="Create configuration section for home assistant",) parser.add_argument( ...
Register signal handlers
def _setup_signal_handler(self): """ Register signal handlers """ signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGQUIT, self._signal_handler)
Monitor the bus for events and handle them
def start(self): """ Monitor the bus for events and handle them """ print("Entering monitoring mode, press CTRL-C to quit") serial = self._connection.serial while True: serial.write(b"@R") length = int(serial.read(), 16) data = serial.read(length * 2)...
Method called when handling signals
def _signal_handler(self, signum, frame): """ Method called when handling signals """ if self._options.config: with open(self._options.config, "w") as cfg: yaml.dump(self._home_assistant_config(), cfg) print( "Dumped home assistant configur...
Add device to the list of known ones
def _add_device(self, scs_id, ha_id, name): """ Add device to the list of known ones """ if scs_id in self._devices: return self._devices[scs_id] = { 'name': name, 'ha_id': ha_id }
Creates home assistant configuration for the known devices
def _home_assistant_config(self): """ Creates home assistant configuration for the known devices """ devices = {} for scs_id, dev in self._devices.items(): devices[dev['ha_id']] = { 'name': dev['name'], 'scs_id': scs_id} return {'devices': dev...
Load the filter file and populates self._devices accordingly
def _load_filter(self, config): """ Load the filter file and populates self._devices accordingly """ path = pathlib.Path(config) if not path.is_file(): return with open(config, 'r') as conf: devices = yaml.load(conf)['devices'] for ha_id, dev in devic...
Closes the connection to the serial port and ensure no pending operatoin are left
def close(self): """ Closes the connection to the serial port and ensure no pending operatoin are left """ self._serial.write(b"@c") self._serial.read() self._serial.close()
Load a value, converting it to the proper type if validation_type exists.
def load(self, value): """Load a value, converting it to the proper type if validation_type exists.""" if self.property_type is None: return value elif not isinstance(self.property_type, BaseType): raise TypeError('property_type must be schematics BaseType') else:...
Iterate over all ConfigProperty attributes, yielding (attr_name, config_property)
def _iter_config_props(cls): """Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) """ props = inspect.getmembers(cls, lambda a: isinstance(a, ConfigProperty)) for attr_name, config_prop in props: yield attr_name, config_prop
Set unspecified property_keys for each ConfigProperty to the name of the class attr
def _update_property_keys(cls): """Set unspecified property_keys for each ConfigProperty to the name of the class attr""" for attr_name, config_prop in cls._iter_config_props(): if config_prop.property_key is None: config_prop.property_key = attr_name
Set instance property to a value and add it varz if needed
def _set_instance_prop(self, attr_name, config_prop, value): """Set instance property to a value and add it varz if needed""" setattr(self, attr_name, value) # add to varz if it is not private if not config_prop.exclude_from_varz: self.varz[attr_name] = value
Load values for all ConfigProperty attributes
def _load(self): """Load values for all ConfigProperty attributes""" for attr_name, config_prop in self._iter_config_props(): found = False for loader in self._loaders: if loader.exists(config_prop.property_key): raw_value = loader.get(config_p...
Reload all ConfigProperty values (reading from loader sources again, if applicable)
def reload(self): """Reload all ConfigProperty values (reading from loader sources again, if applicable)""" for loader in self._loaders: loader.reload() self.varz = {} # reset varz self._load()
Return all properties and values in a dictionary (includes private properties)
def as_dict(self): """Return all properties and values in a dictionary (includes private properties)""" return {config_name: getattr(self, config_name) for config_name, _ in self._iter_config_props()}
Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file
def in_same_dir(as_file, target_file): """Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file """ return os.path.abspa...
Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer". Other possibilities include names with hyphens such as "Chi...
def compare_name(given_name, family_name, question_name): """Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer"...
Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range (`bool`): flag from schema indicating T range is to be checked field (`str`): T_range values (`list`): List of temperature values indicating low, middle, and high ranges The rule...
def _validate_isvalid_t_range(self, isvalid_t_range, field, values): """Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range (`bool`): flag from schema indicating T range is to be checked field (`str`): T_range values (`list`): List...
Checks for appropriate units using Pint unit registry. Args: isvalid_unit (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with units in question. value (`dict`): dictionary of values from file associated with this property. ...
def _validate_isvalid_unit(self, isvalid_unit, field, value): """Checks for appropriate units using Pint unit registry. Args: isvalid_unit (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with units in question. value (`dic...
Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. value (`dict`): dictionary of values from file associated with this propert...
def _validate_isvalid_history(self, isvalid_history, field, value): """Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. ...
Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. value (`list`): list whose first element is a string representing a value wi...
def _validate_isvalid_quantity(self, isvalid_quantity, field, value): """Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. ...
Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with the quantity in question. value (`list`): list with the string of the value ...
def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value): """Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with t...
Checks valid reference metadata using DOI (if present). Args: isvalid_reference (`bool`): flag from schema indicating reference to be checked. field (`str`): 'reference' value (`dict`): dictionary of reference metadata. The rule's arguments are validated against thi...
def _validate_isvalid_reference(self, isvalid_reference, field, value): """Checks valid reference metadata using DOI (if present). Args: isvalid_reference (`bool`): flag from schema indicating reference to be checked. field (`str`): 'reference' value (`dict`): dictio...
Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule's arguments are validated against this schema: {'isvalid_orcid...
def _validate_isvalid_orcid(self, isvalid_orcid, field, value): """Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule...
Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (dict): dictionary of composition The rule's arguments are validated against this...
def _validate_isvalid_composition(self, isvalid_composition, field, value): """Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (di...
Read a CSV in canonical form: :: <agent_id, t_step, key, value, value_type>
def read_csv(filename, keys=None, convert_types=False, **kwargs): ''' Read a CSV in canonical form: :: <agent_id, t_step, key, value, value_type> ''' df = pd.read_csv(filename) if convert_types: df = convert_types_slow(df) if keys: df = df[df['key'].isin(keys)] df =...
This is a slow operation.
def convert_types_slow(df): '''This is a slow operation.''' dtypes = get_types(df) for k, v in dtypes.items(): t = df[df['key']==k] t['value'] = t['value'].astype(v) df = df.apply(convert_row, axis=1) return df
Split a dataframe in two dataframes: one with the history of agents, and one with the environment history
def split_df(df): ''' Split a dataframe in two dataframes: one with the history of agents, and one with the environment history ''' envmask = (df['agent_id'] == 'env') n_env = envmask.sum() if n_env == len(df): return df, None elif n_env == 0: return None, df agents, ...
Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into two dataframes with a column per key: one with the history of the agents, and one for the history of the environment.
def process(df, **kwargs): ''' Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into two dataframes with a column per key: one with the history of the agents, and one for the history of the environment. ''' env, agents = split_df(df) return process_one(env...
Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into a dataframe with a column per key
def process_one(df, *keys, columns=['key', 'agent_id'], values='value', fill=True, index=['t_step',], aggfunc='first', **kwargs): ''' Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into a dataframe with a column per key ''' if df ...
Read all the trial data and plot the result of applying a function on them.
def plot_all(*args, **kwargs): ''' Read all the trial data and plot the result of applying a function on them. ''' dfs = do_all(*args, **kwargs) ps = [] for line in dfs: f, df, config = line df.plot(title=config['name']) ps.append(df) return ps
Return a name that can be imported, to serialize/deserialize an object
def name(value, known_modules=[]): '''Return a name that can be imported, to serialize/deserialize an object''' if value is None: return 'None' if not isinstance(value, type): # Get the class name first value = type(value) tname = value.__name__ if hasattr(builtins, tname): ...
Get a text representation of an object.
def serialize(v, known_modules=[]): '''Get a text representation of an object.''' tname = name(v, known_modules=known_modules) func = serializer(tname) return func(v), tname
Get an object from a text representation
def deserialize(type_, value=None, **kwargs): '''Get an object from a text representation''' if not isinstance(type_, str): return type_ des = deserializer(type_, **kwargs) if value is None: return des return des(value)
Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line).
def content(self): """ Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line). """ if self._content is None: self._content = self.parse_files() return self._content
Find files. Returns: list: the list of matching files.
def matching_files(self): """ Find files. Returns: list: the list of matching files. """ matching = [] matcher = self.file_path_regex pieces = self.file_path_regex.pattern.split(sep) partial_matchers = list(map(re.compile, ( sep.jo...
Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line).
def parse_files(self): """ Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line). """ log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: ...
Calculate the threshold values (thresholds for a uniform distribution) of an agent distribution given the weights of each agent type. The input has this form: :: [ {'agent_type': 'agent_type_1', 'weight': 0.2, 'state': { 'id': 0 ...
def calculate_distribution(network_agents=None, agent_type=None): ''' Calculate the threshold values (thresholds for a uniform distribution) of an agent distribution given the weights of each agent type. The input has this form: :: [ {'agent_type': 'a...