text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _eratosthenes(): """Yields the sequence of prime numbers via the Sieve of Eratosthenes."""
d = {} # map each composite integer to its first-found prime factor for q in count(2): # q gets 2, 3, 4, 5, ... ad infinitum p = d.pop(q, None) if p is None: # q not a key in D, so q is prime, therefore, yield it yield q # mark q squared as not-prime (with ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def atoms_order(self): """ Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs """
if not len(self): # for empty containers return {} elif len(self) == 1: # optimize single atom containers return dict.fromkeys(self, 2) params = {n: (int(node), tuple(sorted(int(edge) for edge in self._adj[n].values()))) for n, node in self.atoms()} ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_manual(cls, pawn_value, knight_value, bishop_value, rook_value, queen_value, king_value): """ Manual init method for external piece values :type: PAWN_V...
piece_values = cls() piece_values.PAWN_VALUE = pawn_value piece_values.KNIGHT_VALUE = knight_value piece_values.BISHOP_VALUE = bishop_value piece_values.ROOK_VALUE = rook_value piece_values.QUEEN_VALUE = queen_value piece_values.KING_VALUE = king_value re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def val(self, piece, ref_color): """ Finds value of ``Piece`` :type: piece: Piece :type: ref_color: Color :rtype: int """
if piece is None: return 0 if ref_color == piece.color: const = 1 else: const = -1 if isinstance(piece, Pawn): return self.PAWN_VALUE * const elif isinstance(piece, Queen): return self.QUEEN_VALUE * const elif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field_cache(self, cache_type='es'): """Return a list of fields' mappings"""
if cache_type == 'kibana': try: search_results = urlopen(self.get_url).read().decode('utf-8') except HTTPError: # as e: # self.pr_err("get_field_cache(kibana), HTTPError: %s" % e) return [] index_pattern = json.loads(search_re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_field_cache(self, field_cache): """Where field_cache is a list of fields' mappings"""
index_pattern = self.field_cache_to_index_pattern(field_cache) # self.pr_dbg("request/post: %s" % index_pattern) resp = requests.post(self.post_url, data=index_pattern).text # resp = {"_index":".kibana","_type":"index-pattern","_id":"aaa*","_version":1,"created":true} # noqa re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def field_cache_to_index_pattern(self, field_cache): """Return a .kibana index-pattern doc_type"""
mapping_dict = {} mapping_dict['customFormats'] = "{}" mapping_dict['title'] = self.index_pattern # now post the data into .kibana mapping_dict['fields'] = json.dumps(field_cache, separators=(',', ':')) # in order to post, we need to create the post string mappin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_mapping(self, m): """Assert minimum set of fields in cache, does not validate contents"""
if 'name' not in m: self.pr_dbg("Missing %s" % "name") return False # self.pr_dbg("Checking %s" % m['name']) for x in ['analyzed', 'indexed', 'type', 'scripted', 'count']: if x not in m or m[x] == "": self.pr_dbg("Missing %s" % x) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_index_mappings(self, index): """Converts all index's doc_types to .kibana"""
fields_arr = [] for (key, val) in iteritems(index): # self.pr_dbg("\tdoc_type: %s" % key) doc_mapping = self.get_doc_type_mappings(index[key]) # self.pr_dbg("\tdoc_mapping: %s" % doc_mapping) if doc_mapping is None: return None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_doc_type_mappings(self, doc_type): """Converts all doc_types' fields to .kibana"""
doc_fields_arr = [] found_score = False for (key, val) in iteritems(doc_type): # self.pr_dbg("\t\tfield: %s" % key) # self.pr_dbg("\tval: %s" % val) add_it = False retdict = {} # _ are system if not key.startswith('_'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field_mappings(self, field): """Converts ES field mappings to .kibana field mappings"""
retdict = {} retdict['indexed'] = False retdict['analyzed'] = False for (key, val) in iteritems(field): if key in self.mappings: if (key == 'type' and (val == "long" or val == "integer" or val == "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_kibana_cache_incomplete(self, es_cache, k_cache): """Test if k_cache is incomplete Assume k_cache is always correct, but could be missing new fields that ...
# convert list into dict, with each item's ['name'] as key k_dict = {} for field in k_cache: # self.pr_dbg("field: %s" % field) k_dict[field['name']] = field for ign_f in self.mappings_ignore: k_dict[field['name']][ign_f] = 0 es_dict =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_to_compare_dict(self, list_form): """Convert list into a data structure we can query easier"""
compare_dict = {} for field in list_form: if field['name'] in compare_dict: self.pr_dbg("List has duplicate field %s:\n%s" % (field['name'], compare_dict[field['name']])) if compare_dict[field['name']] != field: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_field_caches(self, replica, original): """Verify original is subset of replica"""
if original is None: original = [] if replica is None: replica = [] self.pr_dbg("Comparing orig with %s fields to replica with %s fields" % (len(original), len(replica))) # convert list into dict, with each item's ['name'] as key orig ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_daemon_thread(target, args=()): """starts a deamon thread for a given target function and arguments."""
th = Thread(target=target, args=args) th.daemon = True th.start() return th
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_dict_keys(d, prefix=""): """returns all the keys in a dictionary. ['a', 'a.b', 'a.b.c', 'a.b.b'] """
keys = [] for k, v in d.iteritems(): fqk = '%s%s' % (prefix, k) keys.append(fqk) if isinstance(v, dict): keys.extend(serialize_dict_keys(v, prefix="%s." % fqk)) return keys
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_user(self, user): """ Writes user data to session. Args: user: User object """
self.session['user_id'] = user.key self.session['user_data'] = user.clean_value() role = self.get_role() # TODO: this should be remembered from previous login # self.session['role_data'] = default_role.clean_value() self.session['role_id'] = role.key self.current...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains_opposite_color_piece(self, square, position): """ Finds if square on the board is occupied by a ``Piece`` belonging to the opponent. :type: square: ...
return not position.is_square_empty(square) and \ position.piece_at_square(square).color != self.color
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gettext(message, domain=DEFAULT_DOMAIN): """Mark a message as translateable, and translate it. All messages in the application that are translateable should ...
if six.PY2: return InstalledLocale._active_catalogs[domain].ugettext(message) else: return InstalledLocale._active_catalogs[domain].gettext(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gettext_lazy(message, domain=DEFAULT_DOMAIN): """Mark a message as translatable, but delay the translation until the message is used. Sometimes, there are so...
return LazyProxy(gettext, message, domain=domain, enable_cache=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ngettext(singular, plural, n, domain=DEFAULT_DOMAIN): """Mark a message as translateable, and translate it considering plural forms. Some messages may need t...
if six.PY2: return InstalledLocale._active_catalogs[domain].ungettext(singular, plural, n) else: return InstalledLocale._active_catalogs[domain].ngettext(singular, plural, n)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ngettext_lazy(singular, plural, n, domain=DEFAULT_DOMAIN): """Mark a message with plural forms translateable, and delay the translation until the message is ...
return LazyProxy(ngettext, singular, plural, n, domain=domain, enable_cache=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_language(cls, language_code): """Install the translations for language specified by `language_code`. If we don't have translations for this language,...
# Skip if the language is already installed if language_code == cls.language: return try: cls._active_catalogs = cls._translation_catalogs[language_code] cls.language = language_code log.debug('Installed language %s', language_code) except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_locale(cls, locale_code, locale_type): """Install the locale specified by `language_code`, for localizations of type `locale_type`. If we can't perfo...
# Skip if the locale is already installed if locale_code == getattr(cls, locale_type): return try: # We create a Locale instance to see if the locale code is supported locale = Locale(locale_code) log.debug('Installed locale %s', locale_code) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rotate_vector(x, y, x2, y2, x1, y1): """ rotate x,y vector over x2-x1, y2-y1 angle """
angle = atan2(y2 - y1, x2 - x1) cos_rad = cos(angle) sin_rad = sin(angle) return cos_rad * x + sin_rad * y, -sin_rad * x + cos_rad * y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_index(self, index): """ Returns the entry specified by index Note that the table is 1-based ie an index of 0 is invalid. This is due to the fact that ...
index -= 1 if 0 <= index < len(CocaineHeaders.STATIC_TABLE): return CocaineHeaders.STATIC_TABLE[index] index -= len(CocaineHeaders.STATIC_TABLE) if 0 <= index < len(self.dynamic_entries): return self.dynamic_entries[index] raise InvalidTableIndex("Invalid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, name, value): """ Adds a new entry to the table We reduce the table size if the entry will make the table size greater than maxsize. """
# We just clear the table if the entry is too big size = table_entry_size(name, value) if size > self._maxsize: self.dynamic_entries.clear() self._current_size = 0 # Add new entry if the table actually has a size elif self._maxsize > 0: self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, name, value): """ Searches the table for the entry specified by name and value Returns one of the following: - ``None``, no match at all - ``(in...
partial = None header_name_search_result = CocaineHeaders.STATIC_TABLE_MAPPING.get(name) if header_name_search_result: index = header_name_search_result[1].get(value) if index is not None: return index, name, value partial = (header_name_sear...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shrink(self): """ Shrinks the dynamic table to be at or below maxsize """
cursize = self._current_size while cursize > self._maxsize: name, value = self.dynamic_entries.pop() cursize -= table_entry_size(name, value) self._current_size = cursize
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_print(ustring, errors='replace', **kwargs): """ Safely print a unicode string """
encoding = sys.stdout.encoding or 'utf-8' if sys.version_info[0] == 3: print(ustring, **kwargs) else: bytestr = ustring.encode(encoding, errors=errors) print(bytestr, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_permissions(self): """Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects fie...
# Get the role that was selected in the CRUD view key = self.current.input['object_id'] self.current.task_data['role_id'] = key role = RoleModel.objects.get(key=key) # Get the cached permission tree, or build a new one if there is none cached # TODO: Add an extra view in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _permission_trees(permissions): """Get the cached permission tree, or build a new one if necessary."""
treecache = PermissionTreeCache() cached = treecache.get() if not cached: tree = PermissionTreeBuilder() for permission in permissions: tree.insert(permission) result = tree.serialize() treecache.set(result) return resu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _traverse_tree(tree, path): """Traverses the permission tree, returning the permission at given permission path."""
path_steps = (step for step in path.split('.') if step != '') # Special handling for first step, because the first step isn't under 'objects' first_step = path_steps.next() subtree = tree[first_step] for step in path_steps: subtree = subtree['children'][step] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_subtree(self, subtree): """Recursively format all subtrees."""
subtree['children'] = list(subtree['children'].values()) for child in subtree['children']: self._format_subtree(child) return subtree
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_change(self): """Applies changes to the permissions of the role. To make a change to the permission of the role, a request in the following format shou...
changes = self.input['change'] key = self.current.task_data['role_id'] role = RoleModel.objects.get(key=key) for change in changes: permission = PermissionModel.objects.get(code=change['id']) if change['checked'] is True: role.add_permission(permi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, data): """ write single molecule into file """
m = self._convert_structure(data) self._file.write(self._format_mol(*m)) self._file.write('M END\n') for k, v in data.meta.items(): self._file.write(f'> <{k}>\n{v}\n') self._file.write('$$$$\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_workflow_to_cache(self, serialized_wf_instance): """ If we aren't come to the end of the wf, saves the wf state and task_data to cache Task_data items t...
# self.current.task_data['flow'] = None task_data = self.current.task_data.copy() for k, v in list(task_data.items()): if k.startswith('_'): del task_data[k] if 'cmd' in task_data: del task_data['cmd'] self.wf_state.update({'step': serial...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_pool_context(self): # TODO: Add in-process caching """ Builds context for the WF pool. Returns: Context dict. """
context = {self.current.lane_id: self.current.role, 'self': self.current.role} for lane_id, role_id in self.current.pool.items(): if role_id: context[lane_id] = lazy_object_proxy.Proxy( lambda: self.role_model(super_context).objects.get(role_id)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_workflow_from_cache(self): """ loads the serialized wf state and data from cache updates the self.current.task_data """
if not self.current.new_token: self.wf_state = self.current.wf_cache.get(self.wf_state) self.current.task_data = self.wf_state['data'] self.current.set_client_cmds() self.current.pool = self.wf_state['pool'] return self.wf_state['step']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_workflow(self): """ Serializes the current WF. Returns: WF state data. """
self.workflow.refresh_waiting_tasks() return CompactWorkflowSerializer().serialize_workflow(self.workflow, include_spec=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_workflow_path(self): """ Tries to find the path of the workflow diagram file in `WORKFLOW_PACKAGES_PATHS`. Returns: Path of the workflow spec file (BPMN...
for pth in settings.WORKFLOW_PACKAGES_PATHS: path = "%s/%s.bpmn" % (pth, self.current.workflow_name) if os.path.exists(path): return path err_msg = "BPMN file cannot found: %s" % self.current.workflow_name log.error(err_msg) raise RuntimeError(err...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_worfklow_spec(self): """ Generates and caches the workflow spec package from BPMN diagrams that read from disk Returns: SpiffWorkflow Spec object. """
# TODO: convert from in-process to redis based caching if self.current.workflow_name not in self.workflow_spec_cache: # path = self.find_workflow_path() # spec_package = InMemoryPackager.package_in_memory(self.current.workflow_name, path) # spec = BpmnSerializer().de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save_or_delete_workflow(self): """ Calls the real save method if we pass the beggining of the wf """
if not self.current.task_type.startswith('Start'): if self.current.task_name.startswith('End') and not self.are_we_in_subprocess(): self.wf_state['finished'] = True self.wf_state['finish_date'] = datetime.now().strftime( settings.DATETIME_DEFAULT_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_engine(self, **kwargs): """ Initializes the workflow with given request, response objects and diagram name. Args: session: input: workflow_name (str): ...
self.current = WFCurrent(**kwargs) self.wf_state = {'in_external': False, 'finished': False} if not self.current.new_token: self.wf_state = self.current.wf_cache.get(self.wf_state) self.current.workflow_name = self.wf_state['name'] # if we have a pre-selected...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_wf_state_log(self): """ Logs the state of workflow and content of task_data. """
output = '\n- - - - - -\n' output += "WORKFLOW: %s ( %s )" % (self.current.workflow_name.upper(), self.current.workflow.name) output += "\nTASK: %s ( %s )\n" % (self.current.task_name, self.current.task_type) output += "DATA:" for k, v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_from_external_to_main_wf(self): """ Main workflow switcher. This method recreates main workflow from `main wf` dict which was set by external workflow...
# in external assigned as True in switch_to_external_wf. # external_wf should finish EndEvent and it's name should be # also EndEvent for switching again to main wf. if self.wf_state['in_external'] and self.current.task_type == 'EndEvent' and \ self.current.task_name ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_to_external_wf(self): """ External workflow switcher. This method copies main workflow information into a temporary dict `main_wf` and makes external ...
# External WF name should be stated at main wf diagram and type should be service task. if (self.current.task_type == 'ServiceTask' and self.current.task.task_spec.type == 'external'): log.debug("Entering to EXTERNAL WF") # Main wf information is copied to mai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clear_current_task(self): """ Clear tasks related attributes, checks permissions While switching WF to WF, authentication and permissions are checked for ne...
self.current.task_name = None self.current.task_type = None self.current.task = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Main loop of the workflow engine - Updates ::class:`~WFCurrent` object. - Checks for Permissions. - Activates all READY tasks. - Runs referenc...
# FIXME: raise if first task after line change isn't a UserTask # FIXME: raise if last task of a workflow is a UserTask # actually this check should be done at parser is_lane_changed = False while self._should_we_run(): self.check_for_rerun_user_task() t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_lang(self): """Switch to the language of the current user. If the current language is already the specified one, nothing will be done. """
locale = self.current.locale translation.InstalledLocale.install_language(locale['locale_language']) translation.InstalledLocale.install_locale(locale['locale_datetime'], 'datetime') translation.InstalledLocale.install_locale(locale['locale_number'], 'number')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def catch_lane_change(self): """ trigger a lane_user_change signal if we switched to a new lane and new lane's user is different from current one """
if self.current.lane_name: if self.current.old_lane and self.current.lane_name != self.current.old_lane: # if lane_name not found in pool or it's user different from the current(old) user if (self.current.lane_id not in self.current.pool or ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_workflow_messages(self): """ Transmits client message that defined in a workflow task's inputOutput extension .. code-block:: xml <bpmn2:extensionEleme...
if 'client_message' in self.current.spec.data: m = self.current.spec.data['client_message'] self.current.msg_box(title=m.get('title'), msg=m.get('body'), typ=m.get('type', 'info'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_activity(self): """ runs the method that referenced from current task """
activity = self.current.activity if activity: if activity not in self.wf_activities: self._load_activity(activity) self.current.log.debug( "Calling Activity %s from %s" % (activity, self.wf_activities[activity])) self.wf_activities[sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _import_object(self, path, look_for_cls_method): """ Imports the module that contains the referenced method. Args: path: python path of class/function look_f...
last_nth = 2 if look_for_cls_method else 1 path = path.split('.') module_path = '.'.join(path[:-last_nth]) class_name = path[-last_nth] module = importlib.import_module(module_path) if look_for_cls_method and path[-last_nth:][0] == path[-last_nth]: class_meth...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_activity(self, activity): """ Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path. """
fpths = [] full_path = '' errors = [] paths = settings.ACTIVITY_MODULES_IMPORT_PATHS number_of_paths = len(paths) for index_no in range(number_of_paths): full_path = "%s.%s" % (paths[index_no], activity) for look4kls in (0, 1): try...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_lane_permission(self): """ One or more permissions can be associated with a lane of a workflow. In a similar way, a lane can be restricted with rel...
# TODO: Cache lane_data in app memory if self.current.lane_permission: log.debug("HAS LANE PERM: %s" % self.current.lane_permission) perm = self.current.lane_permission if not self.current.has_permission(perm): raise HTTPError(403, "You don't have req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_wf_finalization(self): """ Removes the ``token`` key from ``current.output`` if WF is over. """
if ((not self.current.flow_enabled or ( self.current.task_type.startswith('End') and not self.are_we_in_subprocess())) and 'token' in self.current.output): del self.current.output['token']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_rdkit_molecule(data): """ RDKit molecule object to MoleculeContainer converter """
m = MoleculeContainer() atoms, mapping = [], [] for a in data.GetAtoms(): atom = {'element': a.GetSymbol(), 'charge': a.GetFormalCharge()} atoms.append(atom) mapping.append(a.GetAtomMapNum()) isotope = a.GetIsotope() if isotope: atom['isotope'] = isotope...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_rdkit_molecule(data): """ MoleculeContainer to RDKit molecule object converter """
mol = RWMol() conf = Conformer() mapping = {} is_3d = False for n, a in data.atoms(): ra = Atom(a.number) ra.SetAtomMapNum(n) if a.charge: ra.SetFormalCharge(a.charge) if a.isotope != a.common_isotope: ra.SetIsotope(a.isotope) if a.rad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __dfs(self, start, weights, depth_limit): """ modified NX dfs """
adj = self._adj stack = [(start, depth_limit, iter(sorted(adj[start], key=weights)))] visited = {start} disconnected = defaultdict(list) edges = defaultdict(list) while stack: parent, depth_now, children = stack[-1] try: child = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_args_parser(): """Return a parser for command line options."""
parser = argparse.ArgumentParser( description='Marabunta: Migrating ants for Odoo') parser.add_argument('--migration-file', '-f', action=EnvDefault, envvar='MARABUNTA_MIGRATION_FILE', required=True, help='Th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_parse_args(cls, args): """Constructor from command line args. :param args: parse command line arguments :type args: argparse.ArgumentParser """
return cls(args.migration_file, args.database, db_user=args.db_user, db_password=args.db_password, db_port=args.db_port, db_host=args.db_host, mode=args.mode, allow_serie=args.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_current(self, current): """ Creates some aliases for attributes of ``current``. Args: current: :attr:`~zengine.engine.WFCurrent` object. """
self.current = current self.input = current.input # self.req = current.request # self.resp = current.response self.output = current.output self.cmd = current.task_data['cmd'] if self.cmd and NEXT_CMD_SPLITTER in self.cmd: self.cmd, self.next_cmd = se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form_out(self, _form=None): """ Renders form. Applies form modifiers, then writes result to response payload. If supplied, given form object instance will be...
_form = _form or self.object_form self.output['forms'] = _form.serialize() self._add_meta_props(_form) self.output['forms']['grouping'] = _form.Meta.grouping self.output['forms']['constraints'] = _form.Meta.constraints self._patch_form(self.output['forms']) self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Creates new permissions. """
from pyoko.lib.utils import get_object_from_path from zengine.config import settings model = get_object_from_path(settings.PERMISSION_MODEL) perm_provider = get_object_from_path(settings.PERMISSION_PROVIDER) existing_perms = [] new_perms = [] for code, name, desc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Creates user, encrypts password. """
from zengine.models import User user = User(username=self.manager.args.username, superuser=self.manager.args.super) user.set_password(self.manager.args.password) user.save() print("New user created with ID: %s" % user.key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_domain(mapping): """Prepare a helper dictionary for the domain to temporarily hold some information."""
# Parse the domain-directory mapping try: domain, dir = mapping.split(':') except ValueError: print("Please provide the sources in the form of '<domain>:<directory>'") sys.exit(1) try: default_language = settings.TRANSLATION_DOMAINS[domai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_domains(domains): """Check that all domains specified in the settings was provided in the options."""
missing = set(settings.TRANSLATION_DOMAINS.keys()) - set(domains.keys()) if missing: print('The following domains have been set in the configuration, ' 'but their sources were not provided, use the `--source` ' 'option to specify their sources: {domains}'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_translations(self, domains): """Extract the translations into `.pot` files"""
for domain, options in domains.items(): # Create the extractor extractor = babel_frontend.extract_messages() extractor.initialize_options() # The temporary location to write the `.pot` file extractor.output_file = options['pot'] # Add the ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_update_po_files(self, domains): """Update or initialize the `.po` translation files"""
for language in settings.TRANSLATIONS: for domain, options in domains.items(): if language == options['default']: continue # Default language of the domain doesn't need translations if os.path.isfile(_po_path(language, domain)): # If the translat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cleanup(self, domains): """Remove the temporary '.pot' files that were created for the domains."""
for option in domains.values(): try: os.remove(option['pot']) except (IOError, OSError): # It is not a problem if we can't actually remove the temporary file pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ read workflows, checks if it's updated, tries to update if there aren't any running instances of that wf """
from zengine.lib.cache import WFSpecNames if self.manager.args.clear: self._clear_models() return if self.manager.args.wf_path: paths = self.get_wf_from_path(self.manager.args.wf_path) else: paths = self.get_workflows() self.cou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_workflows(self): """ Scans and loads all wf found under WORKFLOW_PACKAGES_PATHS Yields: XML content of diagram file """
for pth in settings.WORKFLOW_PACKAGES_PATHS: for f in glob.glob("%s/*.bpmn" % pth): with open(f) as fp: yield os.path.basename(os.path.splitext(f)[0]), fp.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_migration_and_solr(self): """ The model or models are checked for migrations that need to be done. Solr is also checked. """
from pyoko.db.schema_update import SchemaUpdater from socket import error as socket_error from pyoko.conf import settings from importlib import import_module import_module(settings.MODELS_MODULE) registry = import_module('pyoko.model').model_registry models = [m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_redis(): """ Redis checks the connection It displays on the screen whether or not you have a connection. """
from pyoko.db.connection import cache from redis.exceptions import ConnectionError try: cache.ping() print(CheckList.OKGREEN + "{0}Redis is working{1}" + CheckList.ENDC) except ConnectionError as e: print(__(u"{0}Redis is not working{1} ").format(Che...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_riak(): """ Riak checks the connection It displays on the screen whether or not you have a connection. """
from pyoko.db.connection import client from socket import error as socket_error try: if client.ping(): print(__(u"{0}Riak is working{1}").format(CheckList.OKGREEN, CheckList.ENDC)) else: print(__(u"{0}Riak is not working{1}").format(Check...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_mq_connection(self): """ RabbitMQ checks the connection It displays on the screen whether or not you have a connection. """
import pika from zengine.client_queue import BLOCKING_MQ_PARAMS from pika.exceptions import ProbableAuthenticationError, ConnectionClosed try: connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS) channel = connection.channel() if channel.is_open:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_encoding_and_env(): """ It brings the environment variables to the screen. The user checks to see if they are using the correct variables. """
import sys import os if sys.getfilesystemencoding() in ['utf-8', 'UTF-8']: print(__(u"{0}File system encoding correct{1}").format(CheckList.OKGREEN, CheckList.ENDC)) else: print(__(u"{0}File syste...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def no_moves(position): """ Finds if the game is over. :type: position: Board :rtype: bool """
return position.no_moves(color.white) \ or position.no_moves(color.black)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_checkmate(position, input_color): """ Finds if particular King is checkmated. :type: position: Board :type: input_color: Color :rtype: bool """
return position.no_moves(input_color) and \ position.get_king(input_color).in_check(position)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _paginate(self, current_page, query_set, per_page=10): """ Handles pagination of object listings. Args: current_page int: Current page number query_set (:cla...
total_objects = query_set.count() total_pages = int(total_objects / per_page or 1) # add orphans to last page current_per_page = per_page + ( total_objects % per_page if current_page == total_pages else 0) pagination_data = dict(page=current_page, total_pages=tota...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_message(current): """ Creates a message for the given channel. .. code-block:: python # request: { 'view':'_zops_create_message', 'message': { 'channe...
msg = current.input['message'] msg_obj = Channel.add_message(msg['channel'], body=msg['body'], typ=msg['type'], sender=current.user, title=msg['title'], receiver=msg['receiver'] or None) current.output = { 'msg_key': msg_obj.key, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_channel(current, waited=False): """ Initial display of channel content. Returns channel description, members, no of members, last 20 messages etc. .. co...
ch = Channel(current).objects.get(current.input['key']) sbs = ch.get_subscription_for_user(current.user_id) current.output = {'key': current.input['key'], 'description': ch.description, 'name': sbs.name, 'actions': sbs.get_actions(), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def channel_history(current): """ Get old messages for a channel. 20 messages per request .. code-block:: python # request: { 'view':'_zops_channel_history, 'cha...
current.output = { 'status': 'OK', 'code': 201, 'messages': [] } for msg in list(Message.objects.filter(channel_id=current.input['channel_key'], updated_at__lte=current.input['timestamp'])[:20]): current.output['messages'].insert(0, msg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report_last_seen_message(current): """ Push timestamp of latest message of an ACTIVE channel. This view should be called with timestamp of latest message; - ...
sbs = Subscriber(current).objects.filter(channel_id=current.input['channel_key'], user_id=current.user_id)[0] sbs.last_seen_msg_time = current.input['timestamp'] sbs.save() current.output = { 'status': 'OK', 'code': 200}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_channels(current): """ List channel memberships of current user .. code-block:: python # request: { 'view':'_zops_list_channels', } # response: { 'chann...
current.output = { 'status': 'OK', 'code': 200, 'channels': []} for sbs in current.user.subscriptions.objects.filter(is_visible=True): try: current.output['channels'].append(sbs.get_channel_listing()) except ObjectDoesNotExist: # FIXME: This shoul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unread_count(current): """ Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'statu...
unread_ntf = 0 unread_msg = 0 for sbs in current.user.subscriptions.objects.filter(is_visible=True): try: if sbs.channel.key == current.user.prv_exchange: unread_ntf += sbs.unread_count() else: unread_msg += sbs.unread_count() except O...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_notifications(current): """ Returns last N notifications for current user .. code-block:: python # request: { 'view':'_zops_unread_messages', 'amount': i...
current.output = { 'status': 'OK', 'code': 200, 'notifications': [], } amount = current.input.get('amount', 8) try: notif_sbs = current.user.subscriptions.objects.get(channel_id=current.user.prv_exchange) except MultipleObjectsReturned: # FIXME: This should n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_channel(current): """ Create a public channel. Can be a broadcast channel or normal chat room. Chat room and broadcast distinction will be made at use...
channel = Channel(name=current.input['name'], description=current.input['description'], owner=current.user, typ=15).save() with BlockSave(Subscriber): Subscriber.objects.get_or_create(user=channel.owner, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_unit_to_channel(current): """ Subscribe users of a given unit to given channel JSON API: .. code-block:: python # request: { 'view':'_zops_add_unit_to_ch...
read_only = current.input['read_only'] newly_added, existing = [], [] for member_key in UnitModel.get_user_keys(current, current.input['unit_key']): sb, new = Subscriber(current).objects.get_or_create(user_id=member_key, read_only=read_onl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_user(current): """ Search users for adding to a public room or creating one to one direct messaging .. code-block:: python # request: { 'view':'_zops_...
current.output = { 'results': [], 'status': 'OK', 'code': 201 } qs = UserModel(current).objects.exclude(key=current.user_id).search_on( *settings.MESSAGING_USER_SEARCH_FIELDS, contains=current.input['query']) # FIXME: somehow exclude(key=current.user_id) not work...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_unit(current): """ Search on units for subscribing it's users to a channel .. code-block:: python # request: { 'view':'_zops_search_unit', 'query': st...
current.output = { 'results': [], 'status': 'OK', 'code': 201 } for user in UnitModel(current).objects.search_on(*settings.MESSAGING_UNIT_SEARCH_FIELDS, contains=current.input['query']): current.output['results'].append((u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_direct_channel(current): """ Create a One-To-One channel between current and selected user. .. code-block:: python # request: { 'view':'_zops_create_d...
channel, sub_name = Channel.get_or_create_direct_channel(current.user_id, current.input['user_key']) current.input['key'] = channel.key show_channel(current) current.output.update({ 'status': 'Created', 'code': 201 })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_message(current): """ Search in messages. If "channel_key" given, search will be limited to that channel, otherwise search will be performed on all of u...
current.output = { 'results': [], 'status': 'OK', 'code': 201 } query_set = Message(current).objects.search_on(['msg_title', 'body', 'url'], contains=current.input['query']) if current.input['channel_key']: query_set = q...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_channel(current): """ Delete a channel .. code-block:: python # request: { 'view':'_zops_delete_channel, 'channel_key': key, } # response: { 'status':...
ch_key = current.input['channel_key'] ch = Channel(current).objects.get(owner_id=current.user_id, key=ch_key) ch.delete() Subscriber.objects.filter(channel_id=ch_key).delete() Message.objects.filter(channel_id=ch_key).delete() current.output = {'status': 'Deleted', 'code': 200}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_channel(current): """ Update channel name or description .. code-block:: python # request: { 'view':'_zops_edit_channel, 'channel_key': key, 'name': str...
ch = Channel(current).objects.get(owner_id=current.user_id, key=current.input['channel_key']) ch.name = current.input['name'] ch.description = current.input['description'] ch.save() for sbs in ch.subscriber_set.objects.all(): sbs.name = ch.name ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pin_channel(current): """ Pin a channel to top of channel list .. code-block:: python # request: { 'view':'_zops_pin_channel, 'channel_key': key, } # respons...
try: Subscriber(current).objects.filter(user_id=current.user_id, channel_id=current.input['channel_key']).update( pinned=True) current.output = {'status': 'OK', 'code': 200} except ObjectDoesNotExist: raise HTTPError(404, "")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_message(current): """ Delete a message .. code-block:: python # request: { 'view':'_zops_delete_message, 'message_key': key, } # response: { 'key': ke...
try: Message(current).objects.get(sender_id=current.user_id, key=current.input['key']).delete() current.output = {'status': 'Deleted', 'code': 200, 'key': current.input['key']} except ObjectDoesNotExist: raise HTTPError(404, "")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_message(current): """ Edit a message a user own. .. code-block:: python # request: { 'view':'_zops_edit_message', 'message': { 'body': string, # message...
current.output = {'status': 'OK', 'code': 200} in_msg = current.input['message'] try: msg = Message(current).objects.get(sender_id=current.user_id, key=in_msg['key']) msg.body = in_msg['body'] msg.save() except ObjectDoesNotExist: raise HTTPError(404, "")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flag_message(current): """ Flag inappropriate messages .. code-block:: python # request: { 'view':'_zops_flag_message', 'message_key': key, } # response: { '...
current.output = {'status': 'Created', 'code': 201} FlaggedMessage.objects.get_or_create(user_id=current.user_id, message_id=current.input['key'])