code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
dt = DATA_TYPES['decimal'] if type(self.data) in dt['type']: self.type = 'DECIMAL' num_split = str(self.data).split('.', 1) self.len = len(num_split[0]) self.len_decimal = len(num_split[1]) return True
def is_decimal(self)
Determine if a data record is of the type float.
4.455879
4.077951
1.092676
dt = DATA_TYPES[data_type] if dt['min'] and dt['max']: if type(self.data) is dt['type'] and dt['min'] < self.data < dt['max']: self.type = data_type.upper() self.len = len(str(self.data)) return True
def _is_numeric_data(self, data_type)
Private method for testing text data types.
3.944931
3.501602
1.126607
def create_enrollment_term(self, account_id, enrollment_term_end_at=None, enrollment_term_name=None, enrollment_term_sis_term_id=None, enrollment_term_start_at=None): path = {} data = {} params = {} # REQUIRED - PATH - account_id path["account_id"] = ac...
Create enrollment term. Create a new enrollment term for the specified account.
null
null
null
def list_enrollment_terms(self, account_id, workflow_state=None): path = {} data = {} params = {} # REQUIRED - PATH - account_id path["account_id"] = account_id # OPTIONAL - workflow_state if workflow_state is not None: ...
List enrollment terms. Return all of the terms in the account.
null
null
null
if not isinstance(model_instance, DataCollection): raise TypeError("model_instance must be a subclass of \ prestans.types.DataCollection, %s given" % (model_instance.__class__.__name__)) elif isinstance(model_instance, Array) and model_instance.is_scalar: ...
def from_model(cls, model_instance, default_value=False, **kwargs)
wrapper for Model's get_attribute_filter
3.908157
3.637574
1.074385
blueprint = dict() for key in self.keys(): blueprint[key] = self.is_attribute_visible(key) return blueprint
def blueprint(self)
:return: blueprint :rtype: dict
6.885145
6.691658
1.028915
if not isinstance(template_filter, self.__class__): raise TypeError("AttributeFilter can only check conformance against \ another template filter, %s provided" % template_filter.__class__.__name__) # keys from the template template_filter_keys = template_fi...
def conforms_to_template_filter(self, template_filter)
Check AttributeFilter conforms to the rules set by the template - If self, has attributes that template_filter does not contain, throw Exception - If sub list found, perform the first check - If self has a value for an attribute, assign to final AttributeFilter - If not found, assig...
3.628766
3.434886
1.056444
keys = list() for attribute_name, type_instance in inspect.getmembers(self): # ignore parameters with __ and if they are methods if attribute_name.startswith('__') or inspect.ismethod(type_instance): continue keys.append(attribute_name) ...
def keys(self)
:returns: a list of usable keys :rtype: list
4.964607
4.519045
1.098597
if key in self: attribute_status = getattr(self, key) if isinstance(attribute_status, self.__class__): return True return False
def is_filter_at_key(self, key)
return True if attribute is a sub filter
5.972404
4.713373
1.267119
if key in self: attribute_status = getattr(self, key) if isinstance(attribute_status, bool) and attribute_status is True: return True elif isinstance(attribute_status, self.__class__) and attribute_status.are_any_attributes_visible(): ...
def is_attribute_visible(self, key)
Returns True if an attribute is visible If attribute is an instance of AttributeFilter, it returns True if all attributes of the sub filter are visible. :param key: name of attribute to check :type key: str :return: whether attribute is visible :rtype: bool
3.370484
3.467637
0.971983
for attribute_name, type_instance in inspect.getmembers(self): if attribute_name.startswith('__') or inspect.ismethod(type_instance): continue if isinstance(type_instance, bool) and type_instance is True: return True elif isinstance...
def are_any_attributes_visible(self)
checks to see if any attributes are set to true
3.02379
2.606056
1.160293
for attribute_name, type_instance in inspect.getmembers(self): if attribute_name.startswith('__') or inspect.ismethod(type_instance): # Ignore parameters with __ and if they are methods continue if isinstance(type_instance, bool): ...
def set_all_attribute_values(self, value)
sets all the attribute values to the value and propagate to any children
3.393339
3.294512
1.029997
output_dictionary = dict() for attribute_name, type_instance in inspect.getmembers(self): if attribute_name.startswith('__') or inspect.ismethod(type_instance): continue if isinstance(type_instance, bool): output_dictionary[attribute_n...
def as_dict(self)
turns attribute filter object into python dictionary
2.648347
2.377036
1.114139
if not isinstance(from_dictionary, dict): raise TypeError("from_dictionary must be of type dict, %s \ provided" % from_dictionary.__class__.__name__) rewrite_map = None if template_model is not None: if not isinstance(template_model, DataCollec...
def _init_from_dictionary(self, from_dictionary, template_model=None)
Private helper to init values from a dictionary, wraps children into AttributeFilter objects :param from_dictionary: dictionary to get attribute names and visibility from :type from_dictionary: dict :param template_model: :type template_model: DataCollection
3.730414
3.425804
1.088916
self._logger.info("Computing all predictions and their variance for %s logical networks...", len(self.networks)) return self.networks.predictions(self.setup.filter(self.networks))
def predict(self)
Computes all possible weighted average predictions and their variances Example:: >>> from caspo import core, predict >>> networks = core.LogicalNetworkList.from_csv('behaviors.csv') >>> setup = core.Setup.from_json('setup.json') >>> predictor = predict.Predict...
21.766293
11.851303
1.836616
traffic = self.get_child_static('traffic') return {o.obj_name(): o for o in traffic.get_objects_or_children_by_type('trafficItem')}
def get_traffic_items(self)
:return: dictionary {name: object} of all traffic items.
10.657713
7.422703
1.435826
raw_content = self._manager.api.session.get(self.download_link).content data = BytesIO(raw_content) archive = ZipFile(data) filename = archive.filelist[0] # Always 1 file in the archive return archive.read(filename)
def content(self)
Returns raw CSV content of the log file.
5.320996
4.779945
1.113192
if reg_lrn.match(read_tuple_name) is None: self.report_error( read_tuple_name=read_tuple_name, error_name="wrong_read_tuple_name_structure", message="'{}' is not matched".format(reg_lrn), ) else: parts = read_tu...
def validate(self, read_tuple_name)
Check RNF validity of a read tuple. Args: read_tuple_name (str): Read tuple name to be checked.s
2.081934
2.07587
1.002921
if (not self.report_only_first) or (error_name not in self.reported_errors): print("\t".join(["error" if warning == False else "warning", read_tuple_name, error_name, wrong, message])) self.reported_errors.add(error_name) if warning: self.warning_has_been_reporte...
def report_error(self, read_tuple_name, error_name, wrong="", message="", warning=False)
Report an error. Args: read_tuple_name (): Name of the read tuple. error_name (): Name of the error. wrong (str): What is wrong. message (str): Additional msessage to be printed. warning (bool): Warning (not an error).
2.794965
3.211311
0.87035
exemptions = self.exclude_paths if exemptions: path = environ.get('PATH_INFO') for excluded_p in self.exclude_paths: if path.startswith(excluded_p): return True return False
def _is_exempt(self, environ)
Returns True if this request's URL starts with one of the excluded paths.
3.882284
3.340462
1.1622
''' Loads metabolic network models in metabolitics. :param str model: model name ''' if type(model) == str: if model in ['ecoli', 'textbook', 'salmonella']: return cb.test.create_test_model(model) elif model == 'recon2': return cb.io.load_json_model('%s/netwo...
def load_network_model(model)
Loads metabolic network models in metabolitics. :param str model: model name
7.06299
4.813587
1.467303
max_age = timezone.now() - timedelta(seconds=app_settings.ESI_TOKEN_VALID_DURATION) return self.filter(created__lte=max_age)
def get_expired(self)
Get all tokens which have expired. :return: All expired tokens. :rtype: :class:`esi.managers.TokenQueryset`
5.520566
4.746924
1.162978
session = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID) auth = requests.auth.HTTPBasicAuth(app_settings.ESI_SSO_CLIENT_ID, app_settings.ESI_SSO_CLIENT_SECRET) incomplete = [] for model in self.filter(refresh_token__isnull=False): try: model.refresh(se...
def bulk_refresh(self)
Refreshes all refreshable tokens in the queryset. Deletes any tokens which fail to refresh. Deletes any tokens which are expired and cannot refresh. Excludes tokens for which the refresh was incomplete for other reasons.
3.506625
3.16122
1.109263
expired = self.get_expired() valid = self.exclude(pk__in=expired) valid_expired = expired.bulk_refresh() return valid_expired | valid
def require_valid(self)
Ensures all tokens are still valid. If expired, attempts to refresh. Deletes those which fail to refresh or cannot be refreshed. :return: All tokens which are still valid. :rtype: :class:`esi.managers.TokenQueryset`
10.193291
6.024807
1.691887
scopes = _process_scopes(scope_string) if not scopes: # asking for tokens with no scopes return self.filter(scopes__isnull=True) from .models import Scope scope_pks = Scope.objects.filter(name__in=scopes).values_list('pk', flat=True) if not len(sc...
def require_scopes(self, scope_string)
:param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with all requested scopes. :rtype: :class:`esi.managers.TokenQueryset`
3.343904
3.243677
1.030899
num_scopes = len(_process_scopes(scope_string)) pks = [v['pk'] for v in self.annotate(models.Count('scopes')).require_scopes(scope_string).filter( scopes__count=num_scopes).values('pk', 'scopes__id')] return self.filter(pk__in=pks)
def require_scopes_exact(self, scope_string)
:param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with only the requested scopes. :rtype: :class:`esi.managers.TokenQueryset`
6.081254
5.622656
1.081563
return self.filter(character_id=token.character_id).require_scopes_exact(token.scopes.all()).filter( models.Q(user=token.user) | models.Q(user__isnull=True)).exclude(pk=token.pk)
def equivalent_to(self, token)
Gets all tokens which match the character and scopes of a reference token :param token: :class:`esi.models.Token` :return: :class:`esi.managers.TokenQueryset`
7.36263
4.48708
1.640851
# perform code exchange logger.debug("Creating new token from code {0}".format(code[:-5])) oauth = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID, redirect_uri=app_settings.ESI_SSO_CALLBACK_URL) token = oauth.fetch_token(app_settings.ESI_TOKEN_URL, client_secret=app_settings.ESI_...
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`
2.988296
2.904476
1.028859
logger.debug("Creating new token for {0} session {1}".format(request.user, request.session.session_key[:5])) code = request.GET.get('code') # attach a user during creation for some functionality in a post_save created receiver I'm working on elsewhere model = self.create_from_co...
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`
9.488583
9.001093
1.054159
source = iter(iterable) while True: batch = itertools.islice(source, size) yield itertools.chain([next(batch)], batch)
def ibatch(iterable, size)
Yield a series of batches from iterable, each size elements long.
2.846663
2.389076
1.191533
self.put(key, value)
def put_many(self, items): # pragma: no cover for key, value in items
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 produci...
22.539782
12.498791
1.803357
items = self.items(key_from=prefix) start = 0 if strip_prefix: start = len(prefix) for key, value in items: if not key.startswith(prefix): break yield key[start:], value
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 store where ...
3.415756
3.917495
0.871924
keys = self.keys(key_from=prefix) start = 0 if strip_prefix: start = len(prefix) for key in keys: if not key.startswith(prefix): break yield key[start:]
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``.
3.441068
4.202932
0.81873
def details_for_given_date_in_gradebook_history_for_this_course(self, date, course_id): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - date path["date"] = dat...
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 the 'submissions' api endpoint for a given date.
null
null
null
def lists_submissions(self, date, course_id, grader_id, assignment_id): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - date path["date"] = date # R...
Lists submissions. Gives a nested list of submission versions
null
null
null
def list_uncollated_submission_versions(self, course_id, ascending=None, assignment_id=None, user_id=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # OPTIONAL - assignment_id ...
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 +previous_grade+ keys, only the +grade+; same for +graded_at+ and +grader+.
null
null
null
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(self, *args, **kwargs)
Saving ensures that the slug, if not set, is set to the slugified name.
5.287653
4.599762
1.149549
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_typ...
def _save_percolator(self)
saves the query field as an elasticsearch percolator
5.701508
4.709677
1.210594
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", }) re...
def get_content(self)
performs es search and gets content objects
6.291795
5.360054
1.173831
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( ...
def sample(name, reads_in_tuple)
Create a new sample.
8.929166
8.766002
1.018613
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 ImproperlyConfigured( "POSTGRES_SCHEMA_M...
def get_schema_model()
Returns the schema model that is active in this project.
1.822175
1.789294
1.018376
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_R...
def read(self, len=1024)
Read up to LEN bytes and return them. Return zero-length string on EOF.
2.489625
2.461923
1.011252
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_cl...
def write(self, data)
Write DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.
2.390507
2.224919
1.074424
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...
def do_handshake(self)
Perform a TLS/SSL handshake.
2.225827
2.187023
1.017743
# 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.connect(self, addr) if six.PY3: ...
def connect(self, addr)
Connects to remote ADDR, and then wraps the connection in an SSL channel.
2.884807
2.688133
1.073164
newsock, addr = socket.accept(self) ssl_sock = SSLSocket(newsock._sock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ...
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.
1.982817
1.727604
1.147727
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: ...
def send_request(self, url)
Send a request to given url.
4.648604
4.598407
1.010916
return self.send_request( "{0}://{1}:{2}{3}{4}".format( self.get_protocol(), self.host, self.port, uri, self.client_id ) )
def get(self, uri)
Send a request to given uri.
3.583817
3.385282
1.058646
# 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 get_client_id(self)
Attempt to get client_id from soundcloud homepage.
8.552705
6.49141
1.317542
@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(ex...
def error_handler(task)
Handle and log RPC errors.
2.847842
2.721406
1.04646
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 = ...
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 sender ...
3.53342
3.185582
1.109191
# "move" commands if destination_id: tx = db.Transaction( txtype="move", from_user_id=origin, to_user_id=destination_id, txdate=datetime.now(), amount=amount, currency=COINS[self.coin]["t...
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 is a "sendfrom" ...
2.907568
2.620743
1.109444
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"] self.rpc = pyjsonrpc.HttpClient( ...
def rpc_connect(self)
Connect to a coin daemon's JSON RPC interface. Returns: bool: True if successfully connected, False otherwise.
2.614815
2.538253
1.030163
address = self.rpc.call("getaccountaddress", user_id) self.logger.debug("Your", self.coin, "address is", address) return address
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
4.847638
6.122848
0.791729
balance = unicode(self.rpc.call("getbalance", user_id)) self.logger.debug("\"" + user_id + "\"", self.coin, "balance:", balance) if as_decimal: return Decimal(balance) else: return balance
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 ac...
4.297421
5.108969
0.841152
txlist = self.rpc.call("listtransactions", user_id, count, start_at) self.logger.debug("Got transaction list for " + str(user_id)) return txlist
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]: transactions as...
3.732757
5.12546
0.728277
amount = Decimal(amount).quantize(self.quantum, rounding=ROUND_HALF_EVEN) return self.rpc.call("move", fromaccount, toaccount, float(str(amount)), minconf )
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 Decimal): ...
4.654566
6.156758
0.756009
amount = Decimal(amount).quantize(self.quantum, rounding=ROUND_HALF_EVEN) txhash = self.rpc.call("sendfrom", user_id, dest_address, float(str(amount)), minconf ) self.logger.debug("Send %s %s from %s to %s" % (str(amount), self.coin, ...
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 using this ...
2.948134
3.249235
0.907332
signature = self.rpc.call("signmessage", address, message) self.logger.debug("Signature: %s" % signature) return signature
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 whic...
3.384532
5.186094
0.652617
verified = self.rpc.call("verifymessage", address, signature, message) self.logger.debug("Signature verified: %s" % str(verified)) return verified
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...
3.971388
5.260269
0.754978
return self.rpc.call(str(command), *args)
def call(self, command, *args)
Passes an arbitrary command to the coin daemon. Args: command (str): command to be sent to the coin daemon
7.300365
13.274454
0.549956
if created: for role in ContributorRole.objects.all(): FeatureTypeRate.objects.create(role=role, feature_type=instance, rate=0)
def update_feature_type_rates(sender, instance, created, *args, **kwargs)
Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate.
3.49729
2.837018
1.232735
if action != 'pre_add': return else: for author in model.objects.filter(pk__in=pk_set): update_content_contributions(instance, author)
def update_contributions(sender, instance, action, model, pk_set, **kwargs)
Creates a contribution for each author added to an article.
4.265341
3.619143
1.17855
def list_calendar_events(self, all_events=None, context_codes=None, end_date=None, excludes=None, start_date=None, type=None, undated=None): path = {} data = {} params = {} # OPTIONAL - type " if type is not None: self._validate_enum(type, [...
List calendar events. Retrieve the list of calendar events or assignments for the current user
null
null
null
def reserve_time_slot(self, id, cancel_existing=None, comments=None, participant_id=None): path = {} data = {} params = {} # REQUIRED - PATH - id path["id"] = id # OPTIONAL - participant_id if participant_id is not None: ...
Reserve a time slot. Reserves a particular time slot and return the new reservation
null
null
null
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...
Update a calendar event. Update and return a calendar event
null
null
null
def delete_calendar_event(self, id, cancel_reason=None): path = {} data = {} params = {} # REQUIRED - PATH - id path["id"] = id # OPTIONAL - cancel_reason if cancel_reason is not None: params["cancel_reason"] =...
Delete a calendar event. Delete an event from the calendar and return the deleted event
null
null
null
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): path = {} data = {} pa...
Set a course timetable. Creates and updates "timetable" events for a course. Can automaticaly generate a series of calendar events based on simple schedules (e.g. "Monday and Wednesday at 2:00pm" ) Existing timetable events for the course and course sections will...
null
null
null
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): path = {} data = {} params = {} # REQUIRED - PATH - course_id ...
Create or update events directly for a course timetable. Creates and updates "timetable" events for a course or course section. Similar to {api:CalendarEventsApiController#set_course_timetable setting a course timetable}, but instead of generating a list of events based on a timetable sched...
null
null
null
def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # if we're coming back from SSO for a new token, return it token = _check_callback(request) if token and new: token...
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.
2.973416
2.834737
1.048921
def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # if we're coming back from SSO for a new token, return it token = _check_callback(request) if token and new: logge...
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.
2.601716
2.551181
1.019809
''' 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 i...
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 fo...
6.593342
3.396911
1.940982
return self.ixnCommand('add', parent.obj_ref(), obj_type, get_args_pairs(attributes))
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.
18.890329
16.333315
1.156552
try: current_app.jinja_env.get_template(field.data) except TemplateNotFound: raise ValidationError(_("Template selected does not exist"))
def template_exists(form, field)
Form validation: check that selected template exists.
4.019081
3.255829
1.234426
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 same_page_choosen(form, field)
Check that we are not trying to assign list page itself as a child.
10.661795
4.034354
2.642751
cols = "" for c in columns: cols = cols + wrap(c) + ', ' return cols[:-2]
def cols_str(columns)
Concatenate list of columns into a string.
4.768126
3.914206
1.218159
return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols
def join_cols(cols)
Join list of columns into a string for a SQL query
4.632037
4.112239
1.126403
# Seperate model_label into parts. labels = resolve_labels(model_label) # Get model class for model_label string. model = get_model(labels['app'], labels['model']) # Dynamic Classes class OrderItemBase(models.Model): item = models.ForeignKey(model_label) timestamp ...
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.
3.050253
3.014395
1.011896
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 = rel_model.objects.all().order_by('-%s' \ ...
def create_order_objects(model, order_fields)
Create order items for objects already present in the database.
2.611806
2.587242
1.009494
if not getattr(settings, 'ORDERABLE_MODELS', None): return False labels = resolve_labels(cls) if labels['app_model'] in settings.ORDERABLE_MODELS: return settings.ORDERABLE_MODELS[labels['app_model']] return False
def is_orderable(cls)
Checks if the provided class is specified as an orderable in settings.ORDERABLE_MODELS. If it is return its settings.
3.90338
3.185419
1.22539
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_model'] = '%s.%s' % (labels['app'], labels['model']) return labels
def resolve_labels(model_label)
Seperate model_label into parts. Returns dictionary with app, model and app_model strings.
3.131243
2.624009
1.193305
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_names: to_order_dict[field_name] = list(model.objects.all().order_by(\ ...
def sanitize_order(model)
Sanitize order values so eliminate conflicts and gaps. XXX: Early start, very ugly, needs work.
2.13255
2.109739
1.010812
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.request.REQUEST: base = self.model.get_...
def get_serializer_class(self)
gets the class type of the serializer :return: `rest_framework.Serializer`
3.940357
4.191519
0.940079
from bulbs.content.tasks import index index.delay(obj.polymorphic_ctype_id, obj.pk) message = "Created" if created else "Saved" LogEntry.objects.log(self.request.user, obj, message) return super(ContentViewSet, self).post_save(obj, created=created)
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`
5.400946
5.283195
1.022288
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 field_name in ("tags", "types...
def list(self, request, *args, **kwargs)
Modified list view to driving listing from ES
2.509678
2.415478
1.038998
content = self.get_object() if "published" in get_request_data(request): if not get_request_data(request)["published"]: content.published = None else: publish_dt = parse_datetime(get_request_data(request)["published"]) if ...
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`
2.81122
2.637259
1.065963
content = self.get_object() content.indexed = False content.save() LogEntry.objects.log(request.user, content, "Trashed") return Response({"status": "Trashed"})
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.Response`
6.234154
6.242813
0.998613
content = self.get_object() return Response({"status": content.get_status()})
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...
5.868986
8.763947
0.669674
# Check if the contribution app is installed if Contribution not in get_models(): return Response([]) if request.method == "POST": serializer = ContributionSerializer(data=get_request_data(request), many=True) if not serializer.is_valid(): ...
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`
3.275447
3.288407
0.996059
data = { "content": self.get_object().id, "create_date": get_request_data(request)["create_date"], "expire_date": get_request_data(request)["expire_date"] } serializer = ObfuscatedUrlInfoSerializer(data=data) if not serializer.is_valid(): ...
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`
2.50868
2.144957
1.169571
# no date checking is done here to make it more obvious if there's an issue with the # number of records. Date filtering will be done on the frontend. infos = [ObfuscatedUrlInfoSerializer(info).data for info in ObfuscatedUrlInfo.objects.filter(content=self.get_object()...
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`
7.638314
6.842195
1.116354
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 get_queryset(self)
creates the base queryset object for the serializer :return: an instance of `django.db.models.QuerySet`
3.720073
4.492556
0.828053
data = get_request_data(request).copy() data["user"] = request.user.id serializer = self.get_serializer(data=data, files=request.FILES) if serializer.is_valid(): self.pre_save(serializer.object) self.object = serializer.save(force_insert=True) ...
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` :r...
1.79588
1.840468
0.975773
author_filter = getattr(settings, "BULBS_AUTHOR_FILTER", {"is_staff": True}) queryset = self.model.objects.filter(**author_filter).distinct() return queryset
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`
5.828441
5.40726
1.077892
data = UserSerializer().to_representation(request.user) # add superuser flag only if user is a superuser, putting it here so users can only # tell if they are themselves superusers if request.user.is_superuser: data['is_superuser'] = True # attempt to add a...
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`
4.609301
4.633154
0.994852
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 na...
def list(self, request)
Search the doctypes for this model.
4.148961
3.54094
1.171712
queryset = self.get_filtered_queryset(get_request_data(request)) # Switch between paginated or standard style responses page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginat...
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".
2.584374
2.505551
1.031459
return self.list(request, *args, **kwargs)
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?
4.953058
3.041295
1.628602
def query_by_course(self, course_id, end_time=None, start_time=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # OPTIONAL - start_time if start_time is not None: ...
Query by course. List course change events for a given course.
null
null
null
global time time += dt disc.inner_radius = disc.outer_radius = 2.5 + math.sin(time / 2.0) * 1.5
def vary_radius(dt)
Vary the disc radius over time
5.501607
4.70791
1.168588