code
stringlengths
1
18.2k
def get_context_data(self, **kwargs): ''' Generic list view with validation included and object transfering support ''' # Call the base implementation first to get a context context = super(GenList, self).get_context_data(**kwargs) # Update general context with the stuff we already calculated context.update(self.__cont...
= getattr(self, 'export_excel', True) context['export_name'] = getattr(self, 'export_name', 'list') # Check ngincludes context['ngincludes'] = getattr(self, 'ngincludes', {}) if 'table' not in context['ngincludes'].keys(): context['ngincludes']['table'] = "{}codenerix/partials/table.html".format(settings.STATIC_URL) # ...
False) # Set search filter button context['search_filter_button'] = getattr(self, 'search_filter_button', False) # Get base template if not self.json_worker: template_base = getattr(self, 'template_base', 'base/base') template_base_ext = getattr(self, 'template_base_ext', 'html') context['template_base'] = get_template...
= unicode except NameError: unicodetest = str if isinstance(object_id, str) or isinstance(object_id, unicodetest): # If object_id is a string, we have a name not an object context['object_name'] = object_id object_obj = None else: # If is not an string if object_id: # If we got one, load the object obj = context['obj']...
None context['object_obj'] = object_obj # Attach extra_context context.update(self.extra_context) # Return new context return context
def get_context_json(self, context): ''' Return a base answer for a json answer ''' # Initialize answer answer = {} # Metadata builder answer['meta'] = self.__jcontext_metadata(context) # Filter builder answer['filter'] = self.__jcontext_filter(context) # Head builder answer['table'] = {} answer['table']['head'] = self...
def set_context_json(self, jsonquery): ''' Get a json parameter and rebuild the context back to a dictionary (probably kwargs) ''' # Make sure we are getting dicts if type(jsonquery) != dict: raise IOError("set_json_context() method can be called only with dictionaries, you gave me a '{}'".format(type(jsonquery))) # Se...
in ['search', 'search_filter_button', 'page', 'pages_to_bring', 'rowsperpage', 'filters', 'year', 'month', 'day', 'hour', 'minute', 'second']: if key in jsonquery: newget[key] = jsonquery[key] # Add transformed ordering json_ordering = jsonquery.get('ordering', None) if json_ordering: # Convert to list ordering = [] fo...
ordering newget['ordering'] = [] for orderer in ordering: key = list(orderer.keys())[0] value = orderer[key] if value > 0: value = 'asc' elif value < 0: value = 'desc' else: value = None if value: newget['ordering'].append({key: value}) # Get listid newget['listid'] = jsonquery.get("listid", None) # Get elementid newge...
def dispatch(self, request, **kwargs): ''' Entry point for this class, here we decide basic stuff ''' # Check if this is a webservice request self.json_worker = (bool(getattr(self.request, "authtoken", False))) or (self.json is True) self.__authtoken = (bool(getattr(self.request, "authtoken", False))) # Check if this i...
body.decode("utf-8") post = json.loads(body) for key in post: if type(post[key]) == dict and '__JSON_DATA__' in post[key]: post[key] = json.dumps(post[key]['__JSON_DATA__']) request.POST.update(post) # Set class internal variables self._setup(request) # Call the base implementation return super(GenModify, self).dispatc...
def get_form(self, form_class=None): ''' Set form groups to the groups specified in the view if defined ''' formobj = super(GenModify, self).get_form(form_class) # Set requested group to this form selfgroups = getattr(self, "form_groups", None) if selfgroups: if type(selfgroups) == list: formobj.__groups__ = lambda: se...
return formobj
def dispatch(self, request, **kwargs): ''' Entry point for this class, here we decide basic stuff ''' # Delete method must happen with POST not with GET if request.method == 'POST': # Check if this is a webservice request self.__authtoken = (bool(getattr(self.request, "authtoken", False))) self.json_worker = self.__aut...
True, 'errortxt': _('Method not allowed, use POST to delete or DELETE on the detail url'), }) return HttpResponse(json_answer, content_type='application/json')
def dispatch(self, request, **kwargs): ''' Entry point for this class, here we decide basic stuff ''' # Check if this is a REST query to pusth the answer to responde in JSON if bool(self.request.META.get('HTTP_X_REST', False)): self.json = True # Check if this is a REST query to add an element if self.request.method in...
= 'delete' # Set new method self.request.method == 'POST' # Find the URL target = get_class(resolve("{}/{}".format(self.request.META.get("REQUEST_URI"), action)).func) # Make sure we will answer as an API target.json = True # Lets go for it return target.as_view()(self.request, pk=kwargs.get('pk')) # Detect if we have ...
AJAX request if (request.is_ajax() or self.json_worker) and request.body: request.POST = json.loads(request.body) # Set class internal variables self._setup(request) # Call the base implementation return super(GenDetail, self).dispatch(request, **kwargs)
def get_filled_structure(self, subgroup=None): ''' method in charged of filling an structure containing the object fields values taking into account the 'group' attribute from the corresponding form object, which is necesary to fill the details form as it is configured in the 'group' attribute ''' # initilize the resul...
= model_to_dict(self.object) # generallically some common or specific fields are not interesting if 'exclude_fields' not in dir(self): self.exclude_fields = [] self.exclude_fields.append("id") for field in (self.exclude_fields): if field in object_content.keys(): object_content.pop(field) # following is going to be cre...
found fields in the groups structure are going to be taked into account gr_object_content = [] if subgroup: group_array = subgroup else: group_array = self.groups for group in group_array: # raise Exception(group) item = {} item["name"] = smart_text(group[0]) item["col"] = group[1] item_elements = group[2:] sublist = [...
1) and (type(item_element) == tuple): # Recursive sublist.append(self.get_filled_structure([subgroup])) else: filter_field = None # Check if it is a list if type(item_element) == list: # if it is a list, that means that can be found the # corresponding values for colums and any other field = item_element[0] # take into...
>= 3 and item_element[2]: verbose_names[field] = _(item_element[2]) if len(item_element) >= 9: filter_field = item_element[8] else: field = item_element if field not in verbose_names: if field.startswith('get_') and field.endswith('_display'): label_field = remove_getdisplay(field) if self.model: try: verbose_names[fie...
is None: try: verbose_names[field] = self.object._meta.get_field(field_split).verbose_name except AttributeError: pass except FieldDoesNotExist: pass value = getattr(self.object, field_split, None) else: try: verbose_names[field] = value._meta.get_field(field_split).verbose_name except AttributeError: pass except Field...
= self.request # Call the method value = value(**args) sublist.append({ "name": _(verbose_names[field]), "value": value, "filter": filter_field, }) gr_object_content.append(field) # Increment index idx += 1 item["value"] = sublist result.append(item) for field in object_content.keys(): item = {} if field not in gr_obje...
def flatatt(attrs): """ Pilfered from `django.forms.utils`: Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. Otherwise, the value is formatted through its...
that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. The result is passed through 'mark_safe' (by way of 'format_html_join'). """ key_value_attrs = [] boolean_attrs = [] for attr, value in attrs.items(): if isinstance(value, bool): if value: boolean_attrs.append((...
+ format_html_join('', ' {}', sorted(boolean_attrs)) )
def _compute_k(self, tau): r"""Evaluate the kernel directly at the given values of `tau`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. Returns ------- k : :py:class:`Array`, (`M`,) :math:`k(\tau)` (less the :math:`\sigma^2` prefactor). """ y = self._compute_y(tau) return y**...
def _compute_dk_dy(self, y, n): """Evaluate the derivative of the outer form of the RQ kernel. Parameters ---------- y : :py:class:`Array`, (`M`,) `M` inputs to evaluate at. n : non-negative scalar int Order of derivative to compute. Returns ------- dk_dy : :py:class:`Array`, (`M`,) Specified derivative at specified lo...
def get_parent(self, directory): """ Given a directory name, return the Page representing it in the menu heirarchy. """ assert settings.PAGE_DIR.startswith('/') assert settings.PAGE_DIR.endswith('/') parents = directory[len(settings.PAGE_DIR):] page = None if parents: for slug in parents.split('/'): page = Page.objects...
def wafer_sso_url(context, sso_method): ''' Return the correct URL to SSO with the given method. ''' request = context.request url = reverse(getattr(views, '%s_login' % sso_method)) if 'next' in request.GET: url += '?' + urlencode({'next': request.GET['next']}) return url
def authorize(args): """ Authorizes Coursera's OAuth2 client for using coursera.org API servers for a specific application """ oauth2_instance = oauth2.build_oauth2(args.app, args) oauth2_instance.build_authorizer() logging.info('Application "%s" authorized!', args.app)
def check_auth(args): """ Checks courseraoauth2client's connectivity to the coursera.org API servers for a specific application """ oauth2_instance = oauth2.build_oauth2(args.app, args) auth = oauth2_instance.build_authorizer() my_profile_url = ( 'https://api.coursera.org/api/externalBasicProfiles.v1?' 'q=me&fields=nam...
of the response body %s', r.text) external_id = None try: name = r.json()['elements'][0]['name'] except: logging.error( 'Could not parse the name out of the response body %s', r.text) name = None if not args.quiet > 0: print 'Name: %s' % name print 'External ID: %s' % external_id if name is None or external_id is None:...
def display_auth_cache(args): ''' Writes to the screen the state of the authentication cache. (For debugging authentication issues.) BEWARE: DO NOT email the output of this command!!! You must keep the tokens secure. Treat them as passwords. ''' oauth2_instance = oauth2.build_oauth2(args.app, args) if not args.quiet > ...
token: %s" % token expires_time = oauth2_instance.token_cache['expires'] expires_in = int((expires_time - time.time()) * 10) / 10.0 print "Auth token expires in: %s seconds." % expires_in if 'refresh' in oauth2_instance.token_cache: refresh = oauth2_instance.token_cache['refresh'] if not args.no_truncate and refresh is...
def tanh_warp_arb(X, l1, l2, lw, x0): r"""Warps the `X` coordinate with the tanh model .. math:: l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w} Parameters ---------- X : :py:class:`Array`, (`M`,) or scalar float `M` locations to evaluate length scale at. l1 : positive float Small-`X` saturation val...
: positive float Length scale of the transition between the two length scales. x0 : float Location of the center of the transition between the two length scales. Returns ------- l : :py:class:`Array`, (`M`,) or scalar float The value of the length scale at the specified point. """ if isinstance(X, scipy.ndarray): if is...
- (l1 - l2) * scipy.tanh((X - x0) / lw)) else: return 0.5 * ((l1 + l2) - (l1 - l2) * mpmath.tanh((X - x0) / lw))
def gauss_warp_arb(X, l1, l2, lw, x0): r"""Warps the `X` coordinate with a Gaussian-shaped divot. .. math:: l = l_1 - (l_1 - l_2) \exp\left ( -4\ln 2\frac{(X-x_0)^2}{l_{w}^{2}} \right ) Parameters ---------- X : :py:class:`Array`, (`M`,) or scalar float `M` locations to evaluate length scale at. l1 : positive float Glo...
scale. lw : positive float Width of the dip. x0 : float Location of the center of the dip in length scale. Returns ------- l : :py:class:`Array`, (`M`,) or scalar float The value of the length scale at the specified point. """ if isinstance(X, scipy.ndarray): if isinstance(X, scipy.matrix): X = scipy.asarray(X, dtype=f...
- x0)**2.0 / (lw**2.0)) else: return l1 - (l1 - l2) * mpmath.exp(-4.0 * mpmath.log(2.0) * (X - x0)**2.0 / (lw**2.0))
def tanh_warp(x, n, l1, l2, lw, x0): r"""Implements a tanh warping function and its derivative. .. math:: l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w} Parameters ---------- x : float or array of float Locations to evaluate the function at. n : int Derivative order to take. Used for ALL of the poi...
float Right saturation value. lw : positive float Transition width. x0 : float Transition location. Returns ------- l : float or array Warped length scale at the given locations. Raises ------ NotImplementedError If `n` > 1. """ if n == 0: return (l1 + l2) / 2.0 - (l1 - l2) / 2.0 * scipy.tanh((x - x0) / lw) elif n == 1...
-(l1 - l2) / (2.0 * lw) * (scipy.cosh((x - x0) / lw))**(-2.0) else: raise NotImplementedError("Only derivatives up to order 1 are supported!")
def double_tanh_warp(x, n, lcore, lmid, ledge, la, lb, xa, xb): r"""Implements a sum-of-tanh warping function and its derivative. .. math:: l = a\tanh\frac{x-x_a}{l_a} + b\tanh\frac{x-x_b}{l_b} Parameters ---------- x : float or array of float Locations to evaluate the function at. n : int Derivative order to take. Use...
scale. ledge : float Edge length scale. la : positive float Transition of first tanh. lb : positive float Transition of second tanh. xa : float Transition of first tanh. xb : float Transition of second tanh. Returns ------- l : float or array Warped length scale at the given locations. Raises ------ NotImplementedError...
0, 0.5], [0, 0.5, -0.5], [0.5, 0.5, 0]], [[lcore], [ledge], [lmid]]) a = a[0] b = b[0] c = c[0] if n == 0: return a * scipy.tanh((x - xa) / la) + b * scipy.tanh((x - xb) / lb) + c elif n == 1: return (a / la * (scipy.cosh((x - xa) / la))**(-2.0) + b / lb * (scipy.cosh((x - xb)
/ lb))**(-2.0)) else: raise NotImplementedError("Only derivatives up to order 1 are supported!")
def cubic_bucket_warp(x, n, l1, l2, l3, x0, w1, w2, w3): """Warps the length scale with a piecewise cubic "bucket" shape. Parameters ---------- x : float or array-like of float Locations to evaluate length scale at. n : non-negative int Derivative order to evaluate. Only first derivatives are supported. l1 : positive f...
Length scale in the bucket. l3 : positive float Length scale to the right of the bucket. x0 : float Location of the center of the bucket. w1 : positive float Width of the left side cubic section. w2 : positive float Width of the bucket. w3 : positive float Width of the right side cubic section. """ x1 = x0 - w2 /
2.0 - w1 / 2.0 x2 = x0 + w2 / 2.0 + w3 / 2.0 x_shift_1 = (x - x1 + w1 / 2.0) / w1 x_shift_2 = (x - x2 + w3 / 2.0) / w3 if n == 0: return ( l1 * (x <= (x1 - w1 / 2.0)) + ( -2.0 * (l2 - l1) * (x_shift_1**3 - 3.0
/ 2.0 * x_shift_1**2) + l1 ) * ((x > (x1 - w1 / 2.0)) & (x < (x1 + w1 / 2.0))) + l2 * ((x >= (x1 + w1 / 2.0)) & (x <= x2 - w3 / 2.0)) + ( -2.0 * (l3 - l2) * (x_shift_2**3 - 3.0 / 2.0 * x_shift_2**2) + l2 ) * ((x > (x2 -
w3 / 2.0)) & (x < (x2 + w3 / 2.0))) + l3 * (x >= (x2 + w3 / 2.0)) ) elif n == 1: return ( ( -2.0 * (l2 - l1) * (3 * x_shift_1**2 - 3.0 * x_shift_1) / w1 ) * ((x > (x1 - w1 / 2.0)) & (x < (x1 + w1 / 2.0))) + ( -2.0
* (l3 - l2) * (3 * x_shift_2**2 - 3.0 * x_shift_2) / w3 ) * ((x > (x2 - w3 / 2.0)) & (x < (x2 + w3 / 2.0))) ) else: raise NotImplementedError("Only up to first derivatives are supported!")
def quintic_bucket_warp(x, n, l1, l2, l3, x0, w1, w2, w3): """Warps the length scale with a piecewise quintic "bucket" shape. Parameters ---------- x : float or array-like of float Locations to evaluate length scale at. n : non-negative int Derivative order to evaluate. Only first derivatives are supported. l1 : positi...
Length scale in the bucket. l3 : positive float Length scale to the right of the bucket. x0 : float Location of the center of the bucket. w1 : positive float Width of the left side quintic section. w2 : positive float Width of the bucket. w3 : positive float Width of the right side quintic section. """ x1 = x0 - w2 /
2.0 - w1 / 2.0 x2 = x0 + w2 / 2.0 + w3 / 2.0 x_shift_1 = 2.0 * (x - x1) / w1 x_shift_3 = 2.0 * (x - x2) / w3 if n == 0: return ( l1 * (x <= (x1 - w1 / 2.0)) + ( 0.5 * (l2 - l1) * ( 3.0 / 8.0 * x_shift_1**5 -
5.0 / 4.0 * x_shift_1**3 + 15.0 / 8.0 * x_shift_1 ) + (l1 + l2) / 2.0 ) * ((x > (x1 - w1 / 2.0)) & (x < (x1 + w1 / 2.0))) + l2 * ((x >= (x1 + w1 / 2.0)) & (x <= x2 - w3 / 2.0)) + ( 0.5 * (l3 - l2) * ( 3.0 /
8.0 * x_shift_3**5 - 5.0 / 4.0 * x_shift_3**3 + 15.0 / 8.0 * x_shift_3 ) + (l2 + l3) / 2.0 ) * ((x > (x2 - w3 / 2.0)) & (x < (x2 + w3 / 2.0))) + l3 * (x >= (x2 + w3 / 2.0)) ) elif n == 1: return ( ( 0.5 * (l2 - l1) * (
5.0 * 3.0 / 8.0 * x_shift_1**4 - 3.0 * 5.0 / 4.0 * x_shift_1**2 + 15.0 / 8.0 ) / w1 ) * ((x > (x1 - w1 / 2.0)) & (x < (x1 + w1 / 2.0))) + ( 0.5 * (l3 - l2) * ( 5.0 * 3.0 / 8.0 * x_shift_3**4 - 3.0 * 5.0 / 4.0 * x_shift_3**2 +
15.0 / 8.0 ) / w3 ) * ((x > (x2 - w3 / 2.0)) & (x < (x2 + w3 / 2.0))) ) else: raise NotImplementedError("Only up to first derivatives are supported!")
def exp_gauss_warp(X, n, l0, *msb): """Length scale function which is an exponential of a sum of Gaussians. The centers and widths of the Gaussians are free parameters. The length scale function is given by .. math:: l = l_0 \exp\left ( \sum_{i=1}^{N}\beta_i\exp\left ( -\frac{(x-\mu_i)^2}{2\sigma_i^2} \right ) \right )...
(for :math:`l_0`). This function is inspired by what Gibbs used in his PhD thesis. Parameters ---------- X : 1d or 2d array of float The points to evaluate the function at. If 2d, it should only have one column (but this is not checked to save time). n : int The derivative order to compute. Used for all `X`. l0 : float...
length scale at the edges of the domain. *msb : floats Means, standard deviations and weights for each Gaussian, in that order. """ X = scipy.asarray(X, dtype=float) msb = scipy.asarray(msb, dtype=float) mm = msb[:len(msb) / 3] ss = msb[len(msb) / 3:2 * len(msb) / 3] bb = msb[2 * len(msb) / 3:] # This is done with for-...
# broadcasting was being too memory-intensive for some reason. if n == 0: l = scipy.zeros_like(X) for m, s, b in zip(mm, ss, bb): l += b * scipy.exp(-(X - m)**2.0 / (2.0 * s**2.0)) l = l0 * scipy.exp(l) return l elif n == 1: l1 = scipy.zeros_like(X) l2 = scipy.zeros_like(X) for m, s, b in zip(mm, ss, bb): term = b *
scipy.exp(-(X - m)**2.0 / (2.0 * s**2.0)) l1 += term l2 += term * (X - m) / s**2.0 l = -l0 * scipy.exp(l1) * l2 return l else: raise NotImplementedError("Only n <= 1 is supported!")
def get_multiple_choices_required(self): """ Add only the required message, but no 'ng-required' attribute to the input fields, otherwise all Checkboxes of a MultipleChoiceField would require the property "checked". """ errors = [] if self.required: for key, msg in self.error_messages.items(): if key == 'required': err...
def sso(user, desired_username, name, email, profile_fields=None): """ Create a user, if the provided `user` is None, from the parameters. Then log the user in, and return it. """ if not user: if not settings.REGISTRATION_OPEN: raise SSOError('Account registration is closed') user = _create_desired_user(desired_usernam...
user. # We are bypassing login, so fake it. user.backend = settings.AUTHENTICATION_BACKENDS[0] return user
def parallel_compute_ll_matrix(gp, bounds, num_pts, num_proc=None): """Compute matrix of the log likelihood over the parameter space in parallel. Parameters ---------- bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters Bounds on the range to use for each of the parameters. If a sing...
or list of ints with length equal to the number of free parameters The number of points to use for each parameters. If a single int is given, it will be used for each of the parameters. num_proc : Positive int or None, optional Number of processes to run the parallel computation with. If set to None, ALL available core...
None (use all available cores). Returns ------- ll_vals : array The log likelihood for each of the parameter possibilities. param_vals : list of array The parameter values used. """ if num_proc is None: num_proc = multiprocessing.cpu_count() present_free_params = gp.free_params bounds = scipy.atleast_2d(scipy.asarray(b...
for each free parameter: if bounds.shape[0] == 1: bounds = scipy.tile(bounds, (len(present_free_params), 1)) # If num_pts is a single value, use it for all of the parameters: try: iter(num_pts) except TypeError: num_pts = num_pts * scipy.ones(bounds.shape[0], dtype=int) else: num_pts = scipy.asarray(num_pts, dtype=int)...
parameters over: param_vals = [] for k in xrange(0, len(present_free_params)): param_vals.append(scipy.linspace(bounds[k, 0], bounds[k, 1], num_pts[k])) pv_cases = list() gp_cases = list() num_pts_cases = list() for k in xrange(0, len(param_vals[0])): specific_param_vals = list(param_vals) specific_param_vals[0] = para...
def slice_plot(*args, **kwargs): """Constructs a plot that lets you look at slices through a multidimensional array. Parameters ---------- vals : array, (`M`, `D`, `P`, ...) Multidimensional array to visualize. x_vals_1 : array, (`M`,) Values along the first dimension. x_vals_2 : array, (`D`,) Values along the second d...
be provided.** names : list of strings, optional Names for each of the parameters at hand. If None, sequential numerical identifiers will be used. Length must be equal to the number of dimensions of `vals`. Default is None. n : Positive int, optional Number of contours to plot. Default is 100. Returns ------- f : :py:c...
If the number of arguments is less than 4. """ names = kwargs.get('names', None) n = kwargs.get('n', 100) num_axes = len(args) - 1 if num_axes < 3: raise GPArgumentError("Must pass at least four arguments to slice_plot!") if num_axes != args[0].ndim: raise GPArgumentError("Number of dimensions of the first argument " "...
[str(k) for k in range(2, num_axes)] f = plt.figure() height_ratios = [8] height_ratios += (num_axes - 2) * [1] gs = mplgs.GridSpec(num_axes - 2 + 1, 2, height_ratios=height_ratios, width_ratios=[8, 1]) a_main = f.add_subplot(gs[0, 0]) a_cbar = f.add_subplot(gs[0, 1]) a_sliders = [] for idx in xrange(0, num_axes - 2): ...
[int(slider.val) for slider in sliders] vals = [args[k + 3][idxs[k]] for k in range(0, num_axes - 2)] descriptions = tuple(itertools.chain.from_iterable(itertools.izip(names[2:], vals))) fmt = "Slice" + (num_axes - 2) * ", %s: %f" title.set_text(fmt % descriptions) a_main.set_xlabel(names[1]) a_main.set_ylabel(names[0]...
= [] for idx in xrange(0, num_axes - 2): sliders.append( mplw.Slider( a_sliders[idx], '%s index' % names[idx + 2], 0, len(args[idx + 3]) - 1, valinit=idxs_0[idx], valfmt='%d' ) ) sliders[-1].on_changed(update) update(idxs_0) f.canvas.mpl_connect('key_press_event', lambda evt: arrow_respond(sliders[0], evt)) return f
def arrow_respond(slider, event): """Event handler for arrow key events in plot windows. Pass the slider object to update as a masked argument using a lambda function:: lambda evt: arrow_respond(my_slider, evt) Parameters ---------- slider : Slider instance associated with this handler. event : Event to be handled. """...
def debit(self, amount, credit_account, description, debit_memo="", credit_memo="", datetime=None): """ Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively. note amount must be non-negative. """ assert amount >= 0 return self.post(amount, credit_account, description, se...
def credit(self, amount, debit_account, description, debit_memo="", credit_memo="", datetime=None): """ Post a credit of 'amount' and a debit of -amount against this account and credit_account respectively. note amount must be non-negative. """ assert amount >= 0 return self.post(-amount, debit_account, description, se...
def post(self, amount, other_account, description, self_memo="", other_memo="", datetime=None): """ Post a transaction of 'amount' against this account and the negative amount against 'other_account'. This will show as a debit or credit against this account when amount > 0 or amount < 0 respectively. """ #Note: debits ...
= self._new_transaction() if datetime: tx.t_stamp = datetime #else now() tx.description = description tx.save() a1 = self._make_ae(self._DEBIT_IN_DB() * amount, self_memo, tx) a1.save() a2 = other_account._make_ae(-self._DEBIT_IN_DB() * amount, other_memo, tx) a2.save() return (a1, a2)
def balance(self, date=None): """ returns the account balance as of 'date' (datetime stamp) or now(). """ qs = self._entries() if date: qs = qs.filter(transaction__t_stamp__lt=date) r = qs.aggregate(b=Sum('amount')) b = r['b'] flip = self._DEBIT_IN_DB() if self._positive_credit(): flip *= -1 if b is None: b = Decimal("...
def totals(self, start=None, end=None): """Returns a Totals object containing the sum of all debits, credits and net change over the period of time from start to end. 'start' is inclusive, 'end' is exclusive """ qs = self._entries_range(start=start, end=end) qs_positive = qs.filter(amount__gt=Decimal("0.00")).all().agg...
qs_positive['amount__sum'] is not None else 0 negatives = -qs_negative['amount__sum'] if qs_negative['amount__sum'] is not None else 0 if self._DEBIT_IN_DB() > 0: debits = positives credits = negatives else: debits = negatives credits = positives net = debits-credits if self._positive_credit(): net = -net return self.T...
def ledger(self, start=None, end=None): """Returns a list of entries for this account. Ledger returns a sequence of LedgerEntry's matching the criteria in chronological order. The returned sequence can be boolean-tested (ie. test that nothing was returned). If 'start' is given, only entries on or after that datetime ar...
datetime are returned. 'end' must be given with a timezone. """ DEBIT_IN_DB = self._DEBIT_IN_DB() flip = 1 if self._positive_credit(): flip *= -1 qs = self._entries_range(start=start, end=end) qs = qs.order_by("transaction__t_stamp", "transaction__tid") balance = Decimal("0.00") if start: balance = self.balance(start) ...
amount = e.amount * DEBIT_IN_DB o_balance = balance balance += flip * amount yield LedgerEntry(amount, e, o_balance, balance) return helper(balance)
def get_third_party(self, third_party): """Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.""" actual_account = third_party.get_account() assert actual_account.get_bookset() == self return ThirdPartySubAccount(actual_account, third_party=third_party)
def get_third_party(self, third_party): """Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.""" actual_account = third_party.get_account() assert actual_account.get_bookset() == self.get_bookset() return ProjectAccount(actual_account, project=self, third_...
def find_overlapping_slots(all_slots): """Find any slots that overlap""" overlaps = set([]) for slot in all_slots: # Because slots are ordered, we can be more efficient than this # N^2 loop, but this is simple and, since the number of slots # should be low, this should be "fast enough" start = slot.get_start_time() end...
other_slot.get_day() != slot.get_day(): # different days, can't overlap continue # Overlap if the start_time or end_time is bounded by our times # start_time <= other.start_time < end_time # or # start_time < other.end_time <= end_time other_start = other_slot.get_start_time() other_end = other_slot.end_time if start <...
def find_non_contiguous(all_items): """Find any items that have slots that aren't contiguous""" non_contiguous = [] for item in all_items: if item.slots.count() < 2: # No point in checking continue last_slot = None for slot in item.slots.all().order_by('end_time'): if last_slot: if last_slot.end_time != slot.get_start_...
def validate_items(all_items): """Find errors in the schedule. Check for: - pending / rejected talks in the schedule - items with both talks and pages assigned - items with neither talks nor pages assigned """ validation = [] for item in all_items: if item.talk is not None and item.page is not None: validation.append(i...
item.talk.status not in [ACCEPTED, CANCELLED]: validation.append(item) return validation