Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def visit_importfrom(self, node): '''triggered when a from statement is seen''' module_filename = node.root().file if fnmatch.fnmatch(module_filename, '__init__.py*') and \ not fnmatch.fnmatch(module_filename, 'test_*.py*'): return basename = node.modname self._check_blacklisted_module(node, basename)
[]
Please provide a description of the function:def _check_blacklisted_module(self, node, mod_path): '''check if the module is blacklisted''' for mod_name in self.blacklisted_modules: if mod_path == mod_name or mod_path.startswith(mod_name + '.'): names = [] for name, name_as in node.names: if name_as: names.append('{0} as {1}'.format(name, name_as)) else: names.append(name) try: import_from_module = node.modname if import_from_module == 'salttesting.helpers': for name in names: if name == 'ensure_in_syspath': self.add_message('blacklisted-syspath-update', node=node) continue msg = 'Please use \'from tests.support.helpers import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if import_from_module in ('salttesting.mock', 'mock', 'unittest.mock', 'unittest2.mock'): for name in names: msg = 'Please use \'from tests.support.mock import {0}\''.format(name) if import_from_module in ('salttesting.mock', 'unittest.mock', 'unittest2.mock'): message_id = 'blacklisted-module' else: message_id = 'blacklisted-external-module' self.add_message(message_id, node=node, args=(mod_path, msg)) continue if import_from_module == 'salttesting.parser': for name in names: msg = 'Please use \'from tests.support.parser import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if import_from_module == 'salttesting.case': for name in names: msg = 'Please use \'from tests.support.case import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if import_from_module == 'salttesting.unit': for name in names: msg = 'Please use \'from tests.support.unit import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if import_from_module.startswith(('unittest', 'unittest2')): for name in names: msg = 'Please use \'from tests.support.unit import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if import_from_module == 'salttesting.mixins': for name in names: msg = 'Please use \'from tests.support.mixins import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if import_from_module == 'six': for name in names: msg = 'Please use \'from salt.ext.six import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if import_from_module == 'distutils.version': for name in names: msg = 'Please use \'from salt.utils.versions import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if names: for name in names: if name in ('TestLoader', 'TextTestRunner', 'TestCase', 'expectedFailure', 'TestSuite', 'skipIf', 'TestResult'): msg = 'Please use \'from tests.support.unit import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if name in ('SaltReturnAssertsMixin', 'SaltMinionEventAssertsMixin'): msg = 'Please use \'from tests.support.mixins import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if name in ('ModuleCase', 'SyndicCase', 'ShellCase', 'SSHCase'): msg = 'Please use \'from tests.support.case import {0}\''.format(name) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) continue if name == 'run_tests': msg = 'Please remove the \'if __name__ == "__main__":\' section from the end of the module' self.add_message('blacklisted-test-module-execution', node=node, args=msg) continue if mod_name in ('integration', 'unit'): if name in ('SYS_TMP_DIR', 'TMP', 'FILES', 'PYEXEC', 'MOCKBIN', 'SCRIPT_DIR', 'TMP_STATE_TREE', 'TMP_PRODENV_STATE_TREE', 'TMP_CONF_DIR', 'TMP_SUB_MINION_CONF_DIR', 'TMP_SYNDIC_MINION_CONF_DIR', 'TMP_SYNDIC_MASTER_CONF_DIR', 'CODE_DIR', 'TESTS_DIR', 'CONF_DIR', 'PILLAR_DIR', 'TMP_SCRIPT_DIR', 'ENGINES_DIR', 'LOG_HANDLERS_DIR', 'INTEGRATION_TEST_DIR'): msg = 'Please use \'from tests.support.paths import {0}\''.format(name) self.add_message('blacklisted-import', node=node, args=(mod_path, msg)) continue msg = 'Please use \'from tests.{0} import {1}\''.format(mod_path, name) self.add_message('blacklisted-import', node=node, args=(mod_path, msg)) continue msg = 'Please report this error to SaltStack so we can fix it: Trying to import {0} from {1}'.format(name, mod_path) self.add_message('blacklisted-module', node=node, args=(mod_path, msg)) except AttributeError: if mod_name in ('integration', 'unit', 'mock', 'six', 'distutils.version', 'unittest', 'unittest2'): if mod_name in ('integration', 'unit'): msg = 'Please use \'import tests.{0} as {0}\''.format(mod_name) message_id = 'blacklisted-import' elif mod_name == 'mock': msg = 'Please use \'import tests.support.{0} as {0}\''.format(mod_name) message_id = 'blacklisted-external-import' elif mod_name == 'six': msg = 'Please use \'import salt.ext.{0} as {0}\''.format(name) message_id = 'blacklisted-external-import' elif mod_name == 'distutils.version': msg = 'Please use \'import salt.utils.versions\' instead' message_id = 'blacklisted-import' elif mod_name.startswith(('unittest', 'unittest2')): msg = 'Please use \'import tests.support.unit as {}\' instead'.format(mod_name) message_id = 'blacklisted-import' self.add_message(message_id, node=node, args=(mod_path, msg)) continue msg = 'Please report this error to SaltStack so we can fix it: Trying to import {0}'.format(mod_path) self.add_message('blacklisted-import', node=node, args=(mod_path, msg))
[]
Please provide a description of the function:def visit_import(self, node): '''triggered when an import statement is seen''' if self.process_module: # Store salt imported modules for module, import_as in node.names: if not module.startswith('salt'): continue if import_as and import_as not in self.imported_salt_modules: self.imported_salt_modules[import_as] = module continue if module not in self.imported_salt_modules: self.imported_salt_modules[module] = module
[]
Please provide a description of the function:def visit_importfrom(self, node): '''triggered when a from statement is seen''' if self.process_module: if not node.modname.startswith('salt'): return # Store salt imported modules for module, import_as in node.names: if import_as and import_as not in self.imported_salt_modules: self.imported_salt_modules[import_as] = import_as continue if module not in self.imported_salt_modules: self.imported_salt_modules[module] = module
[]
Please provide a description of the function:def register(linter): ''' Register the transformation functions. ''' try: MANAGER.register_transform(nodes.Class, rootlogger_transform) except AttributeError: MANAGER.register_transform(nodes.ClassDef, rootlogger_transform)
[]
Please provide a description of the function:def register(linter): ''' required method to auto register this checker ''' if HAS_PEP8 is False: return linter.register_checker(PEP8Indentation(linter)) linter.register_checker(PEP8Whitespace(linter)) linter.register_checker(PEP8BlankLine(linter)) linter.register_checker(PEP8Import(linter)) linter.register_checker(PEP8LineLength(linter)) linter.register_checker(PEP8Statement(linter)) linter.register_checker(PEP8Runtime(linter)) linter.register_checker(PEP8IndentationWarning(linter)) linter.register_checker(PEP8WhitespaceWarning(linter)) linter.register_checker(PEP8BlankLineWarning(linter)) linter.register_checker(PEP8DeprecationWarning(linter))
[]
Please provide a description of the function:def process_module(self, node): ''' process a module the module's content is accessible via node.file_stream object ''' nodepaths = [] if not isinstance(node.path, list): nodepaths = [node.path] else: nodepaths = node.path for node_path in nodepaths: if node_path not in _PROCESSED_NODES: stylechecker = StyleGuide( parse_argv=False, config_file=False, quiet=2, reporter=PyLintPEP8Reporter ) _PROCESSED_NODES[node_path] = stylechecker.check_files([node_path]) for code, lineno, text in _PROCESSED_NODES[node_path].locations: pylintcode = '{0}8{1}'.format(code[0], code[1:]) if pylintcode in self.msgs_map: # This will be handled by PyLint itself, skip it continue if pylintcode not in _KNOWN_PEP8_IDS: if pylintcode not in _UNHANDLED_PEP8_IDS: _UNHANDLED_PEP8_IDS.append(pylintcode) msg = 'The following code, {0}, was not handled by the PEP8 plugin'.format(pylintcode) if logging.root.handlers: logging.getLogger(__name__).warning(msg) else: sys.stderr.write('{0}\n'.format(msg)) continue if pylintcode not in self._msgs: # Not for our class implementation to handle continue if code in ('E111', 'E113'): if _PROCESSED_NODES[node_path].lines[lineno-1].strip().startswith('#'): # If E111 is triggered in a comment I consider it, at # least, bad judgement. See https://github.com/jcrocholl/pep8/issues/300 # If E113 is triggered in comments, which I consider a bug, # skip it. See https://github.com/jcrocholl/pep8/issues/274 continue try: self.add_message(pylintcode, line=lineno, args=(code, text)) except TypeError as exc: if 'not all arguments' not in str(exc): raise # Message does not support being passed the text arg self.add_message(pylintcode, line=lineno, args=(code,))
[]
Please provide a description of the function:def process_module(self, node): ''' process a module ''' if not HAS_PYQVER: return minimum_version = tuple([int(x) for x in self.config.minimum_python_version.split('.')]) with open(node.path, 'r') as rfh: for version, reasons in pyqver2.get_versions(rfh.read()).iteritems(): if version > minimum_version: for lineno, msg in reasons: self.add_message( 'E0598', line=lineno, args=(self.config.minimum_python_version, msg) )
[]
Please provide a description of the function:def get_xblock_settings(self, default=None): settings_service = self.runtime.service(self, "settings") if settings_service: return settings_service.get_settings_bucket(self, default=default) return default
[ "\n Gets XBlock-specific settigns for current XBlock\n\n Returns default if settings service is not available.\n\n Parameters:\n default - default value to be used in two cases:\n * No settings service is available\n * As a `default` parameter to `SettingsService.get_settings_bucket`\n " ]
Please provide a description of the function:def get_theme(self): xblock_settings = self.get_xblock_settings(default={}) if xblock_settings and self.theme_key in xblock_settings: return xblock_settings[self.theme_key] return self.default_theme_config
[ "\n Gets theme settings from settings service. Falls back to default (LMS) theme\n if settings service is not available, xblock theme settings are not set or does\n contain mentoring theme settings.\n " ]
Please provide a description of the function:def include_theme_files(self, fragment): theme = self.get_theme() if not theme or 'package' not in theme: return theme_package, theme_files = theme.get('package', None), theme.get('locations', []) resource_loader = ResourceLoader(theme_package) for theme_file in theme_files: fragment.add_css(resource_loader.load_unicode(theme_file))
[ "\n Gets theme configuration and renders theme css into fragment\n " ]
Please provide a description of the function:def load_unicode(self, resource_path): resource_content = pkg_resources.resource_string(self.module_name, resource_path) return resource_content.decode('utf-8')
[ "\n Gets the content of a resource\n " ]
Please provide a description of the function:def render_django_template(self, template_path, context=None, i18n_service=None): context = context or {} context['_i18n_service'] = i18n_service libraries = { 'i18n': 'xblockutils.templatetags.i18n', } # For django 1.8, we have to load the libraries manually, and restore them once the template is rendered. _libraries = None if django.VERSION[0] == 1 and django.VERSION[1] == 8: _libraries = TemplateBase.libraries.copy() for library_name in libraries: library = TemplateBase.import_library(libraries[library_name]) if library: TemplateBase.libraries[library_name] = library engine = Engine() else: # Django>1.8 Engine can load the extra templatetag libraries itself # but we have to override the default installed libraries. from django.template.backends.django import get_installed_libraries installed_libraries = get_installed_libraries() installed_libraries.update(libraries) engine = Engine(libraries=installed_libraries) template_str = self.load_unicode(template_path) template = Template(template_str, engine=engine) rendered = template.render(Context(context)) # Restore the original TemplateBase.libraries if _libraries is not None: TemplateBase.libraries = _libraries return rendered
[ "\n Evaluate a django template by resource path, applying the provided context.\n " ]
Please provide a description of the function:def render_mako_template(self, template_path, context=None): context = context or {} template_str = self.load_unicode(template_path) lookup = MakoTemplateLookup(directories=[pkg_resources.resource_filename(self.module_name, '')]) template = MakoTemplate(template_str, lookup=lookup) return template.render(**context)
[ "\n Evaluate a mako template by resource path, applying the provided context\n " ]
Please provide a description of the function:def render_template(self, template_path, context=None): warnings.warn( "ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_template" ) return self.render_django_template(template_path, context)
[ "\n This function has been deprecated. It calls render_django_template to support backwards compatibility.\n " ]
Please provide a description of the function:def render_js_template(self, template_path, element_id, context=None): context = context or {} return u"<script type='text/template' id='{}'>\n{}\n</script>".format( element_id, self.render_template(template_path, context) )
[ "\n Render a js template.\n " ]
Please provide a description of the function:def load_scenarios_from_path(self, relative_scenario_dir, include_identifier=False): base_dir = os.path.dirname(os.path.realpath(sys.modules[self.module_name].__file__)) scenario_dir = os.path.join(base_dir, relative_scenario_dir) scenarios = [] if os.path.isdir(scenario_dir): for template in sorted(os.listdir(scenario_dir)): if not template.endswith('.xml'): continue identifier = template[:-4] title = identifier.replace('_', ' ').title() template_path = os.path.join(relative_scenario_dir, template) scenario = text_type(self.render_template(template_path, {"url_name": identifier})) if not include_identifier: scenarios.append((title, scenario)) else: scenarios.append((identifier, title, scenario)) return scenarios
[ "\n Returns an array of (title, xmlcontent) from files contained in a specified directory,\n formatted as expected for the return value of the workbench_scenarios() method.\n\n If `include_identifier` is True, returns an array of (identifier, title, xmlcontent).\n " ]
Please provide a description of the function:def merge_translation(self, context): language = get_language() i18n_service = context.get('_i18n_service', None) if i18n_service: # Cache the original translation object to reduce overhead if language not in self._translations: self._translations[language] = trans_real.DjangoTranslation(language) translation = trans_real.translation(language) translation.merge(i18n_service) yield # Revert to original translation object if language in self._translations: trans_real._translations[language] = self._translations[language] # Re-activate the current language to reset translation caches trans_real.activate(language)
[ "\n Context wrapper which modifies the given language's translation catalog using the i18n service, if found.\n " ]
Please provide a description of the function:def render(self, context): with self.merge_translation(context): django_translated = self.do_translate.render(context) return django_translated
[ "\n Renders the translated text using the XBlock i18n service, if available.\n " ]
Please provide a description of the function:def studio_view(self, context): fragment = Fragment() context = {'fields': []} # Build a list of all the fields that can be edited: for field_name in self.editable_fields: field = self.fields[field_name] assert field.scope in (Scope.content, Scope.settings), ( "Only Scope.content or Scope.settings fields can be used with " "StudioEditableXBlockMixin. Other scopes are for user-specific data and are " "not generally created/configured by content authors in Studio." ) field_info = self._make_field_info(field_name, field) if field_info is not None: context["fields"].append(field_info) fragment.content = loader.render_template('templates/studio_edit.html', context) fragment.add_javascript(loader.load_unicode('public/studio_edit.js')) fragment.initialize_js('StudioEditableXBlockMixin') return fragment
[ "\n Render a form for editing this XBlock\n " ]
Please provide a description of the function:def _make_field_info(self, field_name, field): supported_field_types = ( (Integer, 'integer'), (Float, 'float'), (Boolean, 'boolean'), (String, 'string'), (List, 'list'), (DateTime, 'datepicker'), (JSONField, 'generic'), # This is last so as a last resort we display a text field w/ the JSON string ) if self.service_declaration("i18n"): ugettext = self.ugettext else: def ugettext(text): return text info = { 'name': field_name, 'display_name': ugettext(field.display_name) if field.display_name else "", 'is_set': field.is_set_on(self), 'default': field.default, 'value': field.read_from(self), 'has_values': False, 'help': ugettext(field.help) if field.help else "", 'allow_reset': field.runtime_options.get('resettable_editor', True), 'list_values': None, # Only available for List fields 'has_list_values': False, # True if list_values_provider exists, even if it returned no available options } for type_class, type_name in supported_field_types: if isinstance(field, type_class): info['type'] = type_name # If String fields are declared like String(..., multiline_editor=True), then call them "text" type: editor_type = field.runtime_options.get('multiline_editor') if type_class is String and editor_type: if editor_type == "html": info['type'] = 'html' else: info['type'] = 'text' if type_class is List and field.runtime_options.get('list_style') == "set": # List represents unordered, unique items, optionally drawn from list_values_provider() info['type'] = 'set' elif type_class is List: info['type'] = "generic" # disable other types of list for now until properly implemented break if "type" not in info: raise NotImplementedError("StudioEditableXBlockMixin currently only supports fields derived from JSONField") if info["type"] in ("list", "set"): info["value"] = [json.dumps(val) for val in info["value"]] info["default"] = json.dumps(info["default"]) elif info["type"] == "generic": # Convert value to JSON string if we're treating this field generically: info["value"] = json.dumps(info["value"]) info["default"] = json.dumps(info["default"]) elif info["type"] == "datepicker": if info["value"]: info["value"] = info["value"].strftime("%m/%d/%Y") if info["default"]: info["default"] = info["default"].strftime("%m/%d/%Y") if 'values_provider' in field.runtime_options: values = field.runtime_options["values_provider"](self) else: values = field.values if values and not isinstance(field, Boolean): # This field has only a limited number of pre-defined options. # Protip: when defining the field, values= can be a callable. if isinstance(field.values, dict) and isinstance(field, (Float, Integer)): # e.g. {"min": 0 , "max": 10, "step": .1} for option in field.values: if option in ("min", "max", "step"): info[option] = field.values.get(option) else: raise KeyError("Invalid 'values' key. Should be like values={'min': 1, 'max': 10, 'step': 1}") elif isinstance(values[0], dict) and "display_name" in values[0] and "value" in values[0]: # e.g. [ {"display_name": "Always", "value": "always"}, ... ] for value in values: assert "display_name" in value and "value" in value info['values'] = values else: # e.g. [1, 2, 3] - we need to convert it to the [{"display_name": x, "value": x}] format info['values'] = [{"display_name": text_type(val), "value": val} for val in values] info['has_values'] = 'values' in info if info["type"] in ("list", "set") and field.runtime_options.get('list_values_provider'): list_values = field.runtime_options['list_values_provider'](self) # list_values must be a list of values or {"display_name": x, "value": y} objects # Furthermore, we need to convert all values to JSON since they could be of any type if list_values and isinstance(list_values[0], dict) and "display_name" in list_values[0]: # e.g. [ {"display_name": "Always", "value": "always"}, ... ] for entry in list_values: assert "display_name" in entry and "value" in entry entry["value"] = json.dumps(entry["value"]) else: # e.g. [1, 2, 3] - we need to convert it to the [{"display_name": x, "value": x}] format list_values = [json.dumps(val) for val in list_values] list_values = [{"display_name": text_type(val), "value": val} for val in list_values] info['list_values'] = list_values info['has_list_values'] = True return info
[ "\n Create the information that the template needs to render a form field for this field.\n ", " Dummy ugettext method that doesn't do anything " ]
Please provide a description of the function:def submit_studio_edits(self, data, suffix=''): values = {} # dict of new field values we are updating to_reset = [] # list of field names to delete from this XBlock for field_name in self.editable_fields: field = self.fields[field_name] if field_name in data['values']: if isinstance(field, JSONField): values[field_name] = field.from_json(data['values'][field_name]) else: raise JsonHandlerError(400, "Unsupported field type: {}".format(field_name)) elif field_name in data['defaults'] and field.is_set_on(self): to_reset.append(field_name) self.clean_studio_edits(values) validation = Validation(self.scope_ids.usage_id) # We cannot set the fields on self yet, because even if validation fails, studio is going to save any changes we # make. So we create a "fake" object that has all the field values we are about to set. preview_data = FutureFields( new_fields_dict=values, newly_removed_fields=to_reset, fallback_obj=self ) self.validate_field_data(validation, preview_data) if validation: for field_name, value in six.iteritems(values): setattr(self, field_name, value) for field_name in to_reset: self.fields[field_name].delete_from(self) return {'result': 'success'} else: raise JsonHandlerError(400, validation.to_json())
[ "\n AJAX handler for studio_view() Save button\n " ]
Please provide a description of the function:def validate(self): validation = super(StudioEditableXBlockMixin, self).validate() self.validate_field_data(validation, self) return validation
[ "\n Validates the state of this XBlock.\n\n Subclasses should override validate_field_data() to validate fields and override this\n only for validation not related to this block's field values.\n " ]
Please provide a description of the function:def render_children(self, context, fragment, can_reorder=True, can_add=False): contents = [] child_context = {'reorderable_items': set()} if context: child_context.update(context) for child_id in self.children: child = self.runtime.get_block(child_id) if can_reorder: child_context['reorderable_items'].add(child.scope_ids.usage_id) view_to_render = 'author_view' if hasattr(child, 'author_view') else 'student_view' rendered_child = child.render(view_to_render, child_context) fragment.add_frag_resources(rendered_child) contents.append({ 'id': text_type(child.scope_ids.usage_id), 'content': rendered_child.content }) fragment.add_content(self.runtime.render_template("studio_render_children_view.html", { 'items': contents, 'xblock_context': context, 'can_add': can_add, 'can_reorder': can_reorder, }))
[ "\n Renders the children of the module with HTML appropriate for Studio. If can_reorder is\n True, then the children will be rendered to support drag and drop.\n " ]
Please provide a description of the function:def author_view(self, context): root_xblock = context.get('root_xblock') if root_xblock and root_xblock.location == self.location: # User has clicked the "View" link. Show an editable preview of this block's children return self.author_edit_view(context) return self.author_preview_view(context)
[ "\n Display a the studio editor when the user has clicked \"View\" to see the container view,\n otherwise just show the normal 'author_preview_view' or 'student_view' preview.\n " ]
Please provide a description of the function:def author_edit_view(self, context): fragment = Fragment() self.render_children(context, fragment, can_reorder=True, can_add=False) return fragment
[ "\n Child blocks can override this to control the view shown to authors in Studio when\n editing this block's children.\n " ]
Please provide a description of the function:def preview_view(self, context): view_to_render = 'author_view' if hasattr(self, 'author_view') else 'student_view' renderer = getattr(self, view_to_render) return renderer(context)
[ "\n Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context.\n Default implementation uses author_view if available, otherwise falls back to student_view\n Child classes can override this method to control their presentation in preview context\n " ]
Please provide a description of the function:def get_nested_blocks_spec(self): return [ block_spec if isinstance(block_spec, NestedXBlockSpec) else NestedXBlockSpec(block_spec) for block_spec in self.allowed_nested_blocks ]
[ "\n Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface\n " ]
Please provide a description of the function:def author_edit_view(self, context): fragment = Fragment() if 'wrap_children' in context: fragment.add_content(context['wrap_children']['head']) self.render_children(context, fragment, can_reorder=True, can_add=False) if 'wrap_children' in context: fragment.add_content(context['wrap_children']['tail']) fragment.add_content( loader.render_template('templates/add_buttons.html', {'child_blocks': self.get_nested_blocks_spec()}) ) fragment.add_javascript(loader.load_unicode('public/studio_container.js')) fragment.initialize_js('StudioContainerXBlockWithNestedXBlocksMixin') return fragment
[ "\n View for adding/editing nested blocks\n " ]
Please provide a description of the function:def author_preview_view(self, context): children_contents = [] fragment = Fragment() for child_id in self.children: child = self.runtime.get_block(child_id) child_fragment = self._render_child_fragment(child, context, 'preview_view') fragment.add_frag_resources(child_fragment) children_contents.append(child_fragment.content) render_context = { 'block': self, 'children_contents': children_contents } render_context.update(context) fragment.add_content(self.loader.render_template(self.CHILD_PREVIEW_TEMPLATE, render_context)) return fragment
[ "\n View for previewing contents in studio.\n " ]
Please provide a description of the function:def _render_child_fragment(self, child, context, view='student_view'): try: child_fragment = child.render(view, context) except NoSuchViewError: if child.scope_ids.block_type == 'html' and getattr(self.runtime, 'is_author_mode', False): # html block doesn't support preview_view, and if we use student_view Studio will wrap # it in HTML that we don't want in the preview. So just render its HTML directly: child_fragment = Fragment(child.data) else: child_fragment = child.render('student_view', context) return child_fragment
[ "\n Helper method to overcome html block rendering quirks\n " ]
Please provide a description of the function:def package_data(pkg, root_list): data = [] for root in root_list: for dirname, _, files in os.walk(os.path.join(pkg, root)): for fname in files: data.append(os.path.relpath(os.path.join(dirname, fname), pkg)) return {pkg: data}
[ "Generic function to find package_data for `pkg` under `root`." ]
Please provide a description of the function:def load_requirements(*requirements_paths): requirements = set() for path in requirements_paths: requirements.update( line.split('#')[0].strip() for line in open(path).readlines() if is_requirement(line.strip()) ) return list(requirements)
[ "\n Load all requirements from the specified requirements files.\n Returns a list of requirement strings.\n " ]
Please provide a description of the function:def is_requirement(line): return not ( line == '' or line.startswith('-r') or line.startswith('#') or line.startswith('-e') or line.startswith('git+') )
[ "\n Return True if the requirement line is a package requirement;\n that is, it is not blank, a comment, a URL, or an included file.\n " ]
Please provide a description of the function:def publish_event(self, data, suffix=''): try: event_type = data.pop('event_type') except KeyError: return {'result': 'error', 'message': 'Missing event_type in JSON data'} return self.publish_event_from_dict(event_type, data)
[ "\n AJAX handler to allow client-side code to publish a server-side event\n " ]
Please provide a description of the function:def publish_event_from_dict(self, event_type, data): for key, value in self.additional_publish_event_data.items(): if key in data: return {'result': 'error', 'message': 'Key should not be in publish_event data: {}'.format(key)} data[key] = value self.runtime.publish(self, event_type, data) return {'result': 'success'}
[ "\n Combine 'data' with self.additional_publish_event_data and publish an event\n " ]
Please provide a description of the function:def child_isinstance(block, child_id, block_class_or_mixin): def_id = block.runtime.id_reader.get_definition_id(child_id) type_name = block.runtime.id_reader.get_block_type(def_id) child_class = block.runtime.load_block_type(type_name) return issubclass(child_class, block_class_or_mixin)
[ "\n Efficiently check if a child of an XBlock is an instance of the given class.\n\n Arguments:\n block -- the parent (or ancestor) of the child block in question\n child_id -- the usage key of the child block we are wondering about\n block_class_or_mixin -- We return true if block's child indentified by child_id is an\n instance of this.\n\n This method is equivalent to\n\n isinstance(block.runtime.get_block(child_id), block_class_or_mixin)\n\n but is far more efficient, as it avoids the need to instantiate the child.\n " ]
Please provide a description of the function:def attr(self, *args, **kwargs): kwargs.update({k: bool for k in args}) for key, value in kwargs.items(): if key == "klass": self.attrs["klass"].update(value.split()) elif key == "style": if isinstance(value, str): splitted = iter(re.split(";|:", value)) value = dict(zip(splitted, splitted)) self.attrs["style"].update(value) else: self.attrs[key] = value self._stable = False return self
[ "Add an attribute to the element" ]
Please provide a description of the function:def remove_attr(self, attr): self._stable = False self.attrs.pop(attr, None) return self
[ "Removes an attribute." ]
Please provide a description of the function:def render_attrs(self): ret = [] for k, v in self.attrs.items(): if v: if v is bool: ret.append(" %s" % self._SPECIAL_ATTRS.get(k, k)) else: fnc = self._FORMAT_ATTRS.get(k, None) val = fnc(v) if fnc else v ret.append(' %s="%s"' % (self._SPECIAL_ATTRS.get(k, k), val)) return "".join(ret)
[ "Renders the tag's attributes using the formats and performing special attributes name substitution." ]
Please provide a description of the function:def toggle_class(self, csscl): self._stable = False action = ("add", "remove")[self.has_class(csscl)] return getattr(self.attrs["klass"], action)(csscl)
[ "Same as jQuery's toggleClass function. It toggles the css class on this element." ]
Please provide a description of the function:def add_class(self, cssclass): if self.has_class(cssclass): return self return self.toggle_class(cssclass)
[ "Adds a css class to this element." ]
Please provide a description of the function:def remove_class(self, cssclass): if not self.has_class(cssclass): return self return self.toggle_class(cssclass)
[ "Removes the given class from this element." ]
Please provide a description of the function:def css(self, *props, **kwprops): self._stable = False styles = {} if props: if len(props) == 1 and isinstance(props[0], Mapping): styles = props[0] else: raise WrongContentError(self, props, "Arguments not valid") elif kwprops: styles = kwprops else: raise WrongContentError(self, None, "args OR wkargs are needed") return self.attr(style=styles)
[ "Adds css properties to this element." ]
Please provide a description of the function:def show(self, display=None): self._stable = False if not display: self.attrs["style"].pop("display") else: self.attrs["style"]["display"] = display return self
[ "Removes the display style attribute.\n If a display type is provided " ]
Please provide a description of the function:def toggle(self): self._stable = False return self.show() if self.attrs["style"]["display"] == "none" else self.hide()
[ "Same as jQuery's toggle, toggles the display attribute of this element." ]
Please provide a description of the function:def text(self): texts = [] for child in self.childs: if isinstance(child, Tag): texts.append(child.text()) elif isinstance(child, Content): texts.append(child.render()) else: texts.append(child) return " ".join(texts)
[ "Renders the contents inside this element, without html tags." ]
Please provide a description of the function:def render(self, *args, **kwargs): # args kwargs API provided for last minute content injection # self._reverse_mro_func('pre_render') pretty = kwargs.pop("pretty", False) if pretty and self._stable != "pretty": self._stable = False for arg in args: self._stable = False if isinstance(arg, dict): self.inject(arg) if kwargs: self._stable = False self.inject(kwargs) # If the tag or his contents are not changed and we already have rendered it # with the same attrs we skip all the work if self._stable and self._render: return self._render pretty_pre = pretty_inner = "" if pretty: pretty_pre = "\n" + ("\t" * self._depth) if pretty else "" pretty_inner = "\n" + ("\t" * self._depth) if len(self.childs) > 1 else "" inner = self.render_childs(pretty) if not self._void else "" # We declare the tag is stable and have an official render: tag_data = ( pretty_pre, self._get__tag(), self.render_attrs(), inner, pretty_inner, self._get__tag() )[: 6 - [0, 3][self._void]] self._render = self._template % tag_data self._stable = "pretty" if pretty else True return self._render
[ "Renders the element and all his childrens." ]
Please provide a description of the function:def _make_tempy_tag(self, tag, attrs, void): tempy_tag_cls = getattr(self.tempy_tags, tag.title(), None) if not tempy_tag_cls: unknow_maker = [self.unknown_tag_maker, self.unknown_tag_maker.Void][void] tempy_tag_cls = unknow_maker[tag] attrs = {Tag._TO_SPECIALS.get(k, k): v or True for k, v in attrs} tempy_tag = tempy_tag_cls(**attrs) if not self.current_tag: self.result.append(tempy_tag) if not void: self.current_tag = tempy_tag else: if not tempy_tag._void: self.current_tag(tempy_tag) self.current_tag = self.current_tag.childs[-1]
[ "Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to\n create a custom tag." ]
Please provide a description of the function:def from_string(self, html_string): self._html_parser._reset().feed(html_string) return self._html_parser.result
[ "Parses an html string and returns a list of Tempy trees." ]
Please provide a description of the function:def dump(self, tempy_tree_list, filename, pretty=False): if not filename: raise ValueError('"filename" argument should not be none.') if len(filename.split(".")) > 1 and not filename.endswith(".py"): raise ValueError( '"filename" argument should have a .py extension, if given.' ) if not filename.endswith(".py"): filename += ".py" with open(filename, "w") as f: f.write( "# -*- coding: utf-8 -*-\nfrom tempy import T\nfrom tempy.tags import *\n" ) for tempy_tree in tempy_tree_list: f.write(tempy_tree.to_code(pretty=pretty)) return filename
[ "Dumps a Tempy object to a python file" ]
Please provide a description of the function:def _filter_classes(cls_list, cls_type): for cls in cls_list: if isinstance(cls, type) and issubclass(cls, cls_type): if cls_type == TempyPlace and cls._base_place: pass else: yield cls
[ "Filters a list of classes and yields TempyREPR subclasses" ]
Please provide a description of the function:def _evaluate_tempyREPR(self, child, repr_cls): score = 0 if repr_cls.__name__ == self.__class__.__name__: # One point if the REPR have the same name of the container score += 1 elif repr_cls.__name__ == self.root.__class__.__name__: # One point if the REPR have the same name of the Tempy tree root score += 1 # Add points defined in scorers methods of used TempyPlaces for parent_cls in _filter_classes(repr_cls.__mro__[1:], TempyPlace): for scorer in ( method for method in dir(parent_cls) if method.startswith("_reprscore") ): score += getattr(parent_cls, scorer, lambda *args: 0)( parent_cls, self, child ) return score
[ "Assign a score ito a TempyRepr class.\n The scores depends on the current scope and position of the object in which the TempyREPR is found." ]
Please provide a description of the function:def _search_for_view(self, obj): evaluator = partial(self._evaluate_tempyREPR, obj) sorted_reprs = sorted( _filter_classes(obj.__class__.__dict__.values(), TempyREPR), key=evaluator, reverse=True, ) if sorted_reprs: # If we find some TempyREPR, we return the one with the best score. return sorted_reprs[0] return None
[ "Searches for TempyREPR class declarations in the child's class.\n If at least one TempyREPR is found, it uses the best one to make a Tempy object.\n Otherwise the original object is returned.\n " ]
Please provide a description of the function:def set_charset(self, charset): self.head.charset.attr(charset=charset) return self
[ "Changes the <meta> charset tag (default charset in init is UTF-8)." ]
Please provide a description of the function:def set_description(self, description): self.head.description.attr(content=description) return self
[ "Changes the <meta> description tag." ]
Please provide a description of the function:def set_keywords(self, keywords): self.head.keywords.attr(content=", ".join(keywords)) return self
[ "Changes the <meta> keywords tag." ]
Please provide a description of the function:def set_title(self, title): self.head.title.attr(content=title) return self
[ "Changes the <meta> title tag." ]
Please provide a description of the function:def populate(self, data, resize_x=True, normalize=True): if data is None: raise WidgetDataError( self, "Parameter data should be non-None, to empty the table use TempyTable.clear() or " "pass an empty list.", ) data = copy(data) if not self.body: # Table is empty self(body=Tbody()) self.clear() max_data_x = max(map(len, data)) if not resize_x: self._check_row_size(max_data_x) for t_row, d_row in zip_longest(self.body, data): if not d_row: t_row.remove() else: if not t_row: t_row = Tr().append_to(self.body) if normalize: d_row = AdjustableList(d_row).ljust(max_data_x, None) for t_cell, d_cell in zip_longest(t_row, d_row): if not t_cell and resize_x: t_cell = Td().append_to(t_row) t_cell.empty() if d_cell is not None: t_cell(d_cell) return self
[ "Adds/Replace data in the table.\n data: an iterable of iterables in the form [[col1, col2, col3], [col1, col2, col3]]\n resize_x: if True, changes the x-size of the table according to the given data.\n If False and data have dimensions different from the existing table structure a WidgetDataError is raised.\n normalize: if True all the rows will have the same number of columns, if False, data structure is followed.\n " ]
Please provide a description of the function:def add_row(self, row_data, resize_x=True): if not resize_x: self._check_row_size(row_data) self.body(Tr()(Td()(cell) for cell in row_data)) return self
[ "Adds a row at the end of the table" ]
Please provide a description of the function:def pop_row(self, idr=None, tags=False): idr = idr if idr is not None else len(self.body) - 1 row = self.body.pop(idr) return row if tags else [cell.childs[0] for cell in row]
[ "Pops a row, default the last" ]
Please provide a description of the function:def pop_cell(self, idy=None, idx=None, tags=False): idy = idy if idy is not None else len(self.body) - 1 idx = idx if idx is not None else len(self.body[idy]) - 1 cell = self.body[idy].pop(idx) return cell if tags else cell.childs[0]
[ "Pops a cell, default the last of the last row" ]
Please provide a description of the function:def make_caption(self, caption): if not hasattr(self, "caption"): self(caption=Caption()) return self.caption.empty()(caption)
[ "Adds/Substitutes the table's caption." ]
Please provide a description of the function:def make_scope(self, col_scope_list=None, row_scope_list=None): if col_scope_list is not None and len(col_scope_list) > 0: self.apply_scope(col_scope_list, "col") if row_scope_list is not None and len(row_scope_list) > 0: self.apply_scope(row_scope_list, "row")
[ "Makes scopes and converts Td to Th for given arguments\n which represent lists of tuples (row_index, col_index)" ]
Please provide a description of the function:def populate(self, struct): if struct is None: # Maybe raise? Empty the list? return self if isinstance(struct, (list, set, tuple)): struct = dict(zip_longest(struct, [None])) if not isinstance(struct, dict): raise WidgetDataError( self, "List Input not managed, expected (dict, list), got %s" % type(struct), ) else: if self._typ == Dl: self.__process_dl_struct(struct) else: self.__process_li_struct(struct) return self
[ "Generates the list tree.\n struct: if a list/set/tuple is given, a flat list is generated\n <*l><li>v1</li><li>v2</li>...</*l>\n If the list type is 'Dl' a flat list without definitions is generated\n <*l><dt>v1</dt><dt>v2</dt>...</*l>\n\n If the given struct is a dict, key contaninct lists/tuples/sets/dicts\n will be transformed in nested lists, and so on recursively, using dict\n keys as list items, and dict values as sublists. If type is 'Dl' each\n value will be transformed in definition (or list of definitions)\n except others dict. In that case, it will be transformed in <dfn> tags.\n\n >>> struct = {'ele1': None, 'ele2': ['sub21', 'sub22'], 'ele3': {'sub31': None, 'sub32': None, '_typ': 'Ol'}}\n >>> TempyList(struct=struct)\n <ul>\n <li>ele1</li>\n <li>ele2\n <ul>\n <li>sub21</li>\n <li>sub22</li>\n </ul>\n </li>\n <li>ele3\n <ol>\n <li>sub31</li>\n <li>sub32</li>\n </ol>\n </li>\n </ul>\n " ]
Please provide a description of the function:def render(self, *args, **kwargs): return self.doctype.render() + super().render(*args, **kwargs)
[ "Override so each html page served have a doctype" ]
Please provide a description of the function:def render(self, *args, **kwargs): if not self.childs and "href" in self.attrs: return self.clone()(self.attrs["href"]).render(*args, **kwargs) return super().render(*args, **kwargs)
[ "Override of the rendering so that if the link have no text in it, the href is used inside the <a> tag" ]
Please provide a description of the function:def _find_content(self, cont_name): try: a = self.content_data[cont_name] return a except KeyError: if self.parent: return self.parent._find_content(cont_name) else: # Fallback for no content (Raise NoContent?) return ""
[ "Search for a content_name in the content data, if not found the parent is searched." ]
Please provide a description of the function:def _get_non_tempy_contents(self): for thing in filter( lambda x: not issubclass(x.__class__, DOMElement), self.childs ): yield thing
[ "Returns rendered Contents and non-DOMElement stuff inside this Tag." ]
Please provide a description of the function:def siblings(self): return list(filter(lambda x: id(x) != id(self), self.parent.childs))
[ "Returns all the siblings of this element as a list." ]
Please provide a description of the function:def slice(self, start=None, end=None, step=None): return self.childs[start:end:step]
[ "Slice of this element's childs as childs[start:end:step]" ]
Please provide a description of the function:def bft(self): queue = deque([self]) while queue: node = queue.pop() yield node if hasattr(node, "childs"): queue.extendleft(node.childs)
[ " Generator that returns each element of the tree in Breadth-first order" ]
Please provide a description of the function:def dfs_preorder(self, reverse=False): stack = deque() stack.append(self) while stack: node = stack.pop() yield node if hasattr(node, "childs"): if reverse: stack.extend(node.childs) else: stack.extend(node.childs[::-1])
[ "Generator that returns each element of the tree in Preorder order.\n Keyword arguments:\n reverse -- if true, the search is done from right to left." ]
Please provide a description of the function:def dfs_inorder(self, reverse=False): stack = deque() visited = set() visited.add(self) if reverse: stack.append(self.childs[0]) stack.append(self) stack.extend(self.childs[1:]) else: stack.extend(self.childs[1:]) stack.append(self) stack.append(self.childs[0]) while stack: node = stack.pop() if node in visited or not node.childs: yield node else: stack.append(node) visited.add(node) if hasattr(node, "childs"): if reverse: stack.extend(node.childs) else: stack.extend(node.childs[::-1])
[ "Generator that returns each element of the tree in Inorder order.\n Keyword arguments:\n reverse -- if true, the search is done from right to left." ]
Please provide a description of the function:def dfs_postorder(self, reverse=False): stack = deque() stack.append(self) visited = set() while stack: node = stack.pop() if node in visited: yield node else: visited.add(node) stack.append(node) if hasattr(node, "childs"): if reverse: stack.extend(node.childs) else: stack.extend(node.childs[::-1])
[ "Generator that returns each element of the tree in Postorder order.\n Keyword arguments:\n reverse -- if true, the search is done from right to left." ]
Please provide a description of the function:def content_receiver(reverse=False): def _receiver(func): @wraps(func) def wrapped(inst, *tags, **kwtags): verse = (1, -1)[int(reverse)] kwtags = kwtags.items() i = 0 for typ in (tags, kwtags)[::verse]: for item in typ: if typ is kwtags: name, item = item else: name, item = None, item if isinstance(item, DOMElement) and name: # Is the DOMGroup is a single DOMElement and we have a name we set his name accordingly item._name = name inst._stable = False func(inst, i, item, name) i += 1 return inst return wrapped return _receiver
[ "Decorator for content adding methods.\n Takes args and kwargs and calls the decorated method one time for each argument provided.\n The reverse parameter should be used for prepending (relative to self) methods.\n " ]
Please provide a description of the function:def _insert(self, dom_group, idx=None, prepend=False, name=None): if idx and idx < 0: idx = 0 if prepend: idx = 0 else: idx = idx if idx is not None else len(self.childs) if dom_group is not None: if not isinstance(dom_group, Iterable) or isinstance( dom_group, (DOMElement, str) ): dom_group = [dom_group] for i_group, elem in enumerate(dom_group): if elem is not None: # Element insertion in this DOMElement childs self.childs.insert(idx + i_group, elem) # Managing child attributes if needed if issubclass(elem.__class__, DOMElement): elem.parent = self if name: setattr(self, name, elem)
[ "Inserts a DOMGroup inside this element.\n If provided at the given index, if prepend at the start of the childs list, by default at the end.\n If the child is a DOMElement, correctly links the child.\n If the DOMGroup have a name, an attribute containing the child is created in this instance.\n " ]
Please provide a description of the function:def after(self, i, sibling, name=None): self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name) return self
[ "Adds siblings after the current tag." ]
Please provide a description of the function:def prepend(self, _, child, name=None): self._insert(child, prepend=True, name=name) return self
[ "Adds childs to this tag, starting from the first position." ]
Please provide a description of the function:def append(self, _, child, name=None): self._insert(child, name=name) return self
[ "Adds childs to this tag, after the current existing childs." ]
Please provide a description of the function:def wrap(self, other): if other.childs: raise TagError(self, "Wrapping in a non empty Tag is forbidden.") if self.parent: self.before(other) self.parent.pop(self._own_index) other.append(self) return self
[ "Wraps this element inside another empty tag." ]
Please provide a description of the function:def wrap_many(self, *args, strict=False): for arg in args: is_elem = arg and isinstance(arg, DOMElement) is_elem_iter = ( not is_elem and arg and isinstance(arg, Iterable) and isinstance(iter(arg).__next__(), DOMElement) ) if not (is_elem or is_elem_iter): raise WrongArgsError( self, "Argument {} is not DOMElement nor iterable of DOMElements".format( arg ), ) wcopies = [] failure = [] def wrap_next(tag, idx): nonlocal wcopies, failure next_copy = self.__copy__() try: return next_copy.wrap(tag) except TagError: failure.append(idx) return next_copy for arg_idx, arg in enumerate(args): if isinstance(arg, DOMElement): wcopies.append(wrap_next(arg, (arg_idx, -1))) else: iter_wcopies = [] for iter_idx, t in enumerate(arg): iter_wcopies.append(wrap_next(t, (arg_idx, iter_idx))) wcopies.append(type(arg)(iter_wcopies)) if failure and strict: raise TagError( self, "Wrapping in a non empty Tag is forbidden, failed on arguments " + ", ".join( list( map( lambda idx: str(idx[0]) if idx[1] == -1 else "[{1}] of {0}".format(*idx), failure, ) ) ), ) return wcopies
[ "Wraps different copies of this element inside all empty tags\n listed in params or param's (non-empty) iterators.\n\n Returns list of copies of this element wrapped inside args\n or None if not succeeded, in the same order and same structure,\n i.e. args = (Div(), (Div())) -> value = (A(...), (A(...)))\n\n If on some args it must raise TagError, it will only if strict is True,\n otherwise it will do nothing with them and return Nones on their positions" ]
Please provide a description of the function:def replace_with(self, other): self.after(other) self.parent.pop(self._own_index) return other
[ "Replace this element with the given DOMElement." ]
Please provide a description of the function:def remove(self): if self._own_index is not None and self.parent: self.parent.pop(self._own_index) return self
[ "Detach this element from his father." ]
Please provide a description of the function:def _detach_childs(self, idx_from=None, idx_to=None): idx_from = idx_from or 0 idx_to = idx_to or len(self.childs) removed = self.childs[idx_from:idx_to] for child in removed: if issubclass(child.__class__, DOMElement): child.parent = None self.childs[idx_from:idx_to] = [] return removed
[ "Moves all the childs to a new father" ]
Please provide a description of the function:def move(self, new_father, idx=None, prepend=None, name=None): self.parent.pop(self._own_index) new_father._insert(self, idx=idx, prepend=prepend, name=name) new_father._stable = False return self
[ "Moves this element from his father to the given one." ]
Please provide a description of the function:def pop(self, arg=None): self._stable = False if arg is None: arg = len(self.childs) - 1 if isinstance(arg, int): try: result = self.childs.pop(arg) except IndexError: raise DOMModByIndexError(self, "Given index invalid.") if isinstance(result, DOMElement): result.parent = None else: result = [] if isinstance(arg, str): arg = [arg] for x in arg: try: result.append(getattr(self, x)) except AttributeError: raise DOMModByKeyError( self, "Given search key invalid. No child found." ) if result: for x in result: self.childs.remove(x) if isinstance(x, DOMElement): x.parent = False return result
[ "Removes the child at given position or by name (or name iterator).\n if no argument is given removes the last." ]
Please provide a description of the function:def data(self, key=None, **kwargs): self.content_data.update(kwargs) if key: return self.content_data[key] if not kwargs: return self.content_data return self
[ "Adds or retrieve extra data to this element, this data will not be rendered.\n Every tag have a _data attribute (dict), if key is given _data[key] is returned.\n Kwargs are used to udpate this Tag's _data." ]
Please provide a description of the function:def inject(self, contents=None, **kwargs): if contents and not isinstance(contents, dict): raise WrongContentError(self, contents, "contents should be a dict") self._stable = False if not contents: contents = {} if kwargs: contents.update(kwargs) self.content_data.update(contents) return self
[ "\n Adds content data in this element. This will be used in the rendering of this element's childs.\n Multiple injections on the same key will override the content (dict.update behavior).\n " ]
Please provide a description of the function:def send(self, message): url = '{0}message'.format(self.remote) data = self._wrap_post_data(content=message) res = requests.post(url, data=data, timeout=self.timeout) if res.status_code == requests.codes.ok: res_data = json.loads(self._convert_bytes(res.content)) if res_data.get('status') == STATUS_SUCCESS: return True, res_data.get('message') return False, res_data.get('message') res.raise_for_status() return False, 'Request or Response Error'
[ "\n 发送基本文字消息\n\n :param message: (必填|str) - 需要发送的文本消息\n :return: * status:发送状态,True 发送成,False 发送失败\n * message:发送失败详情\n " ]
Please provide a description of the function:def delay_send(self, content, time, title='', remind=DEFAULT_REMIND_TIME): url = '{0}delay_message'.format(self.remote) if isinstance(time, (datetime.datetime, datetime.date)): time = time.strftime('%Y-%m-%d %H:%M:%S') if isinstance(remind, datetime.timedelta): remind = int(remind.total_seconds()) if not isinstance(remind, int): raise ValueError data = self._wrap_post_data(title=title, content=content, time=time, remind=remind) res = requests.post(url, data=data, timeout=self.timeout) if res.status_code == requests.codes.ok: res_data = json.loads(self._convert_bytes(res.content)) if res_data.get('status') == STATUS_SUCCESS: return True, res_data.get('message') return False, res_data.get('message') res.raise_for_status() return False, 'Request or Response Error'
[ "\n 发送延时消息\n\n :param content: (必填|str) - 需要发送的消息内容\n :param time: (必填|str|datetime) - 发送消息的开始时间,支持 datetime.date、datetime.datetime 格式或者如 '2017-05-21 10:00:00' 的字符串\n :param title: (选填|str) - 需要发送的消息标题\n :param remind: (选填|int|datetime.timedelta) - 消息提醒时移,默认 1 小时,即早于 time 值 1 小时发送消息提醒, 支持 integer(毫秒) 或 datetime.timedelta\n :return: * status:发送状态,True 发送成,False 发送失败\n * message:发送失败详情\n " ]
Please provide a description of the function:def periodic_send(self, content, interval, title=''): url = '{0}periodic_message'.format(self.remote) if isinstance(interval, datetime.timedelta): interval = int(interval.total_seconds()) if not isinstance(interval, int): raise ValueError data = self._wrap_post_data(title=title, content=content, interval=interval) res = requests.post(url, data, timeout=self.timeout) if res.status_code == requests.codes.ok: res_data = json.loads(self._convert_bytes(res.content)) if res_data.get('status') == STATUS_SUCCESS: return True, res_data.get('message') return False, res_data.get('message') res.raise_for_status() return False, 'Request or Response Error'
[ "\n 发送周期消息\n\n :param content: (必填|str) - 需要发送的消息内容\n :param interval: (必填|int|datetime.timedelta) - 发送消息间隔时间,支持 datetime.timedelta 或 integer 表示的秒数\n :param title: (选填|str) - 需要发送的消息标题\n :return: * status:发送状态,True 发送成,False 发送失败\n * message:发送失败详情\n " ]
Please provide a description of the function:def send_to(self, content, search): url = '{0}send_to_message'.format(self.remote) if isinstance(search, dict): search = json.dumps(search) elif isinstance(search, list): search = reduce(lambda x, y: '{0} {1}'.format(x, y), search) data = self._wrap_post_data(content=content, search=search) res = requests.post(url, data=data, timeout=self.timeout) if res.status_code == requests.codes.ok: res_data = json.loads(self._convert_bytes(res.content)) if res_data.get('status') == STATUS_SUCCESS: return True, res_data.get('message') return False, res_data.get('message') res.raise_for_status() return False, 'Request or Response Error'
[ "\n 向指定好友发送消息\n\n :param content: (必填|str) - 需要发送的消息内容\n :param search: (必填|str|dict|list)-搜索对象,同 wxpy.chats.search 使用方法一样。例如,可以使用字符串进行搜索好友或群,或指定具体属性搜索,如 puid=xxx 的字典\n :return: * status:发送状态,True 发送成,False 发送失败\n * message:发送失败详情\n " ]
Please provide a description of the function:def _read_config_list(): with codecs.open('conf.ini', 'w+', encoding='utf-8') as f1: conf_list = [conf for conf in f1.read().split('\n') if conf != ''] return conf_list
[ "\n 配置列表读取\n " ]
Please provide a description of the function:def write_config(name, value): name = name.lower() new = True conf_list = _read_config_list() for i, conf in enumerate(conf_list): if conf.startswith(name): conf_list[i] = '{0}={1}'.format(name, value) new = False break if new: conf_list.append('{0}={1}'.format(name, value)) with codecs.open('conf.ini', 'w+', encoding='utf-8') as f1: for conf in conf_list: f1.write(conf + '\n') return True
[ "\n 配置写入\n " ]
Please provide a description of the function:def read_config(name): name = name.lower() conf_list = _read_config_list() for conf in conf_list: if conf.startswith(name): return conf.split('=')[1].split('#')[0].strip() return None
[ "\n 配置读取\n " ]
Please provide a description of the function:def init_receivers(self, receivers): if not receivers: self.default_receiver = self.bot.file_helper return True if isinstance(receivers, list): self.default_receiver = receivers[0] for receiver in receivers: if self.bot.puid_map: self.receivers[receiver.puid] = receiver self.receivers[receiver.name] = receiver else: self.default_receiver = receivers if self.bot.puid_map: self.receivers[receivers.puid] = receivers self.receivers[receivers.name] = receivers
[ "\n 初始化 receivers\n " ]
Please provide a description of the function:def send_msg(self, msg): for receiver in msg.receivers: current_receiver = self.receivers.get(receiver, self.default_receiver) current_receiver.send_msg(msg)
[ "\n wxpy 发送文本消息的基本封装,这里会进行消息 receiver 识别分发\n " ]
Please provide a description of the function:def render_message(self): message = None if self.title: message = '标题:{0}'.format(self.title) if self.message_time: message = '{0}\n时间:{1}'.format(message, self.time) if message: message = '{0}\n内容:{1}'.format(message, self.content) else: message = self.content return message
[ "\n 渲染消息\n\n :return: 渲染后的消息\n " ]
Please provide a description of the function:def generate_run_info(): uptime = datetime.datetime.now() - datetime.datetime.fromtimestamp(glb.run_info.create_time()) memory_usage = glb.run_info.memory_info().rss msg = '[当前时间] {now:%H:%M:%S}\n[运行时间] {uptime}\n[内存占用] {memory}\n[发送消息] {messages}'.format( now=datetime.datetime.now(), uptime=str(uptime).split('.')[0], memory='{:.2f} MB'.format(memory_usage / 1024 ** 2), messages=len(glb.wxbot.bot.messages) ) return msg
[ "\n 获取当前运行状态\n " ]