_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q21200 | AnalysesView.get_instruments_vocabulary | train | def get_instruments_vocabulary(self, analysis_brain):
"""Returns a vocabulary with the valid and active instruments available
for the analysis passed in.
If the option "Allow instrument entry of results" for the Analysis
is disabled, the function returns an empty vocabulary.
If the analysis passed in is a Reference Analysis (Blank or Control),
the vocabulary, the invalid instruments will be included in the
vocabulary too.
The vocabulary is a list of dictionaries. Each dictionary has the
following structure:
{'ResultValue': <instrument_UID>,
'ResultText': <instrument_Title>}
:param analysis_brain: A single Analysis or ReferenceAnalysis
:type analysis_brain: Analysis or.ReferenceAnalysis
:return: A vocabulary with the instruments for the analysis
:rtype: A list of dicts: [{'ResultValue':UID, 'ResultText':Title}]
"""
if not analysis_brain.getInstrumentEntryOfResults:
# Instrument entry of results for this analysis is not allowed
return list()
# If the analysis is a QC analysis, display all instruments, including
# those uncalibrated or for which the last QC test failed.
meta_type = analysis_brain.meta_type
uncalibrated = meta_type == 'ReferenceAnalysis'
if meta_type == 'DuplicateAnalysis':
base_analysis_type = analysis_brain.getAnalysisPortalType
uncalibrated = base_analysis_type == 'ReferenceAnalysis'
| python | {
"resource": ""
} |
q21201 | AnalysesView._folder_item_category | train | def _folder_item_category(self, analysis_brain, item):
"""Sets the category to the item passed in
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
if not self.show_categories:
| python | {
"resource": ""
} |
q21202 | AnalysesView._folder_item_duedate | train | def _folder_item_duedate(self, analysis_brain, item):
"""Set the analysis' due date to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
# Note that if the analysis is a Reference Analysis, `getDueDate`
# returns the date when the ReferenceSample expires. If the analysis is
# a duplicate, `getDueDate` returns the due date of the source analysis
due_date = analysis_brain.getDueDate
if not due_date:
return None
due_date_str = self.ulocalized_time(due_date, long_format=0)
item['DueDate'] = due_date_str
| python | {
"resource": ""
} |
q21203 | AnalysesView._folder_item_result | train | def _folder_item_result(self, analysis_brain, item):
"""Set the analysis' result to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
item["Result"] = ""
if not self.has_permission(ViewResults, analysis_brain):
# If user has no permissions, don"t display the result but an icon
img = get_image("to_follow.png", width="16px", height="16px")
item["before"]["Result"] = img
return
result = analysis_brain.getResult
capture_date = analysis_brain.getResultCaptureDate
capture_date_str = self.ulocalized_time(capture_date, long_format=0)
item["Result"] = result
item["CaptureDate"] = capture_date_str
item["result_captured"] = capture_date_str
# Edit mode enabled of this Analysis
if self.is_analysis_edition_allowed(analysis_brain):
# Allow to set Remarks
item["allow_edit"].append("Remarks")
# Set the results field editable
if self.is_result_edition_allowed(analysis_brain):
item["allow_edit"].append("Result")
# Prepare result | python | {
"resource": ""
} |
q21204 | AnalysesView._folder_item_calculation | train | def _folder_item_calculation(self, analysis_brain, item):
"""Set the analysis' calculation and interims to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
is_editable = self.is_analysis_edition_allowed(analysis_brain)
# Set interim fields. Note we add the key 'formatted_value' to the list
# of interims the analysis has already assigned.
interim_fields = analysis_brain.getInterimFields or list()
for interim_field in interim_fields:
interim_keyword = interim_field.get('keyword', '')
if not interim_keyword:
continue
interim_value = interim_field.get('value', '')
interim_formatted = formatDecimalMark(interim_value, self.dmk)
interim_field['formatted_value'] = interim_formatted
item[interim_keyword] = interim_field
item['class'][interim_keyword] = 'interim'
# Note: As soon as we have a separate content type for field
# analysis, we can solely rely on the field permission
# "senaite.core: Field: Edit Analysis Result"
if is_editable:
| python | {
"resource": ""
} |
q21205 | AnalysesView._folder_item_method | train | def _folder_item_method(self, analysis_brain, item):
"""Fills the analysis' method to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
is_editable = self.is_analysis_edition_allowed(analysis_brain)
method_title = analysis_brain.getMethodTitle
item['Method'] = method_title or ''
if is_editable:
method_vocabulary = self.get_methods_vocabulary(analysis_brain)
if method_vocabulary:
item['Method'] = analysis_brain.getMethodUID
| python | {
"resource": ""
} |
q21206 | AnalysesView._folder_item_instrument | train | def _folder_item_instrument(self, analysis_brain, item):
"""Fills the analysis' instrument to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
item['Instrument'] = ''
if not analysis_brain.getInstrumentEntryOfResults:
# Manual entry of results, instrument is not allowed
item['Instrument'] = _('Manual')
item['replace']['Instrument'] = \
'<a href="#">{}</a>'.format(t(_('Manual')))
return
# Instrument can be assigned to this analysis
is_editable = self.is_analysis_edition_allowed(analysis_brain)
self.show_methodinstr_columns = True
instrument = self.get_instrument(analysis_brain)
if is_editable:
# Edition allowed
voc = self.get_instruments_vocabulary(analysis_brain)
if voc:
# The service has at least one instrument available
item['Instrument'] = instrument.UID() if instrument else ''
| python | {
"resource": ""
} |
q21207 | AnalysesView._folder_item_uncertainty | train | def _folder_item_uncertainty(self, analysis_brain, item):
"""Fills the analysis' uncertainty to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
item["Uncertainty"] = ""
if not self.has_permission(ViewResults, analysis_brain):
return
result = analysis_brain.getResult
obj = self.get_object(analysis_brain)
formatted = format_uncertainty(obj, result, decimalmark=self.dmk,
| python | {
"resource": ""
} |
q21208 | AnalysesView._folder_item_detection_limits | train | def _folder_item_detection_limits(self, analysis_brain, item):
"""Fills the analysis' detection limits to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
item["DetectionLimitOperand"] = ""
if not self.is_analysis_edition_allowed(analysis_brain):
# Return immediately if the we are not in edit mode
return
# TODO: Performance, we wake-up the full object here
obj = self.get_object(analysis_brain)
# No Detection Limit Selection
if not obj.getDetectionLimitSelector():
return None
# Show Detection Limit Operand Selector
| python | {
"resource": ""
} |
q21209 | AnalysesView._folder_item_specifications | train | def _folder_item_specifications(self, analysis_brain, item):
"""Set the results range to the item passed in"""
# Everyone can see valid-ranges
item['Specification'] = ''
results_range = analysis_brain.getResultsRange
if not results_range:
return
# Display the specification interval
item["Specification"] = get_formatted_interval(results_range, "")
# Show an icon if out of range
out_range, out_shoulders = is_out_of_range(analysis_brain)
if not out_range:
return
| python | {
"resource": ""
} |
q21210 | AnalysesView._folder_item_verify_icons | train | def _folder_item_verify_icons(self, analysis_brain, item):
"""Set the analysis' verification icons to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
submitter = analysis_brain.getSubmittedBy
if not submitter:
# This analysis hasn't yet been submitted, no verification yet
return
if analysis_brain.review_state == 'retracted':
# Don't display icons and additional info about verification
return
verifiers = analysis_brain.getVerificators
in_verifiers = submitter in verifiers
if in_verifiers:
# If analysis has been submitted and verified by the same person,
# display a warning icon
msg = t(_("Submitted and verified by the same user: {}"))
icon = get_image('warning.png', title=msg.format(submitter))
self._append_html_element(item, 'state_title', icon)
num_verifications = analysis_brain.getNumberOfRequiredVerifications
if num_verifications > 1:
# More than one verification required, place an icon and display
# the number of verifications done vs. total required
done = analysis_brain.getNumberOfVerifications
pending = num_verifications - done
ratio = float(done) / float(num_verifications) if done > 0 else 0
ratio = int(ratio * 100)
scale = ratio == 0 and 0 or (ratio / 25) * 25
anchor = "<a href='#' title='{} {} {}' " \
"class='multi-verification scale-{}'>{}/{}</a>"
anchor = anchor.format(t(_("Multi-verification required")),
str(pending),
t(_("verification(s) pending")),
| python | {
"resource": ""
} |
q21211 | AnalysesView._folder_item_assigned_worksheet | train | def _folder_item_assigned_worksheet(self, analysis_brain, item):
"""Adds an icon to the item dict if the analysis is assigned to a
worksheet and if the icon is suitable for the current context
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
if not IAnalysisRequest.providedBy(self.context):
# We want this icon to only appear if the context is an AR
return
analysis_obj = self.get_object(analysis_brain)
worksheet = analysis_obj.getWorksheet()
if not worksheet: | python | {
"resource": ""
} |
q21212 | AnalysesView._folder_item_reflex_icons | train | def _folder_item_reflex_icons(self, analysis_brain, item):
"""Adds an icon to the item dictionary if the analysis has been
automatically generated due to a reflex rule
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
if | python | {
"resource": ""
} |
q21213 | AnalysesView._folder_item_fieldicons | train | def _folder_item_fieldicons(self, analysis_brain):
"""Resolves if field-specific icons must be displayed for the object
passed in.
:param analysis_brain: Brain that represents an analysis
"""
full_obj = self.get_object(analysis_brain)
uid = api.get_uid(full_obj)
for name, adapter in getAdapters((full_obj,), IFieldIcons):
alerts = adapter()
if not alerts or uid not in alerts:
| python | {
"resource": ""
} |
q21214 | AnalysesView._folder_item_remarks | train | def _folder_item_remarks(self, analysis_brain, item):
"""Renders the Remarks field for the passed in analysis
If the edition of the analysis is permitted, adds the field into the
list of editable fields.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
| python | {
"resource": ""
} |
q21215 | AnalysesView._append_html_element | train | def _append_html_element(self, item, element, html, glue=" ",
after=True):
"""Appends an html value after or before the element in the item dict
:param item: dictionary that represents an analysis row
:param element: id of the element the html must be added thereafter
| python | {
"resource": ""
} |
q21216 | sortable_title | train | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
| python | {
"resource": ""
} |
q21217 | sortable_sortkey_title | train | def sortable_sortkey_title(instance):
"""Returns a sortable title as a mxin of sortkey + lowercase sortable_title
"""
title = sortable_title(instance)
if safe_callable(title):
title = title()
| python | {
"resource": ""
} |
q21218 | ARTemplateAnalysesView.get_settings | train | def get_settings(self):
"""Returns a mapping of UID -> setting
"""
settings = self.context.getAnalysisServicesSettings()
| python | {
"resource": ""
} |
q21219 | WorkflowActionAssignAdapter.sorted_analyses | train | def sorted_analyses(self, analyses):
"""Sort the analyses by AR ID ascending and subsorted by priority
sortkey within the AR they belong to
"""
analyses = sorted(analyses, key=lambda an: an.getRequestID())
def sorted_by_sortkey(objs):
return sorted(objs, key=lambda an: an.getPrioritySortkey())
# Now, we need the analyses within a request ID to be sorted by
# sortkey (sortable_title index), so it will appear in the same
# order as they appear in Analyses list from AR view
current_sample_id = None
current_analyses = []
sorted_analyses = []
for analysis in analyses:
sample_id = analysis.getRequestID()
if sample_id and current_sample_id != sample_id:
# Sort the brains we've collected until now, that
# belong to the same Analysis Request
current_analyses = sorted_by_sortkey(current_analyses)
| python | {
"resource": ""
} |
q21220 | InstrumentMaintenanceTask.getMaintenanceTypes | train | def getMaintenanceTypes(self):
""" Return the current list of maintenance types
"""
types = [('Preventive',safe_unicode(_('Preventive')).encode('utf-8')),
('Repair', | python | {
"resource": ""
} |
q21221 | after_unassign | train | def after_unassign(duplicate_analysis):
"""Removes the duplicate from the system
"""
analysis_events.after_unassign(duplicate_analysis)
| python | {
"resource": ""
} |
q21222 | after_retract | train | def after_retract(duplicate_analysis):
"""Function triggered after a 'retract' transition for the duplicate passed
in is performed. The duplicate transitions to "retracted" state and a new
copy of the duplicate is created.
"""
# Rename the analysis to make way for it's successor.
# Support multiple retractions by renaming to *-0, *-1, etc
parent = duplicate_analysis.aq_parent
keyword = duplicate_analysis.getKeyword()
analyses = filter(lambda an: an.getKeyword() == keyword,
parent.objectValues("DuplicateAnalysis"))
# Rename the retracted duplicate
# https://docs.plone.org/develop/plone/content/rename.html
# _verifyObjectPaste permission check must be cancelled
parent._verifyObjectPaste = str
retracted_id = '{}-{}'.format(keyword, len(analyses))
# Make sure all persistent objects have _p_jar attribute
transaction.savepoint(optimistic=True)
parent.manage_renameObject(duplicate_analysis.getId(), retracted_id)
delattr(parent, '_verifyObjectPaste')
# Find out the slot position of the duplicate in the worksheet
worksheet = duplicate_analysis.getWorksheet()
if not worksheet:
logger.warn("Duplicate {} has been retracted, but without worksheet"
.format(duplicate_analysis.getId()))
return
dest_slot = worksheet.get_slot_position_for(duplicate_analysis)
if not dest_slot:
logger.warn("Duplicate {} has been retracted, but not found in any"
"slot of worksheet {}"
| python | {
"resource": ""
} |
q21223 | MasshunterQuantCSVParser.parse_sequencetableline | train | def parse_sequencetableline(self, line):
""" Parses sequence table lines
Sequence Table example:
Sequence Table,,,,,,,,,,,,,,,,,
Data File,Sample Name,Position,Inj Vol,Level,Sample Type,Acq Method File,,,,,,,,,,,
prerunrespchk.d,prerunrespchk,Vial 3,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
DSS_Nist_L1.d,DSS_Nist_L1,P1-A2,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
DSS_Nist_L2.d,DSS_Nist_L2,P1-B2,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
DSS_Nist_L3.d,DSS_Nist_L3,P1-C2,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
UTAK_DS_L1.d,UTAK_DS_L1,P1-D2,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
UTAK_DS_L2.d,UTAK_DS_L2,P1-E2,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
mid_respchk.d,mid_respchk,Vial 3,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
UTAK_DS_low.d,UTAK_DS_Low,P1-F2,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
FDBS_31.d,FDBS_31,P1-G2,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
FDBS_32.d,FDBS_32,P1-H2,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
LS_60-r001.d,LS_60,P1-G12,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
LS_60-r002.d,LS_60,P1-G12,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
LS_61-r001.d,LS_61,P1-H12,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
LS_61-r002.d,LS_61,P1-H12,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
post_respchk.d,post_respchk,Vial 3,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
,,,,,,,,,,,,,,,,,
"""
# Sequence Table,,,,,,,,,,,,,,,,,
# prerunrespchk.d,prerunrespchk,Vial 3,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
# mid_respchk.d,mid_respchk,Vial 3,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
# ,,,,,,,,,,,,,,,,,
if line.startswith(self.SEQUENCETABLE_KEY) \
or line.startswith(self.SEQUENCETABLE_PRERUN) \
or line.startswith(self.SEQUENCETABLE_MIDRUN) \
or self._end_sequencetable == True:
# Nothing to do, continue
return 0
# Data File,Sample Name,Position,Inj Vol,Level,Sample Type,Acq Method File,,,,,,,,,,,
if line.startswith(self.SEQUENCETABLE_HEADER_DATAFILE):
self._sequencesheader = [token.strip() for token in line.split(',') if token.strip()]
return 0
# post_respchk.d,post_respchk,Vial 3,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,
# Quantitation Results,,,,,,,,,,,,,,,,,
if line.startswith(self.SEQUENCETABLE_POSTRUN) \
or line.startswith(self.QUANTITATIONRESULTS_KEY) \
or line.startswith(self.COMMAS):
self._end_sequencetable = True
if len(self._sequences) == 0:
self.err("No Sequence Table found", linenum=self._numline)
| python | {
"resource": ""
} |
q21224 | JSONReadExtender.render_template_partitions | train | def render_template_partitions(self):
"""
Supplies a more detailed view of the Partitions for this
template. It's built to mimic the partitions that are stored in the
ar_add form state variable, so that when a partition is chosen, there
is no further translation necessary.
It combines the Analyses and Partitions AT schema field values.
For some fields (separate, minvol) there is no information, when partitions
are specified in the AR Template.
:return a list of dictionaries like this:
container
[]
container_titles
[]
preservation
[]
preservation_titles
[]
separate
false
minvol
"0.0000 m3 "
services
["2fdc040e05bb42ca8b52e41761fdb795", 6 more...]
service_titles
["Copper", "Iron", "Magnesium", 4 more...]
"""
Analyses = self.context.Schema()['Analyses'].get(self.context)
Parts = self.context.Schema()['Partitions'].get(self.context)
if not Parts:
# default value copied in from content/artemplate.py
Parts = [{'part_id': 'part-1',
'Container': '',
'Preservation': '',
'container_uid': '',
'preservation_uid': ''}]
parts = []
not_found = set()
for Part in Parts:
part = {
'part_id': Part.get("part_id", "part-1"),
'container_titles': Part.get("Container", ""),
'container': Part.get("container_uid", ""),
'preservation_titles': Part.get("Preservation", ""),
'preservation': Part.get("preservation_uid", ""),
| python | {
"resource": ""
} |
q21225 | ComboBoxWidget.process_form | train | def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
"""A typed in value takes precedence over a selected value.
"""
name = field.getName()
otherName = "%s_other" % name
value = form.get(otherName, empty_marker)
regex = field.widget.field_regex
# validate the custom value against the given regex
if value and not re.match(regex, value):
value = None
# If value is an empty string we check if the selection box
| python | {
"resource": ""
} |
q21226 | searchResults | train | def searchResults(self, REQUEST=None, used=None, **kw):
"""Search the catalog
Search terms can be passed in the REQUEST or as keyword
arguments.
The used argument is now deprecated and ignored
"""
if REQUEST and REQUEST.get('getRequestUID') \
and self.id == CATALOG_ANALYSIS_LISTING:
# Fetch all analyses that have the request UID passed in as an ancestor,
# cause we want Primary ARs to always display the analyses from their
# derived ARs (if result is not empty)
request = REQUEST.copy()
orig_uid = request.get('getRequestUID')
# If a list of request uid, retrieve them sequentially to make the
# masking process easier
if isinstance(orig_uid, list):
results = list()
for uid in orig_uid:
request['getRequestUID'] = [uid]
results += self.searchResults(REQUEST=request, used=used, **kw)
return results
# Get all analyses, those from descendant ARs included
del request['getRequestUID']
| python | {
"resource": ""
} |
q21227 | barcode_entry.handle_Sample | train | def handle_Sample(self, instance):
"""If this sample has a single AR, go there.
If the sample has 0 or >1 ARs, go to the sample's view URL.
"""
ars = instance.getAnalysisRequests()
if len(ars) == 1:
| python | {
"resource": ""
} |
q21228 | set_sample_type_default_stickers | train | def set_sample_type_default_stickers(portal):
"""
Fills the admitted stickers and their default stickers to every sample
type.
"""
# Getting all sticker templates
stickers = getStickerTemplates()
sticker_ids = []
for sticker in stickers:
sticker_ids.append(sticker.get('id'))
def_small_template = portal.bika_setup.getSmallStickerTemplate()
def_large_template = portal.bika_setup.getLargeStickerTemplate()
# Getting all Sample Type objects
catalog = api.get_tool('bika_setup_catalog')
brains = catalog(portal_type='SampleType')
for | python | {
"resource": ""
} |
q21229 | ARAnalysesField.get | train | def get(self, instance, **kwargs):
"""Returns a list of Analyses assigned to this AR
Return a list of catalog brains unless `full_objects=True` is passed.
Other keyword arguments are passed to bika_analysis_catalog
:param instance: Analysis Request object
:param kwargs: Keyword arguments to inject in the search query
:returns: A list of Analysis Objects/Catalog Brains
"""
catalog = getToolByName(instance, CATALOG_ANALYSIS_LISTING)
query = dict(
[(k, v) for k, v in kwargs.items() if k in | python | {
"resource": ""
} |
q21230 | ARAnalysesField._get_services | train | def _get_services(self, full_objects=False):
"""Fetch and return analysis service objects
"""
bsc = | python | {
"resource": ""
} |
q21231 | ARAnalysesField._to_service | train | def _to_service(self, thing):
"""Convert to Analysis Service
:param thing: UID/Catalog Brain/Object/Something
:returns: Analysis Service object or None
"""
# Convert UIDs to objects
if api.is_uid(thing):
thing = api.get_object_by_uid(thing, None)
# Bail out if the thing is not a valid object
if not api.is_object(thing):
logger.warn("'{}' is not a valid object!".format(repr(thing)))
return None
# Ensure we have an object here and not a brain
obj = api.get_object(thing)
if IAnalysisService.providedBy(obj):
| python | {
"resource": ""
} |
q21232 | ARAnalysesField._update_specs | train | def _update_specs(self, instance, specs):
"""Update AR specifications
:param instance: Analysis Request
:param specs: List of Specification Records
"""
if specs is None:
return
# N.B. we copy the records here, otherwise the spec will be written to
# the attached specification of this AR
rr = {item["keyword"]: item.copy()
for item in instance.getResultsRange()}
for spec in specs:
keyword = spec.get("keyword")
if keyword in rr:
| python | {
"resource": ""
} |
q21233 | AnalysisProfile.getTotalPrice | train | def getTotalPrice(self):
"""
Computes the final price using the VATAmount and the subtotal price
"""
| python | {
"resource": ""
} |
q21234 | EasyQParser.xlsx_to_csv | train | def xlsx_to_csv(self, infile, worksheet=0, delimiter=","):
""" Convert xlsx to easier format first, since we want to use the
convenience of the CSV library
"""
wb = load_workbook(self.getInputFile())
sheet = wb.worksheets[worksheet]
buffer = StringIO()
# extract all rows
for n, row in enumerate(sheet.rows):
line = []
for cell in row:
value = cell.value
| python | {
"resource": ""
} |
q21235 | SamplePoint.getSampleTypeTitles | train | def getSampleTypeTitles(self):
"""Returns a list of sample type titles
"""
sample_types = self.getSampleTypes()
sample_type_titles = map(lambda obj: obj.Title(), sample_types)
# N.B. This is used only for search purpose, because the catalog does
| python | {
"resource": ""
} |
q21236 | contentmenu_factories_available | train | def contentmenu_factories_available(self):
"""These types will have their Add New... factories dropdown menu removed.
"""
if hasattr(self._addContext(), 'portal_type') \
and self._addContext().portal_type in [
'ARImport',
'Batch',
'Client',
'AnalysisRequest',
'Worksheet',
'AnalysisCategory',
'AnalysisProfile',
'ARTemplate',
'AnalysisService',
'AnalysisSpec',
| python | {
"resource": ""
} |
q21237 | ReportsListingView.get_filesize | train | def get_filesize(self, pdf):
"""Compute the filesize of the PDF
"""
try:
filesize = float(pdf.get_size())
| python | {
"resource": ""
} |
q21238 | TX1800iParser._submit_results | train | def _submit_results(self):
"""
Adding current values as a Raw Result and Resetting everything.
"""
if self._cur_res_id and self._cur_values:
# Setting DefaultResult | python | {
"resource": ""
} |
q21239 | ThermoScientificMultiskanCSVParser.parse_data | train | def parse_data(self, sline):
"""This function builds the addRawResults dictionary using the header values of the labels section
as sample Ids.
"""
if sline[0] == '':
return 0
for idx, label in | python | {
"resource": ""
} |
q21240 | ContactLoginDetailsView.get_users | train | def get_users(self):
"""Get all users of the portal
"""
# We make use of the existing controlpanel `@@usergroup-userprefs`
| python | {
"resource": ""
} |
q21241 | ContactLoginDetailsView.get_user_properties | train | def get_user_properties(self):
"""Return the properties of the User
"""
user = self.context.getUser()
# No User linked, nothing to do
if user is None:
return {}
out = {}
plone_user = user.getUser()
userid = plone_user.getId()
for sheet in plone_user.listPropertysheets():
ps = plone_user.getPropertysheet(sheet)
out.update(dict(ps.propertyItems()))
| python | {
"resource": ""
} |
q21242 | ContactLoginDetailsView.linkable_users | train | def linkable_users(self):
"""Search Plone users which are not linked to a contact or lab contact
"""
# Only users with at nost these roles are displayed
linkable_roles = {"Authenticated", "Member", "Client"}
out = []
for user in self.get_users():
userid = user.get("id", None)
if userid is None:
continue
# Skip users which are already linked to a Contact
contact = Contact.getContactByUsername(userid)
labcontact = LabContact.getContactByUsername(userid)
if contact or labcontact:
continue
if self.is_contact():
# Checking Plone user belongs to Client group only. Otherwise,
# weird things could happen (a client contact assigned to a
# user with labman privileges, different contacts from
# different clients assigned to the same user, etc.)
user_roles = security.get_roles(user=userid)
if not linkable_roles.issuperset(set(user_roles)):
continue
| python | {
"resource": ""
} |
q21243 | ContactLoginDetailsView._link_user | train | def _link_user(self, userid):
"""Link an existing user to the current Contact
"""
# check if we have a selected user from the search-list
if userid:
try:
self.context.setUser(userid)
self.add_status_message(
| python | {
"resource": ""
} |
q21244 | ContactLoginDetailsView.add_status_message | train | def add_status_message(self, message, severity="info"):
"""Set a portal message
"""
| python | {
"resource": ""
} |
q21245 | _cache_key_select_state | train | def _cache_key_select_state(method, self, workflow_id, field_id, field_title):
"""
This function returns | python | {
"resource": ""
} |
q21246 | _cache_key_select_analysisservice | train | def _cache_key_select_analysisservice(method, self, allow_blank,
multiselect, style=None):
"""
This function returns the key used to decide if | python | {
"resource": ""
} |
q21247 | _cache_key_select_analyst | train | def _cache_key_select_analyst(method, self, allow_blank=False, style=None):
"""
This function returns the key used to decide if method select_analyst | python | {
"resource": ""
} |
q21248 | _cache_key_select_user | train | def _cache_key_select_user(method, self, allow_blank=True, style=None):
"""
This function returns the key used to decide if method select_user | python | {
"resource": ""
} |
q21249 | _cache_key_select_daterange | train | def _cache_key_select_daterange(method, self, field_id, field_title, style=None):
"""
This function returns the key used to decide if method select_daterange | python | {
"resource": ""
} |
q21250 | _cache_key_select_sample_type | train | def _cache_key_select_sample_type(method, self, allow_blank=True, multiselect=False, style=None):
"""
This function returns the key used to decide if method | python | {
"resource": ""
} |
q21251 | ReferenceAnalysis.getResultsRange | train | def getResultsRange(self):
"""Returns the valid result range for this reference analysis based on
the results ranges defined in the Reference Sample from which this
analysis has been created.
A Reference Analysis (control or blank) will be considered out of range
if its results does not match with the result defined on its parent
Reference Sample, with the % error as the margin of error, that will be
used to set the range's min and max values
:return: A dictionary with the keys min and max
:rtype: dict
| python | {
"resource": ""
} |
q21252 | ServicesWidget.process_form | train | def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False, validating=True):
"""Return UIDs of the selected services
| python | {
"resource": ""
} |
q21253 | ServicesWidget.Services | train | def Services(self, field, show_select_column=True):
"""Render Analyses Services Listing Table
"""
instance = getattr(self, "instance", field.aq_parent)
table = | python | {
"resource": ""
} |
q21254 | get_user | train | def get_user(user=None):
"""Get the user object
:param user: A user id, memberdata object or None for the current user
:returns: Plone User (PlonePAS) / Propertied User (PluggableAuthService)
"""
if user is None:
# Return the current authenticated user
user = getSecurityManager().getUser()
elif isinstance(user, MemberData):
# MemberData wrapped user -> get the user object | python | {
"resource": ""
} |
q21255 | get_group | train | def get_group(group):
"""Return the group
:param group: The group name/id
:returns: Group
"""
portal_groups = get_tool("portal_groups")
if isinstance(group, basestring):
group | python | {
"resource": ""
} |
q21256 | get_groups | train | def get_groups(user=None):
"""Return the groups of the user
:param user: A user id, memberdata object or None for the current user
:returns: List of groups
"""
portal_groups | python | {
"resource": ""
} |
q21257 | add_group | train | def add_group(group, user=None):
"""Add the user to the group
"""
user = get_user(user)
if user is None:
raise ValueError("User '{}' not found".format(repr(user)))
if isinstance(group, basestring):
group = [group]
elif isinstance(group, GroupData):
group = [group]
portal_groups = | python | {
"resource": ""
} |
q21258 | fix_broken_calculations | train | def fix_broken_calculations():
"""Walks-through calculations associated to undergoing analyses and
resets the value for DependentServices field"""
logger.info("Fixing broken calculations (re-assignment of dependents)...")
# Fetch only the subset of analyses that are undergoing.
# Analyses that have been verified or published cannot be updated, so there
# is no sense to check their calculations
review_states = [
'attachment_due',
'not_requested',
'rejected',
'retracted',
'sample_due',
'sample_prep',
'sample_received',
'sample_received',
'sample_registered',
'sampled',
'to_be_preserved',
'to_be_sampled',
]
uc = api.get_tool('uid_catalog')
catalog = get_tool(CATALOG_ANALYSIS_LISTING)
brains = catalog(portal_type='Analysis', review_state=review_states)
for brain in brains:
analysis = brain.getObject()
calculation = analysis.getCalculation()
if not calculation:
continue
dependents = calculation.getDependentServices()
# We don't want eventualities such as [None,]
dependents = filter(None, dependents)
if not dependents:
# Assign the formula again to the calculation. Note the function
# setFormula inferes the dependent services (and stores them) by
# inspecting the keywords set in the formula itself.
# So, instead of doing this job here, we just let setFormula to work
# for us.
formula = calculation.getFormula()
calculation.setFormula(formula)
deps = calculation.getDependentServices()
if not deps:
# Ok, this calculation does not depend on the result of other
# analyses, so we can omit this one, he is already ok
continue
deps = [dep.getKeyword() for dep in deps]
deps = ', '.join(deps)
arid = analysis.getRequestID()
logger.info("Dependents for {}.{}.{}: {}".format(arid,
analysis.getKeyword(),
| python | {
"resource": ""
} |
q21259 | UpgradeReferenceFields | train | def UpgradeReferenceFields():
"""Convert all ReferenceField's values into UIDReferenceFields.
These are not touched: HistoryAware to be removed:
- Analysis.Calculation: HistoryAwareReferenceField (rel=
AnalysisCalculation)
- DuplicateAnalysis.Calculation: HistoryAwareReferenceField (rel=
DuplicateAnalysisCalculation)
- RejectAnalysis.Calculation: HistoryAwareReferenceField (rel=
RejectAnalysisCalculation)
These are not touched: They are deprecated and will be removed:
- AnalysisRequest.Profile: ReferenceField (rel=AnalysisRequestProfile)
- LabContact.Department ReferenceField (rel=LabContactDepartment)
The remaining fields are listed below.
"""
# Change these carefully
# they were made slowly with love
# still they may be wrong.
for portal_type, fields in [
# portal_type
['ARReport', [
('AnalysisRequest', 'ARReportAnalysisRequest')
]],
['Analysis', [
# AbstractBaseAnalysis
('Category', 'AnalysisCategory'),
('Department', 'AnalysisDepartment'),
('Instrument', 'AnalysisInstrument'),
('Method', 'AnalysisMethod'),
# AbstractAnalysis
('AnalysisService', 'AnalysisAnalysisService'),
('Attachment', 'AnalysisAttachment'),
# AbstractRoutineAnalysis
('OriginalReflexedAnalysis', 'AnalysisOriginalReflexedAnalysis'),
('ReflexAnalysisOf', 'AnalysisReflexAnalysisOf'),
('SamplePartition', 'AnalysisSamplePartition')
]],
['ReferenceAnalysis', [
# AbstractBaseAnalysis
('Category', 'AnalysisCategory'),
('Department', 'AnalysisDepartment'),
('Instrument', 'AnalysisInstrument'),
('Method', 'AnalysisMethod'),
# AbstractAnalysis
('AnalysisService', 'AnalysisAnalysisService'),
('Attachment', 'AnalysisAttachment'),
]],
['DuplicateAnalysis', [
# AbstractBaseAnalysis
('Category', 'AnalysisCategory'),
('Department', 'AnalysisDepartment'),
('Instrument', 'AnalysisInstrument'),
('Method', 'AnalysisMethod'),
# AbstractAnalysis
('AnalysisService', 'AnalysisAnalysisService'),
('Attachment', 'AnalysisAttachment'),
# AbstractRoutineAnalysis
('OriginalReflexedAnalysis', 'AnalysisOriginalReflexedAnalysis'),
('ReflexAnalysisOf', 'AnalysisReflexAnalysisOf'),
('SamplePartition', 'AnalysisSamplePartition'),
# DuplicateAnalysis
('Analysis', 'DuplicateAnalysisAnalysis'),
]],
['AnalysisService', [
# AbstractBaseAnalysis
('Category', 'AnalysisCategory'),
('Department', 'AnalysisDepartment'),
('Instrument', 'AnalysisInstrument'),
('Method', 'AnalysisMethod'),
# AnalysisService
| python | {
"resource": ""
} |
q21260 | get_uid | train | def get_uid(value):
"""Takes a brain or object and returns a valid UID.
In this case, the object may come from portal_archivist, so we will
need to do a catalog query to get the UID of the current version
"""
if not value:
return ''
# Is value a brain?
if ICatalogBrain.providedBy(value):
value = value.getObject()
# validate UID
uid = value.UID()
uc = get_tool('uid_catalog')
if uc(UID=uid):
# The object is valid
return uid
# Otherwise the object is an old version
brains = uc(portal_type=value.portal_type, Title=value.Title())
if not brains:
# Cannot find UID
| python | {
"resource": ""
} |
q21261 | migrateFileFields | train | def migrateFileFields(portal):
"""
This function walks over all attachment types and migrates their FileField
fields.
"""
portal_types = [
"Attachment",
"ARImport",
"Instrument",
"InstrumentCertification",
"Method",
"Multifile",
"Report", | python | {
"resource": ""
} |
q21262 | XXX_REMOVEME | train | def XXX_REMOVEME(func):
"""Decorator for dead code removal
"""
@wraps(func)
def decorator(self, *args, **kwargs):
msg = "~~~~~~~ XXX REMOVEME marked method called: {}.{}".format(
| python | {
"resource": ""
} |
q21263 | returns_json | train | def returns_json(func):
"""Decorator for functions which return JSON
"""
def decorator(*args, **kwargs):
instance = args[0]
request = getattr(instance, 'request', None)
| python | {
"resource": ""
} |
q21264 | returns_super_model | train | def returns_super_model(func):
"""Decorator to return standard content objects as SuperModels
"""
def to_super_model(obj):
# avoid circular imports
from senaite.core.supermodel import SuperModel
# Object is already a SuperModel
if isinstance(obj, SuperModel):
return obj
# Only portal objects are supported
if not api.is_object(obj):
raise TypeError("Expected a portal object, got '{}'"
.format(type(obj)))
# Wrap the object into a specific Publication Object Adapter
uid = api.get_uid(obj)
| python | {
"resource": ""
} |
q21265 | profileit | train | def profileit(path=None):
"""cProfile decorator to profile a function
:param path: output file path
:type path: str
:return: Function
"""
def inner(func):
@wraps(func)
def wrapper(*args, **kwargs):
| python | {
"resource": ""
} |
q21266 | timeit | train | def timeit(threshold=0):
"""Decorator to log the execution time of a function
"""
def inner(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
return_value = func(*args, **kwargs)
| python | {
"resource": ""
} |
q21267 | AttachmentsView.action_update | train | def action_update(self):
"""Form action enpoint to update the attachments
"""
order = []
form = self.request.form
attachments = form.get("attachments", [])
for attachment in attachments:
# attachment is a form mapping, not a dictionary -> convert
values = dict(attachment)
uid = values.pop("UID")
obj = api.get_object_by_uid(uid)
# delete the attachment if the delete flag is true
if values.pop("delete", False):
self.delete_attachment(obj)
continue
| python | {
"resource": ""
} |
q21268 | AttachmentsView.action_add_to_ws | train | def action_add_to_ws(self):
"""Form action to add a new attachment in a worksheet
"""
ws = self.context
form = self.request.form
attachment_file = form.get('AttachmentFile_file', None)
analysis_uid = self.request.get('analysis_uid', None)
service_uid = self.request.get('Service', None)
AttachmentType = form.get('AttachmentType', '')
AttachmentKeys = form.get('AttachmentKeys', '')
ReportOption = form.get('ReportOption', 'r')
# nothing to do if the attachment file is missing
if attachment_file is None:
logger.warn("AttachmentView.action_add_attachment: Attachment file is missing")
return
if analysis_uid:
rc = api.get_tool("reference_catalog")
analysis = rc.lookupObject(analysis_uid)
# create attachment
attachment = self.create_attachment(
ws,
attachment_file,
AttachmentType=AttachmentType,
AttachmentKeys=AttachmentKeys,
ReportOption=ReportOption)
others = analysis.getAttachment()
attachments = []
for other in others:
attachments.append(other.UID())
attachments.append(attachment.UID())
analysis.setAttachment(attachments)
# The metadata for getAttachmentUIDs need to get updated,
# otherwise the attachments are not displayed
# https://github.com/senaite/bika.lims/issues/521
analysis.reindexObject()
if service_uid:
workflow = api.get_tool('portal_workflow')
# XXX: refactor out dependency to this view.
view = api.get_view("manage_results", context=self.context, request=self.request)
analyses = self.context.getAnalyses()
allowed_states = ["assigned", "unassigned", "to_be_verified"]
for analysis in analyses:
if analysis.portal_type not in ('Analysis', 'DuplicateAnalysis'):
continue
if not analysis.getServiceUID() == service_uid:
continue
review_state = workflow.getInfoFor(analysis, 'review_state', '')
if review_state | python | {
"resource": ""
} |
q21269 | AttachmentsView.action_add | train | def action_add(self):
"""Form action to add a new attachment
Code taken from bika.lims.content.addARAttachment.
"""
form = self.request.form
parent = api.get_parent(self.context)
attachment_file = form.get('AttachmentFile_file', None)
AttachmentType = form.get('AttachmentType', '')
AttachmentKeys = form.get('AttachmentKeys', '')
ReportOption = form.get('ReportOption', 'r')
# nothing to do if the attachment file is missing
if attachment_file is None:
logger.warn("AttachmentView.action_add_attachment: Attachment file is missing")
return
# create attachment
attachment = self.create_attachment(
parent,
attachment_file,
AttachmentType=AttachmentType,
AttachmentKeys=AttachmentKeys,
ReportOption=ReportOption)
# append the new UID to the end of the current order
self.set_attachments_order(api.get_uid(attachment))
# handle analysis attachment
analysis_uid = form.get("Analysis", None)
if analysis_uid:
analysis = api.get_object_by_uid(analysis_uid)
others = analysis.getAttachment()
attachments = []
for other in others:
attachments.append(other.UID())
| python | {
"resource": ""
} |
q21270 | AttachmentsView.create_attachment | train | def create_attachment(self, container, attachment_file, **kw):
"""Create an Attachment object in the given container
"""
filename = getattr(attachment_file, "filename", "Attachment")
attachment = api.create(container, "Attachment", title=filename)
attachment.edit(AttachmentFile=attachment_file, **kw)
| python | {
"resource": ""
} |
q21271 | AttachmentsView.delete_attachment | train | def delete_attachment(self, attachment):
"""Delete attachment from the AR or Analysis
The attachment will be only deleted if it is not further referenced by
another AR/Analysis.
"""
# Get the holding parent of this attachment
parent = None
if attachment.getLinkedRequests():
# Holding parent is an AR
parent = attachment.getRequest()
elif attachment.getLinkedAnalyses():
# Holding parent is an Analysis
parent = attachment.getAnalysis()
if parent is None:
logger.warn(
"Attachment {} is nowhere assigned. This should never happen!"
.format(repr(attachment)))
return False
# Get the other attachments of the holding parent
attachments = parent.getAttachment()
# New attachments to set
if attachment in attachments:
attachments.remove(attachment)
# Set the attachments w/o the current attachments
parent.setAttachment(attachments)
retain = False
# Attachment is referenced by another Analysis
if attachment.getLinkedAnalyses():
holder = | python | {
"resource": ""
} |
q21272 | AttachmentsView.get_attachment_size | train | def get_attachment_size(self, attachment):
"""Get the human readable size of the attachment
"""
fsize = 0
file = attachment.getAttachmentFile()
if file:
fsize = file.get_size()
if fsize < | python | {
"resource": ""
} |
q21273 | AttachmentsView.get_attachment_info | train | def get_attachment_info(self, attachment):
"""Returns a dictionary of attachment information
"""
attachment_uid = api.get_uid(attachment)
attachment_file = attachment.getAttachmentFile()
attachment_type = attachment.getAttachmentType()
attachment_icon = attachment_file.icon
if callable(attachment_icon):
attachment_icon = attachment_icon()
return {
'keywords': attachment.getAttachmentKeys(),
'size': self.get_attachment_size(attachment),
'name': attachment_file.filename,
| python | {
"resource": ""
} |
q21274 | AttachmentsView.get_attachments | train | def get_attachments(self):
"""Returns a list of attachments info dictionaries
Original code taken from bika.lims.analysisrequest.view
"""
attachments = []
# process AR attachments
for attachment in self.context.getAttachment():
attachment_info = self.get_attachment_info(attachment)
| python | {
"resource": ""
} |
q21275 | AttachmentsView.get_sorted_attachments | train | def get_sorted_attachments(self):
"""Returns a sorted list of analysis info dictionaries
"""
inf = float("inf")
order = self.get_attachments_order()
attachments = self.get_attachments()
def att_cmp(att1, att2): | python | {
"resource": ""
} |
q21276 | AttachmentsView.get_attachment_types | train | def get_attachment_types(self):
"""Returns a list of available attachment types
"""
bika_setup_catalog = api.get_tool("bika_setup_catalog")
attachment_types = bika_setup_catalog(portal_type='AttachmentType',
is_active=True,
| python | {
"resource": ""
} |
q21277 | AttachmentsView.get_analyses | train | def get_analyses(self):
"""Returns a list of analyses from the AR
"""
analyses = | python | {
"resource": ""
} |
q21278 | AttachmentsView.is_analysis_attachment_allowed | train | def is_analysis_attachment_allowed(self, analysis):
"""Checks if the analysis
"""
if analysis.getAttachmentOption() not in ["p", "r"]:
return False | python | {
"resource": ""
} |
q21279 | AttachmentsView.user_can_add_attachments | train | def user_can_add_attachments(self):
"""Checks if the current logged in user is allowed to add attachments
"""
if not self.global_attachments_allowed(): | python | {
"resource": ""
} |
q21280 | AttachmentsView.user_can_update_attachments | train | def user_can_update_attachments(self):
"""Checks if the current logged in user is allowed to update attachments
"""
| python | {
"resource": ""
} |
q21281 | AttachmentsView.user_can_delete_attachments | train | def user_can_delete_attachments(self):
"""Checks if the current logged in user is allowed to delete attachments
"""
context = self.context
user = api.get_current_user()
if not self.is_ar_editable():
return False
| python | {
"resource": ""
} |
q21282 | AttachmentsView.storage | train | def storage(self):
"""A storage which keeps configuration settings for attachments
"""
annotation = self.get_annotation()
if annotation.get(ATTACHMENTS_STORAGE) is None:
| python | {
"resource": ""
} |
q21283 | AttachmentsView.flush | train | def flush(self):
"""Remove the whole storage
"""
annotation = self.get_annotation()
if | python | {
"resource": ""
} |
q21284 | AttachmentsView.set_attachments_order | train | def set_attachments_order(self, order):
"""Remember the attachments order
"""
# append single uids to the order
| python | {
"resource": ""
} |
q21285 | ajaxAttachmentsView.ajax_delete_analysis_attachment | train | def ajax_delete_analysis_attachment(self):
"""Endpoint for attachment delete in WS
"""
form = self.request.form
attachment_uid = form.get("attachment_uid", None)
if not attachment_uid:
return "error"
attachment = api.get_object_by_uid(attachment_uid, None)
if attachment is None:
| python | {
"resource": ""
} |
q21286 | get_backreferences | train | def get_backreferences(context, relationship=None, as_brains=None):
"""Return all objects which use a UIDReferenceField to reference context.
:param context: The object which is the target of references.
:param relationship: The relationship name of the UIDReferenceField.
:param as_brains: Requests that this function returns only catalog brains.
as_brains can only be used if a relationship has been specified.
This function can be called with or without specifying a relationship.
- If a relationship is provided, the return value will be a list of items
which reference the context using the provided relationship.
If relationship is provided, then you can request that the backrefs
should be returned as catalog brains. If you do not specify as_brains,
the raw list of UIDs will be returned.
- If the relationship is not provided, then the entire set | python | {
"resource": ""
} |
q21287 | UIDReferenceField.get_relationship_key | train | def get_relationship_key(self, context):
"""Return the configured relationship key or generate a new | python | {
"resource": ""
} |
q21288 | UIDReferenceField.link_reference | train | def link_reference(self, source, target):
"""Link the target to the source
"""
target_uid = api.get_uid(target)
# get the annotation storage key
key = self.get_relationship_key(target)
# get all backreferences from the source
# N.B. only like this we get the persistent mapping!
backrefs = get_backreferences(source, relationship=None) | python | {
"resource": ""
} |
q21289 | UIDReferenceField.unlink_reference | train | def unlink_reference(self, source, target):
"""Unlink the target from the source
"""
target_uid = api.get_uid(target)
# get the storage key
key = self.get_relationship_key(target)
# get all backreferences from the source
# N.B. only like this we get the persistent mapping!
backrefs = get_backreferences(source, relationship=None)
if key not in backrefs:
logger.warn(
"Referenced object {} has no backreferences for the key {}"
.format(repr(source), | python | {
"resource": ""
} |
q21290 | UIDReferenceField.getRaw | train | def getRaw(self, context, aslist=False, **kwargs):
"""Grab the stored value, and return it directly as UIDs.
:param context: context is the object who's schema contains this field.
:type context: BaseContent
:param aslist: Forces a single-valued field to return a list type.
:type aslist: bool
:param kwargs: kwargs are passed | python | {
"resource": ""
} |
q21291 | UIDReferenceField._set_backreferences | train | def _set_backreferences(self, context, items, **kwargs):
"""Set the back references on the linked items
This will set an annotation storage on the referenced items which point
to the current context.
"""
# Don't set any references during initialization.
# This might cause a recursion error when calling `getRaw` to fetch the
# current set UIDs!
initializing = kwargs.get('_initializing_', False)
if initializing:
return
# UID of the current object
uid = api.get_uid(context)
# current set UIDs
raw = self.getRaw(context) or []
# handle single reference fields
if isinstance(raw, basestring):
raw = [raw, ]
cur = set(raw)
# UIDs to be set
new = set(map(api.get_uid, items))
# removed UIDs
removed = cur.difference(new)
# | python | {
"resource": ""
} |
q21292 | DateReceivedFieldVisibility.isVisible | train | def isVisible(self, field, mode="view", default="visible"):
"""Returns whether the field is visible in a given mode
"""
if mode != "edit":
return default
# If this is a Secondary Analysis Request, this field is not editable
if | python | {
"resource": ""
} |
q21293 | format_keyword | train | def format_keyword(keyword):
"""
Removing special character from a keyword. Analysis Services must have
this kind of keywords. E.g. if assay name from the Instrument is | python | {
"resource": ""
} |
q21294 | guard_activate | train | def guard_activate(analysis_service):
"""Returns whether the transition activate can be performed for the
analysis service passed in
"""
calculation = analysis_service.getCalculation()
if not calculation:
return True
# If the calculation is inactive, we cannot activate the service
if not api.is_active(calculation):
return False
# All services that we depend on | python | {
"resource": ""
} |
q21295 | guard_deactivate | train | def guard_deactivate(analysis_service):
"""Returns whether the transition deactivate can be performed for the
analysis service passed in
"""
for dependant in analysis_service.getServiceDependants():
| python | {
"resource": ""
} |
q21296 | AnalysisRequestsView.get_progress_percentage | train | def get_progress_percentage(self, ar_brain):
"""Returns the percentage of completeness of the Analysis Request
"""
review_state = ar_brain.review_state
if review_state == "published":
return 100
numbers = ar_brain.getAnalysesNum
num_analyses = numbers[1] or 0
if not num_analyses:
return 0
# [verified, total, not_submitted, to_be_verified]
num_to_be_verified = numbers[3] or 0
num_verified = numbers[0] or 0
# 2 steps per analysis (submit, verify) plus one step | python | {
"resource": ""
} |
q21297 | RecordsWidget.process_form | train | def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
"""
Basic impl for form processing in a widget plus allowing empty
values to be saved
"""
# a poor workaround for Plone repeating itself.
# XXX this is important XXX
key = field.getName() + '_value'
if key in instance.REQUEST:
return instance.REQUEST[key], {}
value = form.get(field.getName(), empty_marker)
# When a recordswidget's visibility is defined as hidden
# '...visible={'view': 'hidden', 'edit': 'hidden'},...' the template
# displays it as an input field with the attribute 'value' as a string
# 'value="[{:},{:}]"'. This makes the system save the content of the
# widget as the string instead of a dictionary inside a list, so we
# need to check if the variable contains a python object as a string.
if value and value is not empty_marker and isinstance(value, str):
import ast
try:
value = ast.literal_eval(form.get(field.getName()))
except:
| python | {
"resource": ""
} |
q21298 | ProxyField.get | train | def get(self, instance, **kwargs):
"""retrieves the value of the same named field on the proxy object
"""
# The default value
default = self.getDefault(instance)
# Retrieve the proxy object
proxy_object = self.get_proxy(instance)
# Return None if we could not find a proxied object, e.g. through
# the proxy expression 'context.getSample()' on an AR
if proxy_object is None:
logger.debug("Expression '{}' did not return a valid Proxy Object on {}"
.format(self.proxy, instance))
return default
| python | {
"resource": ""
} |
q21299 | ProxyField.set | train | def set(self, instance, value, **kwargs):
"""writes the value to the same named field on the proxy object
"""
# Retrieve the proxy object
proxy_object = self.get_proxy(instance)
# Return None if we could not find a proxied object, e.g. through
# the proxy expression 'context.getSample()' on an AR
if not proxy_object:
logger.debug("Expression '{}' did not return a valid Proxy Object on {}"
.format(self.proxy, instance))
return None
# Lookup the proxied field by name
field_name = self.getName()
field = proxy_object.getField(field_name)
# Bail out if the proxy object has no identical named field.
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.