code stringlengths 1 18.2k |
|---|
def from_tuples(cls, tuples): """ Creates a clamping from tuples of the form (variable, sign) Parameters ---------- tuples : iterable[(str,int)] An iterable of tuples describing clamped variables Returns ------- caspo.core.clamping.Clamping Created object instance """ return cls(it.imap(lambda (v, s): Literal(v, s), tu... |
def to_funset(self, index, name="clamped"): """ Converts the clamping to a set of `gringo.Fun`_ object instances Parameters ---------- index : int An external identifier to associate several clampings together in ASP name : str A function name for the clamping Returns ------- set The set of `gringo.Fun`_ object instanc... |
def to_array(self, variables): """ Converts the clamping to a 1-D array with respect to the given variables Parameters ---------- variables : list[str] List of variables names Returns ------- `numpy.ndarray`_ 1-D array where position `i` correspond to the sign of the clamped variable at position `i` in the given list o... |
def create_custom_gradebook_column(self, course_id, column_title, column_hidden=None, column_position=None, column_teacher_notes=None): """ Create a custom gradebook column. Create a custom gradebook column """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIR... |
data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/custom_gradebook_columns".format(**path), data=data, params=params, single_item=True) |
def update_column_data(self, id, user_id, course_id, column_data_content): """ Update column data. Set the content of a custom column """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - user_id """ID... |
def parse_log(file_path): """ Parse a CISM output log and extract some information. Args: file_path: absolute path to the log file Return: A dictionary created by the elements object corresponding to the results of the bit for bit testing """ if not os.path.isfile(file_path): return elements.error("Output Log", "Could ... |
elif ('Nonlinear Solver Step' in line): curr_step = int(line.split()[4]) elif ('Compute ice velocities, time = ' in line): converged_iters.append(curr_step) curr_step = float(line.split()[-1]) elif ('"SOLVE_STATUS_CONVERGED"' in line): split = line.split() iters_to_converge.append(int(split[split.index('"SOLVE_STATUS_C... |
def parse_config(file_path): """ Convert the CISM configuration file to a python dictionary Args: file_path: absolute path to the configuration file Returns: A dictionary representation of the given file """ if not os.path.isfile(file_path): return {} parser = ConfigParser() parser.read(file_path) # Strip out inline co... |
def _selectedRepoRow(self): """ Return the currently select repo """ # TODO - figure out what happens if no repo is selected selectedModelIndexes = \ self.reposTableWidget.selectionModel().selectedRows() for index in selectedModelIndexes: return index.row() |
def set_objective(self, measured_metabolites): ''' Updates objective function for given measured metabolites. :param dict measured_metabolites: dict in which keys are metabolite names and values are float numbers represent fold changes in metabolites. ''' self.clean_objective() for k, v in measured_metabolites.items():... |
def Routers(typ, share, handler=RoutersHandler): """ Pass the result of this function to the handler argument in your attribute declaration """ _sharing_id, _mode = tuple(share.split(":")) _router_cls = ROUTERS.get(typ) class _Handler(handler): mode=_mode sharing_id=_sharing_id router_cls=_router_cls return _Handler |
def list_migration_issues_accounts(self, account_id, content_migration_id): """ List migration issues. Returns paginated migration issues """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # REQUIRED - PATH - content_migration_id """ID""" path["content_migration_... |
def list_migration_issues_courses(self, course_id, content_migration_id): """ List migration issues. Returns paginated migration issues """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - content_migration_id """ID""" path["content_migration_id"] ... |
def list_migration_issues_groups(self, group_id, content_migration_id): """ List migration issues. Returns paginated migration issues """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - PATH - content_migration_id """ID""" path["content_migration_id"] = con... |
def list_migration_issues_users(self, user_id, content_migration_id): """ List migration issues. Returns paginated migration issues """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - content_migration_id """ID""" path["content_migration_id"] = content_... |
def update_migration_issue_accounts(self, id, account_id, workflow_state, content_migration_id): """ Update a migration issue. Update the workflow_state of a migration issue """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # REQUIRED - PATH - content_migration_... |
def update_migration_issue_courses(self, id, course_id, workflow_state, content_migration_id): """ Update a migration issue. Update the workflow_state of a migration issue """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - content_migration_id ""... |
def update_migration_issue_groups(self, id, group_id, workflow_state, content_migration_id): """ Update a migration issue. Update the workflow_state of a migration issue """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - PATH - content_migration_id """ID""... |
def update_migration_issue_users(self, id, user_id, workflow_state, content_migration_id): """ Update a migration issue. Update the workflow_state of a migration issue """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - content_migration_id """ID""" pat... |
def stringize( self, rnf_profile, ): """Create RNF representation of this segment. Args: rnf_profile (rnftools.rnfformat.RnfProfile): RNF profile (with widths). """ coor_width = max(rnf_profile.coor_width, len(str(self.left)), len(str(self.right))) return "({},{},{},{},{})".format( str(self.genome_id).zfill(rnf_profile... |
def destringize(self, string): """Get RNF values for this segment from its textual representation and save them into this object. Args: string (str): Textual representation of a segment. """ m = segment_destr_pattern.match(string) self.genome_id = int(m.group(1)) self.chr_id = int(m.group(2)) self.direction = m.group(3... |
def list_assignments(self, course_id, assignment_ids=None, bucket=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None, search_term=None): """ List assignments. Returns the list of assignments for the current context. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id "... |
if override_assignment_dates is not None: params["override_assignment_dates"] = override_assignment_dates # OPTIONAL - needs_grading_count_by_section """Split up "needs_grading_count" by sections into the "needs_grading_count_by_section" key, defaults to false""" if needs_grading_count_by_section is not None: params["n... |
def list_assignments_for_user(self, user_id, course_id): """ List assignments for user. Returns the list of assignments for the specified user if the current user has rights to view. See {api:AssignmentsApiController#index List assignments} for valid arguments. """ path = {} data = {} params = {} # REQUIRED - PATH - us... |
def get_single_assignment(self, id, course_id, all_dates=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None): """ Get a single assignment. Returns the assignment with the given id. "observed_users" is passed, submissions for observed users will also be included. """ path = {} data =... |
into the "needs_grading_count_by_section" key, defaults to false""" if needs_grading_count_by_section is not None: params["needs_grading_count_by_section"] = needs_grading_count_by_section # OPTIONAL - all_dates """All dates associated with the assignment, if applicable""" if all_dates is not None: params["all_dates"] ... |
def create_assignment(self, course_id, assignment_name, assignment_allowed_extensions=None, assignment_assignment_group_id=None, assignment_assignment_overrides=None, assignment_automatic_peer_reviews=None, assignment_description=None, assignment_due_at=None, assignment_external_tool_tag_attributes=None, assignment_gra... |
one element. If not allowing online submissions, your options are: "online_quiz" "none" "on_paper" "online_quiz" "discussion_topic" "external_tool" If you are allowing online submissions, you can have one or many allowed submission types: "online_upload" "online_text_entry" "online_url" "media_recording" (Only valid wh... |
assignment_turnitin_enabled # OPTIONAL - assignment[vericite_enabled] """Only applies when the VeriCite plugin is enabled for a course and the submission_types array includes "online_upload". Toggles VeriCite submissions for the assignment. Will be ignored if VeriCite is not available for the course.""" if assignment_v... |
reviews will be turned on for the assignment.""" if assignment_peer_reviews is not None: data["assignment[peer_reviews]"] = assignment_peer_reviews # OPTIONAL - assignment[automatic_peer_reviews] """Whether peer reviews will be assigned automatically by Canvas or if teachers must manually assign peer reviews. Does not ... |
If false, Canvas will apply the assignment's score to each member of the group. If true, the teacher can manually assign scores to each member of the group.""" if assignment_grade_group_students_individually is not None: data["assignment[grade_group_students_individually]"] = assignment_grade_group_students_individuall... |
times in ISO 8601 format, e.g. 2014-10-21T18:48:00Z.""" if assignment_due_at is not None: data["assignment[due_at]"] = assignment_due_at # OPTIONAL - assignment[lock_at] """The day/time the assignment is locked after. Accepts times in ISO 8601 format, e.g. 2014-10-21T18:48:00Z.""" if assignment_lock_at is not None: dat... |
not send change notifications and hides grades from students. Defaults to false.""" if assignment_muted is not None: data["assignment[muted]"] = assignment_muted # OPTIONAL - assignment[assignment_overrides] """List of overrides for the assignment. NOTE: The assignment overrides feature is in beta.""" if assignment_ass... |
argument the current grading_standard will be un-set from this course. This will update the grading_type for the course to 'letter_grade' unless it is already 'gpa_scale'.""" if assignment_grading_standard_id is not None: data["assignment[grading_standard_id]"] = assignment_grading_standard_id # OPTIONAL - assignment[o... |
def list_assignment_overrides(self, course_id, assignment_id): """ List assignment overrides. Returns the list of overrides for this assignment that target sections/groups/students visible to the current user. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQ... |
def redirect_to_assignment_override_for_group(self, group_id, assignment_id): """ Redirect to the assignment override for a group. Responds with a redirect to the override for the given group, if any (404 otherwise). """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id #... |
def redirect_to_assignment_override_for_section(self, assignment_id, course_section_id): """ Redirect to the assignment override for a section. Responds with a redirect to the override for the given section, if any (404 otherwise). """ path = {} data = {} params = {} # REQUIRED - PATH - course_section_id """ID""" path[... |
def create_assignment_override(self, course_id, assignment_id, assignment_override_course_section_id=None, assignment_override_due_at=None, assignment_override_group_id=None, assignment_override_lock_at=None, assignment_override_student_ids=None, assignment_override_title=None, assignment_override_unlock_at=None): """ ... |
# OPTIONAL - assignment_override[title] """The title of the adhoc assignment override. Required if student_ids is present, ignored otherwise (the title is set to the name of the targetted group or section instead).""" if assignment_override_title is not None: data["assignment_override[title]"] = assignment_override_tit... |
the override's target section. If present, must identify an active section of the assignment's course not already targetted by a different override.""" if assignment_override_course_section_id is not None: data["assignment_override[course_section_id]"] = assignment_override_course_section_id # OPTIONAL - assignment_ove... |
data["assignment_override[unlock_at]"] = assignment_override_unlock_at # OPTIONAL - assignment_override[lock_at] """The day/time the overridden assignment becomes locked. Accepts times in ISO 8601 format, e.g. 2014-10-21T18:48:00Z. If absent, this override will not affect the lock date. May be present but null to indic... |
def update_assignment_override(self, id, course_id, assignment_id, assignment_override_due_at=None, assignment_override_lock_at=None, assignment_override_student_ids=None, assignment_override_title=None, assignment_override_unlock_at=None): """ Update an assignment override. All current overridden values must be suppli... |
IDs must each identify a user with an active student enrollment in the course that is not already targetted by a different adhoc override. Ignored unless the override being updated is adhoc.""" if assignment_override_student_ids is not None: data["assignment_override[student_ids]"] = assignment_override_student_ids # O... |
Accepts times in ISO 8601 format, e.g. 2014-10-21T18:48:00Z. If absent, this override will not affect the unlock date. May be present but null to indicate the override removes any previous unlock date.""" if assignment_override_unlock_at is not None: data["assignment_override[unlock_at]"] = assignment_override_unlock_a... |
def batch_retrieve_overrides_in_course(self, course_id, assignment_overrides_id, assignment_overrides_assignment_id): """ Batch retrieve overrides in a course. Returns a list of specified overrides in this course, providing they target sections/groups/students visible to the current user. Returns null elements in the l... |
def batch_create_overrides_in_course(self, course_id, assignment_overrides): """ Batch create overrides in a course. Creates the specified overrides for each assignment. Handles creation in a transaction, so all records are created or none are. One of student_ids, group_id, or course_section_id must be present. At most... |
for available attributes""" data["assignment_overrides"] = assignment_overrides self.logger.debug("POST /api/v1/courses/{course_id}/assignments/overrides with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/assignme... |
def randomize_es(es_queryset): """Randomize an elasticsearch queryset.""" return es_queryset.query( query.FunctionScore( functions=[function.RandomScore()] ) ).sort("-_score") |
def transform(self, X, y=None): ''' :param X: list of dict which contains metabolic measurements. ''' return Parallel(n_jobs=self.n_jobs)(delayed(self._transform)(x) for x in X) |
def learn(self, fit=0, size=0, configure=None): """ Learns all (nearly) optimal logical networks with give fitness and size tolerance. The first optimum logical network found is saved in the attribute :attr:`optimum` while all enumerated logical networks are saved in the attribute :attr:`networks`. Example:: >>> from c... |
['opt']) if configure is not None: configure(clingo.conf) clingo.ground([("base", [])]) clingo.solve(on_model=self.__keep_last__) self.stats['time_optimum'] = clingo.stats['time_total'] self._logger.info("Optimum logical network learned in %.4fs", self.stats['time_optimum']) tuples = (f.args() for f in self._last) self... |
def random(self, size, n_and, max_in, n=1): """ Generates `n` random logical networks with given size range, number of AND gates and maximum input signals for AND gates. Logical networks are saved in the attribute :attr:`networks`. Parameters ---------- n : int Number of random logical networks to be generated size : (... |
def configure(self, cfg, handler, path=""): """ Start configuration process for the provided handler Args: cfg (dict): config container handler (config.Handler class): config handler to use path (str): current path in the configuration progress """ # configure simple value attributes (str, int etc.) for name, attr in h... |
(path, name)) if attr.expected_type in [list, dict] and not cfg.get(name): try: del cfg[name] except KeyError: pass |
def set(self, handler, attr, name, path, cfg): """ Obtain value for config variable, by prompting the user for input and substituting a default value if needed. Also does validation on user input """ full_name = ("%s.%s" % (path, name)).strip(".") # obtain default value if attr.default is None: default = None else: try... |
be of type %s"% attr.expected_type) try: b = handler.check({name:r}, name, path) except Exception as inst: if hasattr(inst, "explanation"): self.echo(inst.explanation) else: raise return r |
def _from_keras_log_format(data, **kwargs): """Plot accuracy and loss from a panda's dataframe. Args: data: Panda dataframe in the format of the Keras CSV log. output_dir_path: The path to the directory where the resultings plots should end up. """ data_val = pd.DataFrame(data[['epoch']]) data_val['acc'] = data['val_ac... |
def from_keras_log(csv_path, output_dir_path, **kwargs): """Plot accuracy and loss from a Keras CSV log. Args: csv_path: The path to the CSV log with the actual data. output_dir_path: The path to the directory where the resultings plots should end up. """ # automatically get seperator by using Python's CSV parser data ... |
def get_config(self, key_name): """ Return configuration value Args: key_name (str): configuration key Returns: The value for the specified configuration key, or if not found in the config the default value specified in the Configuration Handler class specified inside this component """ if key_name in self.config: retu... |
def make_pagination_headers(request, limit, curpage, total, links=False): """Return Link Hypermedia Header.""" lastpage = math.ceil(total / limit) - 1 headers = {'X-Total-Count': str(total), 'X-Limit': str(limit), 'X-Page-Last': str(lastpage), 'X-Page': str(curpage)} if links: base = "{}?%s".format(request.path) links ... |
def bind(cls, app, *paths, methods=None, name=None, **kwargs): """Bind to the application. Generate URL, name if it's not provided. """ paths = paths or ['/%s(/{%s})?/?' % (cls.name, cls.name)] name = name or "api.%s" % cls.name return super(RESTHandler, cls).bind(app, *paths, methods=methods, name=name, **kwargs) |
async def dispatch(self, request, view=None, **kwargs): """Process request.""" # Authorization endpoint self.auth = await self.authorize(request, **kwargs) # noqa # Load collection self.collection = await self.get_many(request, **kwargs) if request.method == 'POST' and view is None: return await super(RESTHandler, self... |
self.meta.page_links) except ValueError: raise RESTBadRequest(reason='Pagination params are invalid.') response = await super(RESTHandler, self).dispatch( request, resource=resource, view=view, **kwargs) response.headers.update(headers) return response |
async def make_response(self, request, response, **response_kwargs): """Convert a handler result to web response.""" while iscoroutine(response): response = await response if isinstance(response, StreamResponse): return response response_kwargs.setdefault('content_type', 'application/json') return Response(text=dumps(r... |
async def filter(self, request, **kwargs): """Filter collection.""" try: data = loads(request.query.get(VAR_WHERE)) except (ValueError, TypeError): return self.collection self.filters, collection = self.meta.filters.filter( data, self.collection, resource=self, **kwargs) return collection |
async def get(self, request, resource=None, **kwargs): """Get resource or collection of resources. --- parameters: - name: resource in: path type: string """ if resource is not None and resource != '': return self.to_simple(request, resource, **kwargs) return self.to_simple(request, self.collection, many=True, **kwargs... |
def to_simple(self, request, data, many=False, **kwargs): """Serialize response to simple object (list, dict).""" schema = self.get_schema(request, **kwargs) return schema.dump(data, many=many).data if schema else data |
async def post(self, request, resource=None, **kwargs): """Create a resource.""" resource = await self.load(request, resource=resource, **kwargs) resource = await self.save(request, resource=resource, **kwargs) return self.to_simple(request, resource, many=isinstance(resource, list), **kwargs) |
async def load(self, request, resource=None, **kwargs): """Load resource from given data.""" schema = self.get_schema(request, resource=resource, **kwargs) data = await self.parse(request) resource, errors = schema.load( data, partial=resource is not None, many=isinstance(data, list)) if errors: raise RESTBadRequest(re... |
async def put(self, request, resource=None, **kwargs): """Update a resource. --- parameters: - name: resource in: path type: string """ if resource is None: raise RESTNotFound(reason='Resource not found') return await self.post(request, resource=resource, **kwargs) |
async def delete(self, request, resource=None, **kwargs): """Delete a resource.""" if resource is None: raise RESTNotFound(reason='Resource not found') self.collection.remove(resource) |
def render_to_response(self, context, **response_kwargs): """ This endpoint sets very permiscuous CORS headers. Access-Control-Allow-Origin is set to the request Origin. This allows a page from ANY domain to make a request to this endpoint. Access-Control-Allow-Credentials is set to true. This allows requesting poll da... |
def save(self, **kwargs): """ Save and return a list of object instances. """ validated_data = [ dict(list(attrs.items()) + list(kwargs.items())) for attrs in self.validated_data ] if "id" in validated_data: ModelClass = self.Meta.model try: self.instance = ModelClass.objects.get(id=validated_data["id"]) except ModelCl... |
def resize(widthWindow, heightWindow): """Setup 3D projection for window""" glViewport(0, 0, widthWindow, heightWindow) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(70, 1.0*widthWindow/heightWindow, 0.001, 10000.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() |
def to_d(l): """ Converts list of dicts to dict. """ _d = {} for x in l: for k, v in x.items(): _d[k] = v return _d |
def tailor(pattern_or_root, dimensions=None, distributed_dim='time', read_only=False): """ Return a TileManager to wrap the root descriptor and tailor all the dimensions to a specified window. Keyword arguments: root -- a NCObject descriptor. pattern -- a filename string to open a NCObject descriptor. dimensions -- a d... |
def command_dependants(options): """Command launched by CLI.""" dependants = sorted( get_dependants(options.package.project_name), key=lambda n: n.lower() ) if dependants: print(*dependants, sep='\n') |
def get_dependants(project_name): """Yield dependants of `project_name`.""" for package in get_installed_distributions(user_only=ENABLE_USER_SITE): if is_dependant(package, project_name): yield package.project_name |
def is_dependant(package, project_name): """Determine whether `package` is a dependant of `project_name`.""" for requirement in package.requires(): # perform case-insensitive matching if requirement.project_name.lower() == project_name.lower(): return True return False |
def get_global_rate_limit(self): """Get the global rate limit per client. :rtype: int :returns: The global rate limit for each client. """ r = urllib.request.urlopen('https://archive.org/metadata/iamine-rate-limiter') j = json.loads(r.read().decode('utf-8')) return int(j.get('metadata', {}).get('rate_per_second', 300)) |
def _rate_limited(): """A rate limit decorator for limiting the number of times the decorated :class:`Miner` method can be called. Limits are set in :attr:`Miner._max_per_second`. """ def decorate(func): def rate_limited_func(self, *args, **kwargs): elapsed = time.monotonic() - self._last_time_called self.left_to_wait ... |
def mine_items(self, identifiers, params=None, callback=None): """Mine metadata from Archive.org items. :param identifiers: Archive.org identifiers to be mined. :type identifiers: iterable :param params: URL parameters to send with each metadata request. :type params: dict :param callback: A callback function to be cal... |
def search_requests(self, query=None, params=None, callback=None, mine_ids=None): """Mine Archive.org search results. :param query: The Archive.org search query to yield results for. Refer to https://archive.org/advancedsearch.php#raw for help formatting your query. :type query: str :param params: The URL parameters to... |
1) and (not any('identifier' == params[k] for k in params)): # Make sure to not overwrite the existing fl[] key. i = 0 while params.get('fl[{}]'.format(i)): i += 1 params['fl[{}]'.format(i)] = 'identifier' search_params = self.get_search_params(query, params) url = make_url('/advancedsearch.php', self.protocol, self.ho... |
def analyze(self, text): """Sends text to LUIS for analysis. Returns a LuisResult. """ logger.debug('Sending %r to LUIS app %s', text, self._url) r = requests.get(self._url, {'q': text}) logger.debug('Request sent to LUIS URL: %s', r.url) logger.debug( 'LUIS returned status %s with text: %s', r.status_code, r.text) r.r... |
def enum(**enums): """ A basic enum implementation. Usage: >>> MY_ENUM = enum(FOO=1, BAR=2) >>> MY_ENUM.FOO 1 >>> MY_ENUM.BAR 2 """ # Enum values must be hashable to support reverse lookup. if not all(isinstance(val, collections.Hashable) for val in _values(enums)): raise EnumConstructionException('All enum values must... |
def choices(cls, value_field='canonical_name', display_field='display_name'): """ DEPRECATED Returns a list of 2-tuples to be used as an argument to Django Field.choices Implementation note: choices() can't be a property See: http://www.no-ack.org/2011/03/strange-behavior-with-properties-on.html http://utcc.utoronto.ca... |
def create_translation_tasks(self, instance): """ Creates the translations tasks from the instance and its translatable children :param instance: :return: """ langs = self.get_languages() result = [] # get the previous and actual values # in case it's and "add" operation previous values will be empty previous_values, a... |
def update_task(self, differences): """ Updates a task as done if we have a new value for this alternative language :param differences: :return: """ self.log('differences UPDATING: {}'.format(differences)) object_name = '{} - {}'.format(self.app_label, self.instance.master._meta.verbose_name) lang = self.instance.langu... |
def get_previous_and_current_values(self, instance): """ Obtain the previous and actual values and compares them in order to detect which fields has changed :param instance: :param translation: :return: """ translated_field_names = self._get_translated_field_names(instance.master) if instance.pk: try: previous_obj = in... |
def get_obj_values(obj, translated_field_names): """ get the translated field values from translatable fields of an object :param obj: :param translated_field_names: :return: """ # set of translated fields to list fields = list(translated_field_names) values = {field: getattr(obj, field) for field in fields} return val... |
def _get_translated_field_names(model_instance): """ Get the instance translatable fields :return: """ hvad_internal_fields = ['id', 'language_code', 'master', 'master_id', 'master_id'] translated_field_names = set(model_instance._translated_field_names) - set(hvad_internal_fields) return translated_field_names |
def get_languages(self, include_main=False): """ Get all the languages except the main. Try to get in order: 1.- item languages 2.- model languages 3.- application model languages # 4.- default languages :param master: :param include_main: :return: """ if not self.master: raise Exception('TransManager - No master set')... |
def get_users_indexed_by_lang(): """ Return all the translator users indexed by lang :return: """ result = {} users = TransUser.objects.filter(active=True).select_related('user') for user in users: for lang in user.languages.all(): if lang.code not in result: result[lang.code] = set() result[lang.code].add(user) return... |
def get_languages_from_item(ct_item, item): """ Get the languages configured for the current item :param ct_item: :param item: :return: """ try: item_lan = TransItemLanguage.objects.filter(content_type__pk=ct_item.id, object_id=item.id).get() languages = [lang.code for lang in item_lan.languages.all()] return languages... |
def get_languages_from_model(app_label, model_label): """ Get the languages configured for the current model :param model_label: :param app_label: :return: """ try: mod_lan = TransModelLanguage.objects.filter(model='{} - {}'.format(app_label, model_label)).get() languages = [lang.code for lang in mod_lan.languages.all(... |
def get_languages_from_application(app_label): """ Get the languages configured for the current application :param app_label: :return: """ try: mod_lan = TransApplicationLanguage.objects.filter(application=app_label).get() languages = [lang.code for lang in mod_lan.languages.all()] return languages except TransApplicat... |
def get_main_language(): """ returns the main language :return: """ try: main_language = TransLanguage.objects.filter(main_language=True).get() return main_language.code except TransLanguage.DoesNotExist: return TM_DEFAULT_LANGUAGE_CODE |
def log(self, msg): """ Log a message information adding the master_class and instance_class if available :param msg: :return: """ if self.master_class and self.instance_class: logger.info('{0} - {1} - {2} - {3} - lang: {4} msg: {5}'.format( self.ct_master.app_label, self.ct_master.model, self.instance_class, self.inst... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.