function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def testCredentials(self): self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test')) cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test', self.core_instance) self.assertEqual(self.cred_instance.CheckCredential(cred_string, u'sharrell', self.core_instance), u'') self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell', self.core_instance), None)
stephenlienharrell/roster-dns-management
[ 1, 1, 1, 4, 1426209952 ]
def new_tool_type(request): if request.method == 'POST': tform = ToolTypeForm(request.POST, instance=Tool_Type()) if tform.is_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Created.', extra_tags='alert-success') return HttpResponseRedirect(reverse('tool_type', )) else: tform = ToolTypeForm() add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request) return render(request, 'dojo/new_tool_type.html', {'tform': tform})
rackerlabs/django-DefectDojo
[ 2681, 1254, 2681, 272, 1424368427 ]
def edit_tool_type(request, ttid): tool_type = Tool_Type.objects.get(pk=ttid) if request.method == 'POST': tform = ToolTypeForm(request.POST, instance=tool_type) if tform.is_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('tool_type', )) else: tform = ToolTypeForm(instance=tool_type) add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request) return render(request, 'dojo/edit_tool_type.html', { 'tform': tform, })
rackerlabs/django-DefectDojo
[ 2681, 1254, 2681, 272, 1424368427 ]
def algorithm(self): return 'Simultaneous-FA'
jabooth/menpo-archive
[ 5, 2, 5, 5, 1352724935 ]
def algorithm(self): return 'Simultaneous-FC'
jabooth/menpo-archive
[ 5, 2, 5, 5, 1352724935 ]
def _fit(self, lk_fitting, max_iters=20, project=True): # Initial error > eps error = self.eps + 1 image = lk_fitting.image lk_fitting.weights = [] n_iters = 0 # Number of shape weights n_params = self.transform.n_parameters # Initial appearance weights if project: # Obtained weights by projection IWxp = image.warp_to(self.template.mask, self.transform, interpolator=self.interpolator) weights = self.appearance_model.project(IWxp) # Reset template self.template = self.appearance_model.instance(weights) else: # Set all weights to 0 (yielding the mean) weights = np.zeros(self.appearance_model.n_active_components) lk_fitting.weights.append(weights) # Compute appearance model Jacobian wrt weights appearance_jacobian = self.appearance_model._jacobian.T # Forward Additive Algorithm while n_iters < max_iters and error > self.eps: # Compute warped image with current weights IWxp = image.warp_to(self.template.mask, self.transform, interpolator=self.interpolator) # Compute steepest descent images, VI_dW_dp J = self.residual.steepest_descent_images(IWxp, self._dW_dp) # Concatenate VI_dW_dp with appearance model Jacobian self._J = np.hstack((J, appearance_jacobian)) # Compute Hessian and inverse self._H = self.residual.calculate_hessian(self._J) # Compute steepest descent parameter updates sd_delta_p = self.residual.steepest_descent_update( self._J, self.template, IWxp) # Compute gradient descent parameter updates delta_p = np.real(self._calculate_delta_p(sd_delta_p)) # Update warp weights self.transform.compose_after_from_vector_inplace(delta_p[:n_params]) lk_fitting.parameters.append(self.transform.as_vector()) # Update appearance weights weights -= delta_p[n_params:] self.template = self.appearance_model.instance(weights) lk_fitting.weights.append(weights) # Test convergence error = np.abs(norm(delta_p)) n_iters += 1 lk_fitting.fitted = True return lk_fitting
jabooth/menpo-archive
[ 5, 2, 5, 5, 1352724935 ]
def algorithm(self): return 'Simultaneous-IA'
jabooth/menpo-archive
[ 5, 2, 5, 5, 1352724935 ]
def fuzzylogic(features, cfg, require="all"): """ FIXME: Think about, should I return 0, or have an assert, and at qc.py all qc tests are applied with a try, and in case it fails it flag 0s. """ require = cfg.get("require", require) if (require == "all") and not np.all([f in features for f in cfg["features"]]): module_logger.warning( "Not all features (%s) required by fuzzy logic are available".format( cfg["features"].keys() ) ) raise KeyError uncertainty = fuzzy_uncertainty( data=features, features=cfg["features"], output=cfg["output"], require=require ) return uncertainty
castelao/CoTeDe
[ 36, 15, 36, 9, 1369489700 ]
def set_features(self): self.features = {} for v in [f for f in self.cfg["features"] if f not in self.features]: if v == "woa_bias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_bias"] elif v == "woa_normbias": woa_comparison = woa_normbias(self.data, self.varname, self.attrs) self.features[v] = woa_comparison["woa_normbias"] elif v == "spike": self.features[v] = spike(self.data[self.varname]) elif v == "gradient": self.features[v] = gradient(self.data[self.varname]) self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg)
castelao/CoTeDe
[ 36, 15, 36, 9, 1369489700 ]
def loaded(cls): return 'cudf' in sys.modules
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def applies(cls, obj): if not cls.loaded(): return False import cudf return isinstance(obj, (cudf.DataFrame, cudf.Series))
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def init(cls, eltype, data, kdims, vdims): import cudf import pandas as pd element_params = eltype.param.objects() kdim_param = element_params['kdims'] vdim_param = element_params['vdims'] if isinstance(data, (cudf.Series, pd.Series)): data = data.to_frame() if not isinstance(data, cudf.DataFrame): data, _, _ = PandasInterface.init(eltype, data, kdims, vdims) data = cudf.from_pandas(data) columns = list(data.columns) ncols = len(columns) index_names = [data.index.name] if index_names == [None]: index_names = ['index'] if eltype._auto_indexable_1d and ncols == 1 and kdims is None: kdims = list(index_names) if isinstance(kdim_param.bounds[1], int): ndim = min([kdim_param.bounds[1], len(kdim_param.default)]) else: ndim = None nvdim = vdim_param.bounds[1] if isinstance(vdim_param.bounds[1], int) else None if kdims and vdims is None: vdims = [c for c in columns if c not in kdims] elif vdims and kdims is None: kdims = [c for c in columns if c not in vdims][:ndim] elif kdims is None: kdims = list(columns[:ndim]) if vdims is None: vdims = [d for d in columns[ndim:((ndim+nvdim) if nvdim else None)] if d not in kdims] elif kdims == [] and vdims is None: vdims = list(columns[:nvdim if nvdim else None]) # Handle reset of index if kdims reference index by name for kd in kdims: kd = dimension_name(kd) if kd in columns: continue if any(kd == ('index' if name is None else name) for name in index_names): data = data.reset_index() break if any(isinstance(d, (np.int64, int)) for d in kdims+vdims): raise DataError("cudf DataFrame column names used as dimensions " "must be strings not integers.", cls) if kdims: kdim = dimension_name(kdims[0]) if eltype._auto_indexable_1d and ncols == 1 and kdim not in columns: data = data.copy() data.insert(0, kdim, np.arange(len(data))) for d in kdims+vdims: d = dimension_name(d) if len([c for c in columns if c == d]) > 1: raise DataError('Dimensions may not reference duplicated DataFrame ' 'columns (found duplicate %r columns). If you want to plot ' 'a column against itself simply declare two dimensions ' 'with the same name. '% d, cls) return data, {'kdims':kdims, 'vdims':vdims}, {}
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def range(cls, dataset, dimension): dimension = dataset.get_dimension(dimension, strict=True) column = dataset.data[dimension.name] if dimension.nodata is not None: column = cls.replace_value(column, dimension.nodata) if column.dtype.kind == 'O': return np.NaN, np.NaN else: return finite_range(column, column.min(), column.max())
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def values(cls, dataset, dim, expanded=True, flat=True, compute=True, keep_index=False): dim = dataset.get_dimension(dim, strict=True) data = dataset.data[dim.name] if not expanded: data = data.unique() return data.values_host if compute else data.values elif keep_index: return data elif compute: return data.values_host try: return data.values except Exception: return data.values_host
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def groupby(cls, dataset, dimensions, container_type, group_type, **kwargs): # Get dimensions information dimensions = [dataset.get_dimension(d).name for d in dimensions] kdims = [kdim for kdim in dataset.kdims if kdim not in dimensions] # Update the kwargs appropriately for Element group types group_kwargs = {} group_type = dict if group_type == 'raw' else group_type if issubclass(group_type, Element): group_kwargs.update(util.get_param_values(dataset)) group_kwargs['kdims'] = kdims group_kwargs.update(kwargs) # Propagate dataset group_kwargs['dataset'] = dataset.dataset # Find all the keys along supplied dimensions keys = product(*(dataset.data[dimensions[0]].unique().values_host for d in dimensions)) # Iterate over the unique entries applying selection masks grouped_data = [] for unique_key in util.unique_iterator(keys): group_data = dataset.select(**dict(zip(dimensions, unique_key))) if not len(group_data): continue group_data = group_type(group_data, **group_kwargs) grouped_data.append((unique_key, group_data)) if issubclass(container_type, NdMapping): with item_check(False), sorted_context(False): kdims = [dataset.get_dimension(d) for d in dimensions] return container_type(grouped_data, kdims=kdims) else: return container_type(grouped_data)
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def select_mask(cls, dataset, selection): """ Given a Dataset object and a dictionary with dimension keys and selection keys (i.e. tuple ranges, slices, sets, lists, or literals) return a boolean mask over the rows in the Dataset object that have been selected. """ mask = None for dim, sel in selection.items(): if isinstance(sel, tuple): sel = slice(*sel) arr = cls.values(dataset, dim, keep_index=True) if util.isdatetime(arr) and util.pd: try: sel = util.parse_datetime_selection(sel) except: pass new_masks = [] if isinstance(sel, slice): with warnings.catch_warnings(): warnings.filterwarnings('ignore', r'invalid value encountered') if sel.start is not None: new_masks.append(sel.start <= arr) if sel.stop is not None: new_masks.append(arr < sel.stop) if not new_masks: continue new_mask = new_masks[0] for imask in new_masks[1:]: new_mask &= imask elif isinstance(sel, (set, list)): for v in sel: new_masks.append(arr==v) if not new_masks: continue new_mask = new_masks[0] for imask in new_masks[1:]: new_mask |= imask elif callable(sel): new_mask = sel(arr) else: new_mask = arr == sel if mask is None: mask = new_mask else: mask &= new_mask return mask
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def select(cls, dataset, selection_mask=None, **selection): df = dataset.data if selection_mask is None: selection_mask = cls.select_mask(dataset, selection) indexed = cls.indexed(dataset, selection) if selection_mask is not None: df = df.loc[selection_mask] if indexed and len(df) == 1 and len(dataset.vdims) == 1: return df[dataset.vdims[0].name].iloc[0] return df
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def concat_fn(cls, dataframes, **kwargs): import cudf return cudf.concat(dataframes, **kwargs)
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def add_dimension(cls, dataset, dimension, dim_pos, values, vdim): data = dataset.data.copy() if dimension.name not in data: data[dimension.name] = values return data
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def aggregate(cls, dataset, dimensions, function, **kwargs): data = dataset.data cols = [d.name for d in dataset.kdims if d in dimensions] vdims = dataset.dimensions('value', label='name') reindexed = data[cols+vdims] agg = function.__name__ if len(dimensions): agg_map = {'amin': 'min', 'amax': 'max'} agg = agg_map.get(agg, agg) grouped = reindexed.groupby(cols, sort=False) if not hasattr(grouped, agg): raise ValueError('%s aggregation is not supported on cudf DataFrame.' % agg) df = getattr(grouped, agg)().reset_index() else: agg_map = {'amin': 'min', 'amax': 'max', 'size': 'count'} agg = agg_map.get(agg, agg) if not hasattr(reindexed, agg): raise ValueError('%s aggregation is not supported on cudf DataFrame.' % agg) agg = getattr(reindexed, agg)() data = dict(((col, [v]) for col, v in zip(agg.index.values_host, agg.to_array()))) df = util.pd.DataFrame(data, columns=list(agg.index.values_host)) dropped = [] for vd in vdims: if vd not in df.columns: dropped.append(vd) return df, dropped
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def iloc(cls, dataset, index): import cudf rows, cols = index scalar = False columns = list(dataset.data.columns) if isinstance(cols, slice): cols = [d.name for d in dataset.dimensions()][cols] elif np.isscalar(cols): scalar = np.isscalar(rows) cols = [dataset.get_dimension(cols).name] else: cols = [dataset.get_dimension(d).name for d in index[1]] col_index = [columns.index(c) for c in cols] if np.isscalar(rows): rows = [rows] if scalar: return dataset.data[cols[0]].iloc[rows[0]] result = dataset.data.iloc[rows, col_index] # cuDF does not handle single rows and cols indexing correctly # as of cudf=0.10.0 so we have to convert Series back to DataFrame if isinstance(result, cudf.Series): if len(cols) == 1: result = result.to_frame(cols[0]) else: result = result.to_frame().T return result
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def sort(cls, dataset, by=[], reverse=False): cols = [dataset.get_dimension(d, strict=True).name for d in by] return dataset.data.sort_values(by=cols, ascending=not reverse)
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def dframe(cls, dataset, dimensions): if dimensions: return dataset.data[dimensions].to_pandas() else: return dataset.data.to_pandas()
ioam/holoviews
[ 2392, 373, 2392, 992, 1399481962 ]
def __init__(self, **kwargs): """ Initializes a VMResync instance Notes: You can specify all parameters while calling this methods. A special argument named `data` will enable you to load the object from a Python dictionary Examples: >>> vmresync = NUVMResync(id=u'xxxx-xxx-xxx-xxx', name=u'VMResync') >>> vmresync = NUVMResync(data=my_dict) """ super(NUVMResync, self).__init__() # Read/Write Attributes
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def last_request_timestamp(self): """ Get last_request_timestamp value. Notes: Time of the last timestamp received
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def last_request_timestamp(self, value): """ Set last_request_timestamp value. Notes: Time of the last timestamp received
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def last_time_resync_initiated(self): """ Get last_time_resync_initiated value. Notes: Time that the resync was initiated
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def last_time_resync_initiated(self, value): """ Set last_time_resync_initiated value. Notes: Time that the resync was initiated
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def last_updated_by(self): """ Get last_updated_by value. Notes: ID of the user who last updated the object.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def last_updated_by(self, value): """ Set last_updated_by value. Notes: ID of the user who last updated the object.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def last_updated_date(self): """ Get last_updated_date value. Notes: Time stamp when this object was last updated.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def last_updated_date(self, value): """ Set last_updated_date value. Notes: Time stamp when this object was last updated.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def embedded_metadata(self): """ Get embedded_metadata value. Notes: Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def embedded_metadata(self, value): """ Set embedded_metadata value. Notes: Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def entity_scope(self): """ Get entity_scope value. Notes: Specify if scope of entity is Data center or Enterprise level
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def entity_scope(self, value): """ Set entity_scope value. Notes: Specify if scope of entity is Data center or Enterprise level
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def creation_date(self): """ Get creation_date value. Notes: Time stamp when this object was created.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def creation_date(self, value): """ Set creation_date value. Notes: Time stamp when this object was created.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def status(self): """ Get status value. Notes: Status of the resync
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def status(self, value): """ Set status value. Notes: Status of the resync
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def owner(self): """ Get owner value. Notes: Identifies the user that has created this object.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def owner(self, value): """ Set owner value. Notes: Identifies the user that has created this object.
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def external_id(self): """ Get external_id value. Notes: External object ID. Used for integration with third party systems
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def external_id(self, value): """ Set external_id value. Notes: External object ID. Used for integration with third party systems
nuagenetworks/vspk-python
[ 19, 18, 19, 7, 1457133058 ]
def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)'
ric2b/Vivaldi-browser
[ 131, 27, 131, 3, 1490828945 ]
def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step)
ric2b/Vivaldi-browser
[ 131, 27, 131, 3, 1490828945 ]
def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv
ric2b/Vivaldi-browser
[ 131, 27, 131, 3, 1490828945 ]
def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m))
ric2b/Vivaldi-browser
[ 131, 27, 131, 3, 1490828945 ]
def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build)
ric2b/Vivaldi-browser
[ 131, 27, 131, 3, 1490828945 ]
def index(): """Produces a list of the feedback obtained for a given venue, or for all venues.""" venue_id = request.args(0) if venue_id == 'all': q = (db.submission.user == get_user_email()) else: q = ((db.submission.user == get_user_email()) & (db.submission.venue_id == venue_id)) db.submission.id.represent = lambda x, r: A(T('View'), _class='btn', _href=URL('submission', 'view_own_submission', args=['v', r.id])) db.submission.id.label = T('Submission') db.submission.id.readable = True db.submission.venue_id.readable = True grid = SQLFORM.grid(q, fields=[db.submission.id, db.submission.venue_id, db.submission.date_created, db.submission.date_updated, ], csv=False, details=False, create=False, editable=False, deletable=False, args=request.args[:1], maxtextlength=24, ) return dict(grid=grid)
lucadealfaro/crowdranker
[ 5, 5, 5, 1, 1360596564 ]
def view_feedback(): """Shows detailed feedback for a user in a venue. This controller accepts various types of arguments: * 's', submission_id * 'u', venue_id, username * 'v', venue_id (in which case, shows own submission to that venue) """ if len(request.args) == 0: redirect(URL('default', 'index')) if request.args(0) == 's': # submission_id n_args = 2 subm = db.submission(request.args(1)) or redirect(URL('default', 'index')) c = db.venue(subm.venue_id) or redirect(URL('default', 'index')) username = subm.user elif request.args(0) == 'v': # venue_id n_args = 2 c = db.venue(request.args(1)) or redirect(URL('default', 'index')) username = get_user_email() subm = db((db.submission.user == username) & (db.submission.venue_id == c.id)).select().first() else: # venue_id, username n_args = 3 c = db.venue(request.args(1)) or redirect(URL('default', 'index')) username = request.args(2) or redirect(URL('default', 'index')) subm = db((db.submission.user == username) & (db.submission.venue_id == c.id)).select().first() # Checks permissions. props = db(db.user_properties.user == get_user_email()).select().first() if props == None: session.flash = T('Not authorized.') redirect(URL('default', 'index')) is_author = (username == get_user_email()) can_view_feedback = access.can_view_feedback(c, props) or is_author if (not can_view_feedback): session.flash = T('Not authorized.') redirect(URL('default', 'index')) if not (access.can_view_feedback(c, props) or datetime.utcnow() > c.rate_close_date): session.flash = T('The ratings are not yet available.') redirect(URL('feedback', 'index', args=['all'])) # Produces the link to edit the feedback. edit_feedback_link = None if subm is not None and access.can_observe(c, props): edit_feedback_link = A(T('Edit feedback'), _class='btn', _href=URL('submission', 'edit_feedback', args=[subm.id])) # Produces the download link. download_link = None if subm is not None and c.allow_file_upload and subm.content is not None: if is_author: download_link = A(T('Download'), _class='btn', _href=URL('submission', 'download_author', args=[subm.id, subm.content])) else: download_link = A(T('Download'), _class='btn', _href=URL('submission', 'download_manager', args=[subm.id, subm.content])) venue_link = A(c.name, _href=URL('venues', 'view_venue', args=[c.id])) # Submission link. subm_link = None if subm is not None and c.allow_link_submission: subm_link = A(subm.link, _href=subm.link) # Submission content and feedback. subm_comment = None subm_feedback = None if subm is not None: raw_subm_comment = keystore_read(subm.comment) if raw_subm_comment is not None and len(raw_subm_comment) > 0: subm_comment = MARKMIN(keystore_read(subm.comment)) raw_feedback = keystore_read(subm.feedback) if raw_feedback is not None and len(raw_feedback) > 0: subm_feedback = MARKMIN(raw_feedback) # Display settings. db.submission.percentile.readable = True db.submission.comment.readable = True db.submission.feedback.readable = True if access.can_observe(c, props): db.submission.quality.readable = True db.submission.error.readable = True # Reads the grade information. submission_grade = submission_percentile = None review_grade = review_percentile = user_reputation = None final_grade = final_percentile = None assigned_grade = None if c.grades_released: grade_info = db((db.grades.user == username) & (db.grades.venue_id == c.id)).select().first() if grade_info is not None: submission_grade = represent_quality(grade_info.submission_grade, None) submission_percentile = represent_percentage(grade_info.submission_percentile, None) review_grade = represent_quality_10(grade_info.accuracy, None) review_percentile = represent_percentage(grade_info.accuracy_percentile, None) user_reputation = represent_01_as_percentage(grade_info.reputation, None) final_grade = represent_quality(grade_info.grade, None) final_percentile = represent_percentage(grade_info.percentile, None) assigned_grade = represent_quality(grade_info.assigned_grade, None) # Makes a grid of comments. db.task.submission_name.readable = False db.task.assigned_date.readable = False db.task.completed_date.readable = False db.task.rejected.readable = True db.task.helpfulness.readable = db.task.helpfulness.writable = True # Prevent editing the comments; the only thing editable should be the "is bogus" field. db.task.comments.writable = False db.task.comments.readable = True ranking_link = None if access.can_observe(c, props): db.task.user.readable = True db.task.completed_date.readable = True links = [ dict(header=T('Review details'), body= lambda r: A(T('View'), _class='btn', _href=URL('ranking', 'view_comparison', args=[r.id]))), ] details = False if subm is not None: ranking_link = A(T('details'), _href=URL('ranking', 'view_comparisons_given_submission', args=[subm.id])) reviews_link = A(T('details'), _href=URL('ranking', 'view_comparisons_given_user', args=[username, c.id])) db.task.user.represent = lambda v, r: A(v, _href=URL('ranking', 'view_comparisons_given_user', args=[v, c.id], user_signature=True)) else: user_reputation = None links = [ dict(header=T('Review feedback'), body = lambda r: A(T('Give feedback'), _class='btn', _href=URL('feedback', 'reply_to_review', args=[r.id], user_signature=True))), ] details = False ranking_link = None reviews_link = None if subm is not None: q = ((db.task.submission_id == subm.id) & (db.task.is_completed == True)) # q = (db.task.submission_id == subm.id) else: q = (db.task.id == -1) grid = SQLFORM.grid(q, fields=[db.task.id, db.task.user, db.task.rejected, db.task.comments, db.task.helpfulness, ], details = details, csv=False, create=False, editable=False, deletable=False, searchable=False, links=links, args=request.args[:n_args], maxtextlength=24, ) return dict(subm=subm, download_link=download_link, subm_link=subm_link, username=username, subm_comment=subm_comment, subm_feedback=subm_feedback, edit_feedback_link=edit_feedback_link, is_admin=is_user_admin(), submission_grade=submission_grade, submission_percentile=submission_percentile, review_grade=review_grade, review_percentile=review_percentile, user_reputation=user_reputation, final_grade=final_grade, final_percentile=final_percentile, assigned_grade=assigned_grade, venue_link=venue_link, grid=grid, ranking_link=ranking_link, reviews_link=reviews_link)
lucadealfaro/crowdranker
[ 5, 5, 5, 1, 1360596564 ]
def reply_to_review(): t = db.task(request.args(0)) or redirect(URL('default', 'index')) db.task.submission_name.readable = False db.task.assigned_date.readable = False db.task.completed_date.readable = False db.task.comments.readable = False db.task.helpfulness.readable = db.task.helpfulness.writable = True db.task.feedback.readable = db.task.feedback.writable = True form = SQLFORM(db.task, record=t) form.vars.feedback = keystore_read(t.feedback) if form.process(onvalidation=validate_review_feedback(t)).accepted: session.flash = T('Updated.') redirect(URL('feedback', 'view_feedback', args=['s', t.submission_id])) link_to_submission = A(T('View submission'), _href=URL('submission', 'view_own_submission', args=['v', t.submission_id])) review_comments = MARKMIN(keystore_read(t.comments)) return dict(form=form, link_to_submission=link_to_submission, review_comments=review_comments)
lucadealfaro/crowdranker
[ 5, 5, 5, 1, 1360596564 ]
def validate_review_feedback(t): def f(form): if not form.errors: feedback_id = keystore_update(t.feedback, form.vars.feedback) form.vars.feedback = feedback_id return f
lucadealfaro/crowdranker
[ 5, 5, 5, 1, 1360596564 ]
def __init__(self, message, response=None): super(RequestError, self).__init__(message) self.response = response
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def __init__(self, content): etree = lxml.etree.fromstring(content) # noqa: S320 self.init_response_attributes(etree)
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def execute(cls, **kwargs): url = cls._get_url() headers = { 'content-type': 'text/xml', 'SOAPAction': url, } data = cls.template.strip().format( AP_ID=cls.settings['AP_ID'], AP_PWD=cls.settings['AP_PWD'], Instant=cls._format_datetime(timezone.now()), DNSName=cls.settings['DNSName'], **kwargs ) cert = (cls.settings['cert_path'], cls.settings['key_path']) # TODO: add verification logger.debug( 'Executing POST request to %s with data:\n %s \nheaders: %s', url, data, headers, ) response = requests.post( url, data=data, headers=headers, cert=cert, verify=cls.settings['verify_ssl'], ) if response.ok: return cls.response_class(response.content) else: message = ( 'Failed to execute POST request against %s endpoint. Response [%s]: %s' % (url, response.status_code, response.content) ) raise RequestError(message, response)
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def _format_datetime(cls, d): return d.strftime('%Y-%m-%dT%H:%M:%S.000Z')
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def _format_transaction_id(cls, transaction_id): return ('_' + transaction_id)[:32] # such formation is required by server.
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def _get_url(cls): return urljoin(cls.settings['URL'], cls.url)
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def init_response_attributes(self, etree): try: self.backend_transaction_id = etree.xpath('//MSS_SignatureResp')[0].attrib[ 'MSSP_TransID' ] self.status = etree.xpath( '//ns6:StatusCode', namespaces={'ns6': self.ns_namespace} )[0].attrib['Value'] except (IndexError, KeyError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse signature response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) )
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def execute(cls, transaction_id, phone, message): kwargs = { 'MessagingMode': 'asynchClientServer', 'AP_TransID': cls._format_transaction_id(transaction_id), 'MSISDN': phone, 'DataToBeSigned': '%s %s' % (cls.settings['message_prefix'], message), 'SignatureProfile': cls.settings['SignatureProfile'], } return super(SignatureRequest, cls).execute(**kwargs)
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def map(cls, status_code): if status_code == '502': return cls.OK elif status_code == '504': return cls.PROCESSING else: raise UnknownStatusError( 'Received unsupported status in response: %s' % status_code )
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def init_response_attributes(self, etree): try: status_code = etree.xpath( '//ns5:StatusCode', namespaces={'ns5': self.ns_namespace} )[0].attrib['Value'] except (IndexError, KeyError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse status response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) ) self.status = Statuses.map(status_code) try: civil_number_tag = etree.xpath( '//ns4:UserIdentifier', namespaces={'ns4': self.ns_namespace} )[0] except IndexError: # civil number tag does not exist - this is possible if request is still processing return else: try: self.civil_number = civil_number_tag.text.split('=')[1] except IndexError: raise ResponseParseError( 'Cannot get civil_number from tag text: %s' % civil_number_tag.text )
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def init_response_attributes(self, etree): self.status = Statuses.ERRED try: self.details = etree.xpath( '//soapenv:Text', namespaces={'soapenv': self.soapenv_namespace} )[0].text except (IndexError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse error status response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) )
opennode/nodeconductor-assembly-waldur
[ 39, 35, 39, 3, 1484854426 ]
def create(kernel): result = Static() result.template = "object/static/item/shared_armor_composite_helmet.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object")
anhstudios/swganh
[ 62, 37, 62, 37, 1297996365 ]
def csrf_exempt(func): return func
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def __new__(cls, meta=None): overrides = {}
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def __new__(cls, name, bases, attrs): attrs['base_fields'] = {} declared_fields = {}
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def __init__(self, api_name=None): self.fields = deepcopy(self.base_fields)
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def __getattr__(self, name): if name in self.fields: return self.fields[name]
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def wrap_view(self, view): """ Wraps methods so they can be called in a more functional way as well as handling exceptions better.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def wrapper(request, *args, **kwargs): try: callback = getattr(self, view) response = callback(request, *args, **kwargs)
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def _handle_500(self, request, exception): import traceback import sys the_trace = '\n'.join(traceback.format_exception(*(sys.exc_info())))
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def _build_reverse_url(self, name, args=None, kwargs=None): """ A convenience hook for overriding how URLs are built.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def base_urls(self): """ The standard URLs this ``Resource`` should respond to. """ # Due to the way Django parses URLs, ``get_multiple`` won't work without # a trailing slash. return [ url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_list'), name="api_dispatch_list"), url(r"^(?P<resource_name>%s)/schema%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_schema'), name="api_get_schema"), url(r"^(?P<resource_name>%s)/set/(?P<pk_list>\w[\w/;-]*)/$" % self._meta.resource_name, self.wrap_view('get_multiple'), name="api_get_multiple"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), ]
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def override_urls(self): """ A hook for adding your own URLs or overriding the default URLs. """ return []
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def urls(self): """ The endpoints this ``Resource`` responds to.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def determine_format(self, request): """ Used to determine the desired format.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def serialize(self, request, data, format, options=None): """ Given a request, data and a desired format, produces a serialized version suitable for transfer over the wire.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def deserialize(self, request, data, format='application/json'): """ Given a request, data and a format, deserializes the given data.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def dispatch_list(self, request, **kwargs): """ A view for handling the various HTTP methods (GET/POST/PUT/DELETE) over the entire list of resources.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def dispatch_detail(self, request, **kwargs): """ A view for handling the various HTTP methods (GET/POST/PUT/DELETE) on a single resource.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def dispatch(self, request_type, request, **kwargs): """ Handles the common operations (allowed HTTP method, authentication, throttling, method lookup) surrounding most CRUD interactions. """ allowed_methods = getattr(self._meta, "%s_allowed_methods" % request_type, None) request_method = self.method_check(request, allowed=allowed_methods)
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def remove_api_resource_names(self, url_dict): """ Given a dictionary of regex matches from a URLconf, removes ``api_name`` and/or ``resource_name`` if found.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def method_check(self, request, allowed=None): """ Ensures that the HTTP method used on the request is allowed to be handled by the resource.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def is_authorized(self, request, object=None): """ Handles checking of permissions to see if the user has authorization to GET, POST, PUT, or DELETE this resource. If ``object`` is provided, the authorization backend can apply additional row-level permissions checking. """ auth_result = self._meta.authorization.is_authorized(request, object) if isinstance(auth_result, HttpResponse): raise ImmediateHttpResponse(response=auth_result)
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def is_authenticated(self, request): """ Handles checking if the user is authenticated and dealing with unauthenticated users.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def throttle_check(self, request): """ Handles checking if the user should be throttled.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def log_throttled_access(self, request): """ Handles the recording of the user's access for throttling purposes.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def build_bundle(self, obj=None, data=None): """ Given either an object, a data dictionary or both, builds a ``Bundle`` for use throughout the ``dehydrate/hydrate`` cycle.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def build_filters(self, filters=None): """ Allows for the filtering of applicable objects.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def apply_sorting(self, obj_list, options=None): """ Allows for the sorting of objects being returned.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def get_resource_uri(self, bundle_or_obj): """ This needs to be implemented at the user level.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def get_resource_list_uri(self): """ Returns a URL specific to this resource's list endpoint. """ kwargs = { 'resource_name': self._meta.resource_name, }
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def get_via_uri(self, uri): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def full_dehydrate(self, obj): """ Given an object instance, extract the information from it to populate the resource. """ bundle = Bundle(obj=obj)
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def dehydrate(self, bundle): """ A hook to allow a final manipulation of data once all fields/methods have built out the dehydrated data.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def full_hydrate(self, bundle): """ Given a populated bundle, distill it and turn it back into a full-fledged object instance. """ if bundle.obj is None: bundle.obj = self._meta.object_class()
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def hydrate(self, bundle): """ A hook to allow a final manipulation of data once all fields/methods have built out the hydrated data.
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]
def hydrate_m2m(self, bundle): """ Populate the ManyToMany data on the instance. """ if bundle.obj is None: raise HydrationError("You must call 'full_hydrate' before attempting to run 'hydrate_m2m' on %r." % self)
colinsullivan/bingo-board
[ 5, 1, 5, 6, 1293081853 ]