code
stringlengths
1
18.2k
def create_from_code(self, code, user=None): """ Perform OAuth code exchange to retrieve a token. :param code: OAuth grant code. :param user: User who will own token. :return: :class:`esi.models.Token` """ # perform code exchange logger.debug("Creating new token from code {0}".format(code[:-5])) oauth = OAuth2Session(a...
' ').capitalize() scope = Scope.objects.create(name=s, help_text=help_text) model.scopes.add(scope) logger.debug("Added {0} scopes to new token.".format(model.scopes.all().count())) if not app_settings.ESI_ALWAYS_CREATE_TOKEN: # see if we already have a token for this character and scope combination # if so, we don't n...
def create_from_request(self, request): """ Generate a token from the OAuth callback request. Must contain 'code' in GET. :param request: OAuth callback request. :return: :class:`esi.models.Token` """ logger.debug("Creating new token for {0} session {1}".format(request.user, request.session.session_key[:5])) code = req...
def ibatch(iterable, size): """Yield a series of batches from iterable, each size elements long.""" source = iter(iterable) while True: batch = itertools.islice(source, size) yield itertools.chain([next(batch)], batch)
def put_many(self, items): # pragma: no cover """Put many key-value pairs. This method may take advantage of performance or atomicity features of the underlying store. It does not guarantee that all items will be set in the same transaction, only that transactions may be used for performance. :param items: An iterable ...
def prefix_items(self, prefix, strip_prefix=False): """Get all (key, value) pairs with keys that begin with ``prefix``. :param prefix: Lexical prefix for keys to search. :type prefix: bytes :param strip_prefix: True to strip the prefix from yielded items. :type strip_prefix: bool :yields: All (key, value) pairs in the ...
def prefix_keys(self, prefix, strip_prefix=False): """Get all keys that begin with ``prefix``. :param prefix: Lexical prefix for keys to search. :type prefix: bytes :param strip_prefix: True to strip the prefix from yielded items. :type strip_prefix: bool :yields: All keys in the store that begin with ``prefix``. """ k...
def details_for_given_date_in_gradebook_history_for_this_course(self, date, course_id): """ Details for a given date in gradebook history for this course. Returns the graders who worked on this day, along with the assignments they worked on. More details can be obtained by selecting a grader and assignment and calling ...
def lists_submissions(self, date, course_id, grader_id, assignment_id): """ Lists submissions. Gives a nested list of submission versions """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """The id of the contextual course for this API call""" path["course_id"] = course_id # REQUIRED - PATH - date """Th...
def list_uncollated_submission_versions(self, course_id, ascending=None, assignment_id=None, user_id=None): """ List uncollated submission versions. Gives a paginated, uncollated list of submission versions for all matching submissions in the context. This SubmissionVersion objects will not include the +new_grade+ or +...
absent, versions of submissions from any user in the course are included.""" if user_id is not None: params["user_id"] = user_id # OPTIONAL - ascending """Returns submission versions in ascending date order (oldest first). If absent, returns submission versions in descending date order (newest first).""" if ascending i...
def save(self, *args, **kwargs): """Saving ensures that the slug, if not set, is set to the slugified name.""" if not self.slug: self.slug = slugify(self.name) section = super(Section, self).save(*args, **kwargs) if self.query and self.query != {}: self._save_percolator() return section
def _save_percolator(self): """saves the query field as an elasticsearch percolator """ index = Content.search_objects.mapping.index query_filter = self.get_content().to_dict() q = {} if "query" in query_filter: q = {"query": query_filter.get("query", {})} else: return es.index( index=index, doc_type=".percolator", bod...
def get_content(self): """performs es search and gets content objects """ if "query" in self.query: q = self.query["query"] else: q = self.query search = custom_search_model(Content, q, field_map={ "feature-type": "feature_type.slug", "tag": "tags.slug", "content-type": "_type", }) return search
def sample(name, reads_in_tuple): """ Create a new sample. """ if name in [sample_x.get_name() for sample_x in __SAMPLES__]: rnftools.utils.error( "Multiple samples have the same name. Each sample must have a unique name.", program="RNFtools", subprogram="MIShmash", exception=ValueError, ) Sample( name=name, reads_in_t...
def get_schema_model(): """ Returns the schema model that is active in this project. """ try: return django_apps.get_model(settings.POSTGRES_SCHEMA_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("POSTGRES_SCHEMA_MODEL must be of the form 'app_label.model_name'") except LookupError: raise Impr...
def read(self, len=1024): """Read up to LEN bytes and return them. Return zero-length string on EOF.""" while True: try: return self._sslobj.read(len) except SSLError: ex = sys.exc_info()[1] if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: return b'' elif ex.args[0] == SSL_ERROR_WANT_READ: if self.timeout ...
def write(self, data): """Write DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.""" while True: try: return self._sslobj.write(data) except SSLError: ex = sys.exc_info()[1] if ex.args[0] == SSL_ERROR_WANT_READ: if self.timeout == 0.0: raise six.exc_clear() self._io.wait_read(tim...
def do_handshake(self): """Perform a TLS/SSL handshake.""" while True: try: return self._sslobj.do_handshake() except SSLError: ex = sys.exc_info()[1] if ex.args[0] == SSL_ERROR_WANT_READ: if self.timeout == 0.0: raise six.exc_clear() self._io.wait_read(timeout=self.timeout, timeout_exc=_SSLErrorHandshakeTimeout) elif ...
def connect(self, addr): """Connects to remote ADDR, and then wraps the connection in an SSL channel.""" # Here we assume that the socket is client-side, and not # connected at the time of the call. We connect it, then wrap it. if self._sslobj: raise ValueError("attempt to connect already-connected SSLSocket!") socket....
def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) ssl_sock = SSLSocket(newsock._sock, keyfile=self.keyfile, certfile=self.certfile, se...
def send_request(self, url): """ Send a request to given url. """ while True: try: return urllib.request.urlopen(url) except urllib.error.HTTPError as e: raise serror( "Request `%s` failed (%s:%s)." % (url, e.__class__.__name__, e.code)) except Exception as e: choice = input(serror( "Error occured: %s - Retry? [yN]" % ...
def get(self, uri): """ Send a request to given uri. """ return self.send_request( "{0}://{1}:{2}{3}{4}".format( self.get_protocol(), self.host, self.port, uri, self.client_id ) )
def get_client_id(self): """ Attempt to get client_id from soundcloud homepage. """ # FIXME: This method doesn't works id = re.search( "\"clientID\":\"([a-z0-9]*)\"", self.send_request(self.SC_HOME).read().decode("utf-8")) if not id: raise serror("Cannot retrieve client_id.") return id.group(1)
def error_handler(task): """Handle and log RPC errors.""" @wraps(task) def wrapper(self, *args, **kwargs): try: return task(self, *args, **kwargs) except Exception as e: self.connected = False if not self.testing: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] er...
def payment(self, origin, destination, amount): """Convenience method for sending Bitcoins. Send coins from origin to destination. Calls record_tx to log the transaction to database. Uses free, instant "move" transfers if addresses are both local (in the same wallet), and standard "sendfrom" transactions otherwise. The...
otherwise """ if type(amount) != Decimal: amount = Decimal(amount) if amount <= 0: raise Exception("Amount must be a positive number") # Check if the destination is within the same wallet; # if so, we can use the fast (and free) "move" command all_addresses = [] accounts = self.listaccounts() if origin in accounts: if ...
def record_tx(self, origin, destination, amount, outcome, destination_id=None): """Records a transaction in the database. Args: origin (str): user_id of the sender destination (str): coin address or user_id of the recipient amount (str, Decimal, number): amount to send outcome (str, bool): the transaction hash if this ...
def rpc_connect(self): """Connect to a coin daemon's JSON RPC interface. Returns: bool: True if successfully connected, False otherwise. """ if self.coin in COINS: rpc_url = COINS[self.coin]["rpc-url"] + ":" if self.testnet: rpc_url += COINS[self.coin]["rpc-port-testnet"] else: rpc_url += COINS[self.coin]["rpc-port"] s...
def getaccountaddress(self, user_id=""): """Get the coin address associated with a user id. If the specified user id does not yet have an address for this coin, then generate one. Args: user_id (str): this user's unique identifier Returns: str: Base58Check address for this account """ address = self.rpc.call("getaccoun...
def getbalance(self, user_id="", as_decimal=True): """Calculate the total balance in all addresses belonging to this user. Args: user_id (str): this user's unique identifier as_decimal (bool): balance is returned as a Decimal if True (default) or a string if False Returns: str or Decimal: this account's total coin bala...
def listtransactions(self, user_id="", count=10, start_at=0): """List all transactions associated with this account. Args: user_id (str): this user's unique identifier count (int): number of transactions to return (default=10) start_at (int): start the list at this transaction (default=0) Returns: list [dict]: transact...
def move(self, fromaccount, toaccount, amount, minconf=1): """Send coins between accounts in the same wallet. If the receiving account does not exist, it is automatically created (but not automatically assigned an address). Args: fromaccount (str): origin account toaccount (str): destination account amount (str or Deci...
def sendfrom(self, user_id, dest_address, amount, minconf=1): """ Send coins from user's account. Args: user_id (str): this user's unique identifier dest_address (str): address which is to receive coins amount (str or Decimal): amount to send (eight decimal points) minconf (int): ensure the account has a valid balance ...
def signmessage(self, address, message): """Sign a message with the private key of an address. Cryptographically signs a message using ECDSA. Since this requires an address's private key, the wallet must be unlocked first. Args: address (str): address used to sign the message message (str): plaintext message to which a...
def verifymessage(self, address, signature, message): """ Verifies that a message has been signed by an address. Args: address (str): address claiming to have signed the message signature (str): ECDSA signature message (str): plaintext message which was signed Returns: bool: True if the address signed the message, Fals...
def call(self, command, *args): """ Passes an arbitrary command to the coin daemon. Args: command (str): command to be sent to the coin daemon """ return self.rpc.call(str(command), *args)
def update_feature_type_rates(sender, instance, created, *args, **kwargs): """ Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate. """ if created: for role in ContributorRole.objects.all(): FeatureTypeRate.objects.create(role=role, feature_type=instance, rate=0)
def update_contributions(sender, instance, action, model, pk_set, **kwargs): """Creates a contribution for each author added to an article. """ if action != 'pre_add': return else: for author in model.objects.filter(pk__in=pk_set): update_content_contributions(instance, author)
def list_calendar_events(self, all_events=None, context_codes=None, end_date=None, excludes=None, start_date=None, type=None, undated=None): """ List calendar events. Retrieve the list of calendar events or assignments for the current user """ path = {} data = {} params = {} # OPTIONAL - type """Defaults to "event"""" ...
is not None: params["end_date"] = end_date # OPTIONAL - undated """Defaults to false (dated events only). If true, only return undated events and ignore start_date and end_date.""" if undated is not None: params["undated"] = undated # OPTIONAL - all_events """Defaults to false (uses start_date, end_date, and undated cr...
if context_codes is not None: params["context_codes"] = context_codes # OPTIONAL - excludes """Array of attributes to exclude. Possible values are "description", "child_events" and "assignment"""" if excludes is not None: params["excludes"] = excludes self.logger.debug("GET /api/v1/calendar_events with query params: {p...
def create_calendar_event(self, calendar_event_context_code, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_description=None, calendar_event_duplicate_append_iterator=None, calendar_event_duplicate_count...
calendar_event_end_at # OPTIONAL - calendar_event[location_name] """Location name of the event.""" if calendar_event_location_name is not None: data["calendar_event[location_name]"] = calendar_event_location_name # OPTIONAL - calendar_event[location_address] """Location address""" if calendar_event_location_address is ...
- calendar_event[child_event_data][X][context_code] """Context code(s) corresponding to the section-level start and end time(s).""" if calendar_event_child_event_data_X_context_code is not None: data["calendar_event[child_event_data][X][context_code]"] = calendar_event_child_event_data_X_context_code # OPTIONAL - calen...
calendar_event_duplicate_append_iterator is not None: data["calendar_event[duplicate][append_iterator]"] = calendar_event_duplicate_append_iterator self.logger.debug("POST /api/v1/calendar_events with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PO...
def reserve_time_slot(self, id, cancel_existing=None, comments=None, participant_id=None): """ Reserve a time slot. Reserves a particular time slot and return the new reservation """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - participant_id """User or group id for whom ...
{params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/calendar_events/{id}/reservations".format(**path), data=data, params=params, no_data=True)
def update_calendar_event(self, id, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_context_code=None, calendar_event_description=None, calendar_event_end_at=None, calendar_event_location_address=None, ca...
None: data["calendar_event[start_at]"] = calendar_event_start_at # OPTIONAL - calendar_event[end_at] """End date/time of the event.""" if calendar_event_end_at is not None: data["calendar_event[end_at]"] = calendar_event_end_at # OPTIONAL - calendar_event[location_name] """Location name of the event.""" if calendar_eve...
calendar_event[child_event_data][X][end_at] """Section-level end time(s) if this is a course event.""" if calendar_event_child_event_data_X_end_at is not None: data["calendar_event[child_event_data][X][end_at]"] = calendar_event_child_event_data_X_end_at # OPTIONAL - calendar_event[child_event_data][X][context_code] ""...
def delete_calendar_event(self, id, cancel_reason=None): """ Delete a calendar event. Delete an event from the calendar and return the deleted event """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - cancel_reason """Reason for deleting/canceling the event.""" if cancel_rea...
def set_course_timetable(self, course_id, timetables_course_section_id=None, timetables_course_section_id_end_time=None, timetables_course_section_id_location_name=None, timetables_course_section_id_start_time=None, timetables_course_section_id_weekdays=None): """ Set a course timetable. Creates and updates "timetable"...
comma-separated list of abbreviated weekdays (Mon-Monday, Tue-Tuesday, Wed-Wednesday, Thu-Thursday, Fri-Friday, Sat-Saturday, Sun-Sunday)""" if timetables_course_section_id_weekdays is not None: data["timetables[course_section_id][weekdays]"] = timetables_course_section_id_weekdays # OPTIONAL - timetables[course_sectio...
def create_or_update_events_directly_for_course_timetable(self, course_id, course_section_id=None, events=None, events_code=None, events_end_at=None, events_location_name=None, events_start_at=None): """ Create or update events directly for a course timetable. Creates and updates "timetable" events for a course or cour...
data["events"] = events # OPTIONAL - events[start_at] """Start time for the event""" if events_start_at is not None: data["events[start_at]"] = events_start_at # OPTIONAL - events[end_at] """End time for the event""" if events_end_at is not None: data["events[end_at]"] = events_end_at # OPTIONAL - events[location_name]...
def tokens_required(scopes='', new=False): """ Decorator for views to request an ESI Token. Accepts required scopes as a space-delimited string or list of strings of scope names. Can require a new token to be retrieved by SSO. Returns a QueryDict of Tokens. """ def decorator(view_func): @wraps(view_func, assigned=avail...
tokens.exists(): logger.debug("Retrieved {0} tokens for {1} session {2}".format(tokens.count(), request.user, request.session.session_key[:5])) return view_func(request, tokens, *args, **kwargs) # trigger creation of new token via sso logger.debug("No tokens identified for {0} session {1}. Redirecting to SSO.".format(r...
def token_required(scopes='', new=False): """ Decorator for views which supplies a single, user-selected token for the view to process. Same parameters as tokens_required. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # if we're coming ...
to this user and has required scopes if ((token.user and token.user == request.user) or not token.user) and Token.objects.filter( pk=token_pk).require_scopes(scopes).require_valid().exists(): logger.debug("Selected token fulfills requirements of view. Returning.") return view_func(request, token, *args, **kwargs) excep...
def find(self, ip): ''' Find the abuse contact for a IP address :param ip: IPv4 or IPv6 address to check :type ip: string :returns: emails associated with IP :rtype: list :returns: none if no contact could be found :rtype: None :raises: :py:class:`ValueError`: if ip is not properly formatted ''' ip = ipaddr.IPAddress(i...
def add(self, parent, obj_type, **attributes): """ IXN API add command @param parent: object parent - object will be created under this parent. @param object_type: object type. @param attributes: additional attributes. @return: IXN object reference. """ return self.ixnCommand('add', parent.obj_ref(), obj_type, get_args...
def template_exists(form, field): """Form validation: check that selected template exists.""" try: current_app.jinja_env.get_template(field.data) except TemplateNotFound: raise ValidationError(_("Template selected does not exist"))
def same_page_choosen(form, field): """Check that we are not trying to assign list page itself as a child.""" if form._obj is not None: if field.data.id == form._obj.list_id: raise ValidationError( _('You cannot assign list page itself as a child.'))
def cols_str(columns): """Concatenate list of columns into a string.""" cols = "" for c in columns: cols = cols + wrap(c) + ', ' return cols[:-2]
def join_cols(cols): """Join list of columns into a string for a SQL query""" return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols
def create_order_classes(model_label, order_field_names): """ Create order model and admin class. Add order model to order.models module and register admin class. Connect ordered_objects manager to related model. """ # Seperate model_label into parts. labels = resolve_labels(model_label) # Get model class for model_lab...
request, extra_context={ 'add_url': add_url, 'list_url': list_url, 'related_opts': model._meta, } ) # XXX: Sanitize order on list save. # if (request.method == "POST" and self.list_editable and \ # '_save' in request.POST): # sanitize_order(self.model) return result def item_link(self, obj): url = reverse('admin:%s_%s_...
import managers setattr(QuerySet, 'user_order_by', managers.user_order_by) # Return created model class. return order_model
def create_order_objects(model, order_fields): """ Create order items for objects already present in the database. """ for rel in model._meta.get_all_related_objects(): rel_model = rel.model if rel_model.__module__ == 'order.models': objs = model.objects.all() values = {} for order_field in order_fields: order_objs = r...
def is_orderable(cls): """ Checks if the provided class is specified as an orderable in settings.ORDERABLE_MODELS. If it is return its settings. """ if not getattr(settings, 'ORDERABLE_MODELS', None): return False labels = resolve_labels(cls) if labels['app_model'] in settings.ORDERABLE_MODELS: return settings.ORDERABL...
def resolve_labels(model_label): """ Seperate model_label into parts. Returns dictionary with app, model and app_model strings. """ labels = {} # Resolve app label. labels['app'] = model_label.split('.')[0] # Resolve model label labels['model'] = model_label.split('.')[-1] # Resolve module_app_model label. labels['app_...
def sanitize_order(model): """ Sanitize order values so eliminate conflicts and gaps. XXX: Early start, very ugly, needs work. """ to_order_dict = {} order_field_names = [] for field in model._meta.fields: if isinstance(field, models.IntegerField): order_field_names.append(field.name) for field_name in order_field_name...
def get_serializer_class(self): """gets the class type of the serializer :return: `rest_framework.Serializer` """ klass = None lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field if lookup_url_kwarg in self.kwargs: # Looks like this is a detail... klass = self.get_object().__class__ elif "doctype" in self.req...
def post_save(self, obj, created=False): """indexes the object to ElasticSearch after any save function (POST/PUT) :param obj: instance of the saved object :param created: boolean expressing if object is newly created (`False` if updated) :return: `rest_framework.viewset.ModelViewSet.post_save` """ from bulbs.content.t...
def list(self, request, *args, **kwargs): """Modified list view to driving listing from ES""" search_kwargs = {"published": False} for field_name in ("before", "after", "status", "published"): if field_name in get_query_params(self.request): search_kwargs[field_name] = get_query_params(self.request).get(field_name) for...
def publish(self, request, **kwargs): """sets the `published` value of the `Content` :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ content = self.get_object() if "published" in get_request_data(request): if not get_request_data(request)...
def trash(self, request, **kwargs): """Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index Content is not actually deleted, merely hidden by deleted from ES index.import :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Respon...
def status(self, request, **kwargs): """This endpoint returns a status text, currently one of: - "Draft" (If no publish date is set, and no item exists in the editor queue) - "Waiting for Editor" (If no publish date is set, and an item exists in the editor queue) - "Published" (The published date is in the past) - "Sch...
def contributions(self, request, **kwargs): """gets or adds contributions :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ # Check if the contribution app is installed if Contribution not in get_models(): return Response([]) if request.met...
def create_token(self, request, **kwargs): """Create a new obfuscated url info to use for accessing unpublished content. :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ data = { "content": self.get_object().id, "create_date": get_request_...
def list_tokens(self, request, **kwargs): """List all tokens for this content instance. :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ # no date checking is done here to make it more obvious if there's an issue with the # number of recor...
def get_queryset(self): """creates the base queryset object for the serializer :return: an instance of `django.db.models.QuerySet` """ qs = LogEntry.objects.all() content_id = get_query_params(self.request).get("content", None) if content_id: qs = qs.filter(object_id=content_id) return qs
def create(self, request, *args, **kwargs): """ Grabbing the user from request.user, and the rest of the method is the same as ModelViewSet.create(). :param request: a WSGI request object :param args: inline arguments (optional) :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` :ra...
def get_queryset(self): """created the base queryset object for the serializer limited to users within the authors groups and having `is_staff` :return: `django.db.models.QuerySet` """ author_filter = getattr(settings, "BULBS_AUTHOR_FILTER", {"is_staff": True}) queryset = self.model.objects.filter(**author_filter).dist...
def retrieve(self, request, *args, **kwargs): """gets basic information about the user :param request: a WSGI request object :param args: inline arguments (optional) :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ data = UserSerializer().to_representation(request.user) # add ...
def list(self, request): """Search the doctypes for this model.""" query = get_query_params(request).get("search", "") results = [] base = self.model.get_base_class() doctypes = indexable_registry.families[base] for doctype, klass in doctypes.items(): name = klass._meta.verbose_name.title() if query.lower() in name.low...
def list(self, request, *args, **kwargs): """Filter Content with a custom search. { "query": SEARCH_QUERY "preview": true } "preview" is optional and, when true, will include items that would normally be removed due to "excluded_ids". """ queryset = self.get_filtered_queryset(get_request_data(request)) # Switch between...
def create(self, request, *args, **kwargs): """HACK: couldn't get POST to the list endpoint without messing up POST for the other list_routes so I'm doing this. Maybe something to do with the router? """ return self.list(request, *args, **kwargs)
def query_by_course(self, course_id, end_time=None, start_time=None): """ Query by course. List course change events for a given course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - start_time """The beginning of the time range from which you want...
def vary_radius(dt): """Vary the disc radius over time""" global time time += dt disc.inner_radius = disc.outer_radius = 2.5 + math.sin(time / 2.0) * 1.5
def _aggregate(self): ''' The function aggreagtes all pre_stream, layout and post_stream and components, and yields them one by one. ''' # Yielding everything under pre_stream for x in self._yield_all(self.pre_stream): yield x # Yielding layout for x in self._yield_all(self.layout): yield x # Yield LayoutSR Specific Co...
childList: true } observerFlaskSR.observe(target, config); document.addEventListener("DOMContentLoaded", function(event) { observerFlaskSR.disconnect(); }); } else { console.log("MutationObserver not found!"); } </script>""" % ( self.stream_div_id, self.stream_div_id, self.stream_div_layout_id ) # Yielding components f...
def from_str(duration): """Parse a duration string to a datetime.timedelta""" if duration in ("0", "+0", "-0"): return datetime.timedelta() pattern = re.compile('([\d\.]+)([a-zµμ]+)') total = 0 sign = -1 if duration[0] == '-' else 1 matches = pattern.findall(duration) if not len(matches): raise Exception("Invalid durat...
def to_str(delta, extended=False): """Format a datetime.timedelta to a duration string""" total_seconds = delta.total_seconds() sign = "-" if total_seconds < 0 else "" nanoseconds = abs(total_seconds * _second_size) if total_seconds < 1: result_str = _to_str_small(nanoseconds, extended) else: result_str = _to_str_large...
def rename(self, old_table, new_table): """ Rename a table. You must have ALTER and DROP privileges for the original table, and CREATE and INSERT privileges for the new table. """ try: command = 'RENAME TABLE {0} TO {1}'.format(wrap(old_table), wrap(new_table)) except: command = 'ALTER TABLE {0} RENAME {1}'.format(wrap...
def create_database(self, name): """Create a new database.""" statement = "CREATE DATABASE {0} DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci".format(wrap(name)) return self.execute(statement)
def create_table(self, name, data, columns=None, add_pk=True): """Generate and execute a create table query by parsing a 2D dataset""" # TODO: Issue occurs when bool values exist in data # Remove if the table exists if name in self.tables: self.drop(name) # Set headers list if not columns: columns = data[0] # Validate ...
def _get_notification(self, email, token): ''' Consulta o status do pagamento ''' url = u'{notification_url}{notification_code}?email={email}&token={token}'.format( notification_url=self.notification_url, notification_code=self.notification_code, email=email, token=token) req = requests.get(url) if req.status_code == 2...
def items(self): ''' Lista dos items do pagamento ''' if type(self.transaction['items']['item']) == list: return self.transaction['items']['item'] else: return [self.transaction['items']['item'],]