code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
cmd = [self.exe, '-R', self.location] + list(params) with reentry.in_process_context(cmd) as result: sys.modules['mercurial.dispatch'].run() stdout = result.stdio.stdout.getvalue() stderr = result.stdio.stderr.getvalue() if not result.returncode == 0: raise RuntimeError(stderr.strip() or stdout.strip...
def _invoke(self, *params)
Run the self.exe command in-process with the supplied params.
4.80875
4.460618
1.078046
if isRabaObject(obj) : _unregisterRabaObjectInstance(obj) elif isRabaList(obj) : _unregisterRabaListInstance(obj)
def removeFromRegistery(obj)
Removes an object/rabalist from registery. This is useful if you want to allow the garbage collector to free the memory taken by the objects you've already loaded. Be careful might cause some discrepenties in your scripts. For objects, cascades to free the registeries of related rabalists also
5.618657
4.554688
1.233599
"returns a dict describing the object" return {'type' : RabaFields.RABA_FIELD_TYPE_IS_RABA_OBJECT, 'className' : self._rabaClass.__name__, 'raba_id' : self.raba_id, 'raba_namespace' : self._raba_namespace}
def getDctDescription(self)
returns a dict describing the object
7.397159
6.702927
1.103571
"explicit deletes the object from the singleton reference dictionary. This is mandatory to be able to delete the object using del(). Also, any attempt to reload an object with the same parameters will result un a new instance being created" try : del(self.__class__._instances[makeRabaObjectSingletonKey(self.__cl...
def unreference(self)
explicit deletes the object from the singleton reference dictionary. This is mandatory to be able to delete the object using del(). Also, any attempt to reload an object with the same parameters will result un a new instance being created
18.157227
4.31514
4.207796
con = RabaConnection(cls._raba_namespace) rlf, ff = cls._parseIndex(fields) ww = [] for i in range(len(whereValues)) : if isRabaObject(whereValues[i]) : ww.append(whereValues[i].getJsonEncoding()) for name in rlf : con.createIndex(name, 'anchor_raba_id') if len(ff) > 0 : con.createIndex(...
def ensureIndex(cls, fields, where = '', whereValues = [])
Add an index for field, indexes take place and slow down saves and deletes but they speed up a lot everything else. If you are going to do a lot of saves/deletes drop the indexes first re-add them afterwards Fields can be a list of fields for Multi-Column Indices or simply the name of a single field. But as RabaList ...
6.138738
5.255717
1.168012
"removes an index created with ensureIndex " con = RabaConnection(cls._raba_namespace) rlf, ff = cls._parseIndex(fields) for name in rlf : con.dropIndex(name, 'anchor_raba_id') con.dropIndex(cls.__name__, ff) con.commit()
def dropIndex(cls, fields)
removes an index created with ensureIndex
12.648459
10.384381
1.218027
"returns a list of the indexes of a class" con = RabaConnection(cls._raba_namespace) idxs = [] for idx in con.getIndexes(rabaOnly = True) : if idx[2] == cls.__name__ : idxs.append(idx) else : for k in cls.columns : if RabaFields.isRabaListField(getattr(cls, k)) and idx[2] == con.makeRabaListT...
def getIndexes(cls)
returns a list of the indexes of a class
5.375752
5.13789
1.046296
"drops all indexes for a class" con = RabaConnection(cls._raba_namespace) for idx in cls.getIndexes() : con.dropIndexByName(idx[1])
def flushIndexes(cls)
drops all indexes for a class
12.872019
9.316124
1.381693
"set multiple values quickly, ex : name = woopy" for k, v in args.items() : setattr(self, k, v)
def set(self, **args)
set multiple values quickly, ex : name = woopy
15.047426
3.394454
4.432945
s = set(cls.columns.keys()) s.remove('json') s.remove('raba_id') return s
def getFields(cls)
returns a set of the available fields. In order to be able ti securely loop of the fields, "raba_id" and "json" are not included in the set
7.871815
2.83855
2.773181
"dummy fct for compatibility reasons, a RabaListPupa is attached by default" #MutableSequence.__getattribute__(self, "develop")() self.develop() self._attachToObject(anchorObj, relationName)
def _attachToObject(self, anchorObj, relationName)
dummy fct for compatibility reasons, a RabaListPupa is attached by default
26.997097
4.780154
5.647746
for i in range(len(self)) : self[i] = self[i].pupa()
def pupatizeElements(self)
Transform all raba object into pupas
4.713833
3.378901
1.395079
if self.connection.registerSave(self) : if len(self) == 0 : self.connection.updateRabaListLength(self.raba_id, len(self)) return True else : if self.relationName == None or self.anchorObj == None : raise ValueError('%s has not been attached to any object, impossible to save it' % s) #i...
def _save(self)
saves the RabaList into it's own table. This a private function that should be called directly Before saving the entire list corresponding to the anchorObj is wiped out before being rewritten. The alternative would be to keep the sync between the list and the table in real time (remove in both). If the current so...
3.138455
2.836813
1.106331
"Attaches the rabalist to a raba object. Only attached rabalists can be saved" if self.anchorObj == None : self.relationName = relationName self.anchorObj = anchorObj self._setNamespaceConAndConf(anchorObj._rabaClass._raba_namespace) self.tableName = self.connection.makeRabaListTableName(self.anchorObj...
def _attachToObject(self, anchorObj, relationName)
Attaches the rabalist to a raba object. Only attached rabalists can be saved
8.431629
5.972637
1.41171
def list_files_courses(self, course_id, content_types=None, include=None, only=None, order=None, search_term=None, sort=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # OPTIONAL - content_ty...
List files. Returns the paginated list of files for the folder or course.
null
null
null
def get_public_inline_preview_url(self, id, submission_id=None): path = {} data = {} params = {} # REQUIRED - PATH - id path["id"] = id # OPTIONAL - submission_id if submission_id is not None: params["submissio...
Get public inline preview url. Determine the URL that should be used for inline preview of the file.
null
null
null
def get_file_courses(self, id, course_id, include=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - id path["id"] = id # OPTIONAL - include ...
Get file. Returns the standard attachment json object
null
null
null
def update_file(self, id, hidden=None, lock_at=None, locked=None, name=None, on_duplicate=None, parent_folder_id=None, unlock_at=None): path = {} data = {} params = {} # REQUIRED - PATH - id path["id"] = id # OPTIONAL - name ...
Update file. Update some settings on the specified file
null
null
null
def delete_file(self, id): path = {} data = {} params = {} # REQUIRED - PATH - id path["id"] = id self.logger.debug("DELETE /api/v1/files/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) ...
Delete file. Remove the specified file curl -XDELETE 'https://<canvas>/api/v1/files/<file_id>' \ -H 'Authorization: Bearer <token>'
null
null
null
def get_folder_groups(self, id, group_id): path = {} data = {} params = {} # REQUIRED - PATH - group_id path["group_id"] = group_id # REQUIRED - PATH - id path["id"] = id self.logger.debug("GET /api/v1/groups/{gr...
Get folder. Returns the details for a folder You can get the root folder from a context by using 'root' as the :id. For example, you could get the root folder for a course like:
null
null
null
def update_folder(self, id, hidden=None, lock_at=None, locked=None, name=None, parent_folder_id=None, position=None, unlock_at=None): path = {} data = {} params = {} # REQUIRED - PATH - id path["id"] = id # OPTIONAL - name ...
Update folder. Updates a folder
null
null
null
def create_folder_courses(self, name, course_id, hidden=None, lock_at=None, locked=None, parent_folder_id=None, parent_folder_path=None, position=None, unlock_at=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = co...
Create folder. Creates a folder in the specified context
null
null
null
def delete_folder(self, id, force=None): path = {} data = {} params = {} # REQUIRED - PATH - id path["id"] = id # OPTIONAL - force if force is not None: params["force"] = force self.logger.debug("DEL...
Delete folder. Remove the specified folder. You can only delete empty folders unless you set the 'force' flag
null
null
null
def copy_file(self, dest_folder_id, source_file_id, on_duplicate=None): path = {} data = {} params = {} # REQUIRED - PATH - dest_folder_id path["dest_folder_id"] = dest_folder_id # REQUIRED - source_file_id data["source_fil...
Copy a file. Copy a file from elsewhere in Canvas into a folder. Copying a file across contexts (between courses and users) is permitted, but the source and destination must belong to the same institution.
null
null
null
def copy_folder(self, dest_folder_id, source_folder_id): path = {} data = {} params = {} # REQUIRED - PATH - dest_folder_id path["dest_folder_id"] = dest_folder_id # REQUIRED - source_folder_id data["source_folder_id"] = so...
Copy a folder. Copy a folder (and its contents) from elsewhere in Canvas into a folder. Copying a folder across contexts (between courses and users) is permitted, but the source and destination must belong to the same institution. If the source and destination folders are...
null
null
null
def set_usage_rights_courses(self, file_ids, course_id, usage_rights_use_justification, folder_ids=None, publish=None, usage_rights_legal_copyright=None, usage_rights_license=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["cou...
Set usage rights. Sets copyright and license information for one or more files
null
null
null
def remove_usage_rights_courses(self, file_ids, course_id, folder_ids=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - file_ids params["file_ids"] = file_ids ...
Remove usage rights. Removes copyright and license information associated with one or more files
null
null
null
def remove_usage_rights_groups(self, group_id, file_ids, folder_ids=None): path = {} data = {} params = {} # REQUIRED - PATH - group_id path["group_id"] = group_id # REQUIRED - file_ids params["file_ids"] = file_ids ...
Remove usage rights. Removes copyright and license information associated with one or more files
null
null
null
def remove_usage_rights_users(self, user_id, file_ids, folder_ids=None): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # REQUIRED - file_ids params["file_ids"] = file_ids #...
Remove usage rights. Removes copyright and license information associated with one or more files
null
null
null
now = today() if not isinstance(now, datetime) and isinstance(now, date): now = datetime.combine(now, datetime.min.time()) now = now.replace(tzinfo=tz.gettz('UTC')) return now
def today_as_utc_datetime()
Datetime/Date comparisons aren't great, and someone might configure TODAY, to be a date.
2.804524
2.382217
1.177275
module, _, klass = name.rpartition('.') mod = import_module(module) return getattr(mod, klass)
def import_class(name)
Load class from fully-qualified python module name. ex: import_class('bulbs.content.models.Content')
3.094971
3.603672
0.858838
def by_priority_attr(c): return getattr(c, 'priority', 0) classes = sorted( iter_subclasses(cls), key=by_priority_attr, reverse=True) all_managers = (c(location) for c in classes) return (mgr for mgr in all_managers if mgr.is_valid())
def get_valid_managers(cls, location)
Get the valid RepoManagers for this location.
3.783981
3.49547
1.082539
try: parent_rev = one(self.get_parent_revs(rev)) except Exception: return None return self.get_tags(parent_rev)
def get_parent_tags(self, rev=None)
Return the tags for the parent revision (or None if no single parent can be identified).
3.623244
3.384954
1.070397
files = self.find_files() subrepo_files = ( posixpath.join(subrepo.location, filename) for subrepo in self.subrepos() for filename in subrepo.find_files() ) return itertools.chain(files, subrepo_files)
def find_all_files(self)
Find files including those in subrepositories.
3.183663
2.597315
1.225752
'''Get the output of a command. Gets a nice Unicode no-extra-whitespace string of the ``stdout`` of a given command. Args: command (str or list): A string of the command, or a list of the arguments (as would be used in :class:`subprocess.Popen`). Note: If ``command`` is a ``str``, it will be evaluated with...
def get_cmd_out(command)
Get the output of a command. Gets a nice Unicode no-extra-whitespace string of the ``stdout`` of a given command. Args: command (str or list): A string of the command, or a list of the arguments (as would be used in :class:`subprocess.Popen`). Note: If ``command`` is a ``str``, it will be evaluated with ``s...
4.650553
1.476822
3.149029
''' Check if a program is in the system ``PATH``. Checks if a given program is in the user's ``PATH`` or not. Args: program (str): The program to try to find in ``PATH``. Returns: bool: Is the program in ``PATH``? ''' if sys.version_info.major == 2: path = os.getenv('PATH') if os.name == 'nt': p...
def is_in_path(program)
Check if a program is in the system ``PATH``. Checks if a given program is in the user's ``PATH`` or not. Args: program (str): The program to try to find in ``PATH``. Returns: bool: Is the program in ``PATH``?
2.606517
1.716801
1.518241
''' Check if process is running. Check if the given process name is running or not. Note: On a Linux system, kernel threads (like ``kthreadd`` etc.) are excluded. Args: process (str): The name of the process. Returns: bool: Is the process running? ''' if os.name == 'nt': process_list = get_cm...
def is_running(process)
Check if process is running. Check if the given process name is running or not. Note: On a Linux system, kernel threads (like ``kthreadd`` etc.) are excluded. Args: process (str): The name of the process. Returns: bool: Is the process running?
5.45575
3.570433
1.528036
if isinstance(value, (string_types, text_type, binary_type)): value = dateutil.parser.parse(value) value.replace(tzinfo=dateutil.tz.tzutc()) return value elif isinstance(value, datetime.datetime): value.replace(tzinfo=dateutil.tz.tzutc()) return value elif isins...
def parse_datetime(value)
Returns a datetime object for a given argument This helps to convert strings, dates and datetimes to proper tz-enabled datetime objects.
2.090856
2.024933
1.032556
def NegateQueryFilter(es_query): # noqa query = es_query.to_dict().get("query", {}) filtered = query.get("filtered", {}) negated_filter = filtered.get("filter", {}) return Not(**negated_filter)
Return a filter removing the contents of the provided query.
null
null
null
for deserializer in self._deserializers: if deserializer.content_type() == mime_type: self._selected_deserializer = deserializer return raise exception.UnsupportedContentTypeError(mime_type, self.supported_mime_types_str)
def set_deserializer_by_mime_type(self, mime_type)
:param mime_type: :return: Used by content_type_set to set get a reference to the serializer object
3.677669
3.331297
1.103975
if self.method == VERB.GET: raise AssertionError("body_template cannot be set for GET requests") if value is None: self.logger.warning("body_template is None, parsing will be ignored") return if not isinstance(value, DataCollection): ms...
def body_template(self, value)
Must be an instance of a prestans.types.DataCollection subclass; this is generally set during the RequestHandler lifecycle. Setting this spwans the parsing process of the body. If the HTTP verb is GET an AssertionError is thrown. Use with extreme caution.
5.04429
3.88614
1.298021
if template_filter is None: return None if 'Prestans-Response-Attribute-List' not in self.headers: return None # header not set results in a None attribute_list_str = self.headers['Prestans-Response-Attribute-List'] # deserialize the header co...
def get_response_attribute_filter(self, template_filter, template_model=None)
Prestans-Response-Attribute-List can contain a client's requested definition for attributes required in the response. This should match the response_attribute_filter_template? :param template_filter: :param template_model: the expected model that this filter corresponds to :retu...
6.882271
5.484994
1.254745
return self.ixn.add(parent.obj_ref(), obj_type, *self._get_args_list(**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.
9.704867
7.817152
1.241484
lines = iter(self._invoke('version').splitlines()) version = next(lines).strip() return self._parse_version(version)
def version(self)
Return the underlying version
5.758509
5.576066
1.032719
all_files = self._invoke('locate', '-I', '.').splitlines() # now we have a list of all files in self.location relative to # self.find_root() # Remove the parent dirs from them. from_root = os.path.relpath(self.location, self.find_root()) loc_rel_paths = [ os.path.relpath(path, from_root) for path ...
def find_files(self)
Find versioned files in self.location
4.846031
4.374495
1.107792
rev_num = self._get_rev_num(rev) # rev_num might end with '+', indicating local modifications. return ( set(self._read_tags_for_rev(rev_num)) if not rev_num.endswith('+') else set([]) )
def get_tags(self, rev=None)
Get the tags for the given revision specifier (or the current revision if not specified).
5.874584
6.65531
0.882691
cmd = [ 'log', '--style', 'default', '--config', 'defaults.log=', '-r', spec] res = self._invoke(*cmd) header_pattern = re.compile(r'(?P<header>\w+?):\s+(?P<value>.*)') match_res = map(header_pattern.match, res.splitlines()) matched_lines = filter(None, match_res) matches = (match.groupdict() for m...
def _read_tags_for_revset(self, spec)
Return TaggedRevision for each tag/rev combination in the revset spec
4.028458
3.585645
1.123496
# first, determine the numeric ID cmd = ['identify', '--num'] # workaround for #4 cmd.extend(['--config', 'defaults.identify=']) if rev: cmd.extend(['--rev', rev]) res = self._invoke(*cmd) return res.strip()
def _get_rev_num(self, rev=None)
Determine the revision number for a given revision specifier.
9.157174
8.806974
1.039764
by_revision = operator.attrgetter('revision') tags = sorted(self.get_tags(), key=by_revision) revision_tags = itertools.groupby(tags, key=by_revision) def get_id(rev): return rev.split(':', 1)[0] return dict( (get_id(rev), [tr.tag for tr in tr_list]) for rev, tr_list in revision_tags )
def _get_tags_by_num(self)
Return a dictionary mapping revision number to tags for that number.
3.488218
3.178393
1.097479
rev = rev or 'HEAD' return set(self._invoke('tag', '--points-at', rev).splitlines())
def get_tags(self, rev=None)
Return the tags for the current revision as a set
5.73312
5.177834
1.107243
if value not in dict(current_app.config['PAGES_TEMPLATES']): raise ValueError( 'Template "{0}" does not exist.'.format(value)) return value
def validate_template_name(self, key, value)
Validate template name. :param key: The template path. :param value: The template name. :raises ValueError: If template name is wrong.
5.161817
5.696422
0.906151
start = timeit.default_timer() networks = self.networks n = len(networks) cpu = n_jobs if n_jobs > -1 else mp.cpu_count() if cpu > 1: lpart = int(np.ceil(n / float(cpu))) if n > cpu else 1 parts = networks.split(np.arange(lpart, n, lpart)) ...
def classify(self, n_jobs=-1, configure=None)
Returns input-output behaviors for the list of logical networks in the attribute :attr:`networks` Example:: >>> from caspo import core, classify >>> networks = core.LogicalNetworkList.from_csv('networks.csv') >>> setup = core.Setup.from_json('setup.json') >>> ...
4.969478
4.060643
1.223816
def add_observee_with_credentials(self, user_id, access_token=None, observee_password=None, observee_unique_id=None): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # OPTIONAL - observee[unique_id] ...
Add an observee with credentials. Register the given user to observe another user, given the observee's credentials. *Note:* all users are allowed to add their own observees, given the observee's credentials or access token are provided. Administrators can add observees given cred...
null
null
null
def show_observee(self, user_id, observee_id): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # REQUIRED - PATH - observee_id path["observee_id"] = observee_id self.logger.d...
Show an observee. Gets information about an observed user. *Note:* all users are allowed to view their own observees.
null
null
null
'''Adds a program to startup. Adds a program to user startup. Args: name (str) : The name of the startup entry. command (str) : The command to run. system_wide (bool): Add to system-wide startup. Note: ``system_wide`` requires superuser/admin privileges. ''' desktop_env = system.get_name(...
def add_item(name, command, system_wide=False)
Adds a program to startup. Adds a program to user startup. Args: name (str) : The name of the startup entry. command (str) : The command to run. system_wide (bool): Add to system-wide startup. Note: ``system_wide`` requires superuser/admin privileges.
3.608112
3.119787
1.156525
'''Removes a program from startup. Removes a program from startup. Args: name (str) : The name of the program (as known to the system) to remove. See :func:``list_items``. system_wide (bool): Remove it from system-wide startup. Note: ``system_wide`` requires superuser/admin privileges. ''' deskt...
def remove_item(name, system_wide=False)
Removes a program from startup. Removes a program from startup. Args: name (str) : The name of the program (as known to the system) to remove. See :func:``list_items``. system_wide (bool): Remove it from system-wide startup. Note: ``system_wide`` requires superuser/admin privileges.
2.745198
2.306512
1.190195
from google.appengine.api import users if _IS_DEVELOPMENT_SERVER: return users.get_current_user() else: from google.appengine.api import oauth try: user = oauth.get_current_user() except oauth.OAuthRequestError: ...
def get_current_user(self)
Override get_current_user for Google AppEngine Checks for oauth capable request first, if this fails fall back to standard users API
2.840899
2.196625
1.293301
with (gzip.open(self._es_fn, "tw+") if self.compress_intermediate_files else open(self._es_fn, "w+")) as es_fo: self.bam2es( bam_fn=self._bam_fn, es_fo=es_fo, allowed_delta=self.report.allowed_delta, )
def create_es(self)
Create an ES (intermediate) file for this BAM file. This is the function which asses if an alignment is correct
6.761956
5.626475
1.20181
# default value vec = ["x" for i in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1)] assert len(srs) <= rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1, srs should_be_mapped = bool(srs[0]["m"] + srs[0]["U"] == 0) for q in range(len(srs)): ##### ...
def _vector_of_categories(srs, read_tuple_name, parts)
Create vector of categories (voc[q] ... assigned category for given quality level) srs ... single read statistics ... for every q ... dictionary read_tuple_name ... read name parts ... number of segments
2.21918
2.144566
1.034792
et_fo.write("# Mapping information for read tuples" + os.linesep) et_fo.write("#" + os.linesep) et_fo.write("# RN: read name" + os.linesep) et_fo.write("# I: intervals with asigned categories" + os.linesep) et_fo.write("#" + os.linesep) et_fo.write("# RN I"...
def es2et( es_fo, et_fo, )
Convert ES to ET. Args: es_fo (file): File object for the ES file. et_fo (file): File object for the ET file.
2.36392
2.376523
0.994697
with (gzip.open(self._es_fn, "tr") if self.compress_intermediate_files else open(self._es_fn, "r")) as es_fo: with (gzip.open(self._et_fn, "tw+") if self.compress_intermediate_files else open(self._et_fn, "w+")) as et_fo: self.es2et( es...
def create_et(self)
Create a et file for this BAM file (mapping information about read tuples). raises: ValueError
3.726125
3.728401
0.999389
stats_dicts = [ { "q": q, "M": 0, "w": 0, "m": 0, "P": 0, "U": 0, "u": 0, "T": 0, "t": 0, "x": 0 } for q in range(rnft...
def et2roc(et_fo, roc_fo)
ET to ROC conversion. Args: et_fo (file): File object for the ET file. roc_fo (file): File object for the ROC file. raises: ValueError
2.536446
2.572334
0.986048
with (gzip.open(self._et_fn, "tr") if self.compress_intermediate_files else open(self._et_fn, "r")) as et_fo: with open(self._roc_fn, "w+") as roc_fo: self.et2roc( et_fo=et_fo, roc_fo=roc_fo, )
def create_roc(self)
Create a ROC file for this BAM file. raises: ValueError
4.520159
4.76368
0.94888
categories_order = [ ("{U}", "#ee82ee", 'Unmapped correctly'), ("{u}", "#ff0000", 'Unmapped incorrectly'), ("{T}", "#00ff00", 'Thresholded correctly'), ("{t}", "#008800", 'Thresholded incorrectly'), ("{P}", "#ffff00", 'Multimapped'), ...
def create_gp(self)
Create a GnuPlot file for this BAM file.
3.837439
3.637777
1.054886
rnftools.utils.shell('"{}" "{}"'.format("gnuplot", self._gp_fn)) if self.render_pdf_method is not None: svg_fn = self._svg_fn pdf_fn = self._pdf_fn svg42pdf(svg_fn, pdf_fn, method=self.render_pdf_method)
def create_graphics(self)
Create images related to this BAM file using GnuPlot.
6.726665
6.096006
1.103454
# Check if input is a dictionary if not isinstance(tabdata[0], dict): raise TypeError('Table must be a dictionary. Call the SQL query with query_dict.execute()') # Create an empty table to store the data t = Table() colnames = tabdata[0].keys() # If this is a photometry table, p...
def dict_tovot(tabdata, tabname='votable.xml', phot=False, binary=True)
Converts dictionary table **tabdata** to a VOTable with name **tabname** Parameters ---------- tabdata: list SQL query dictionary list from running query_dict.execute() tabname: str The name of the VOTable to be created phot: bool Parameter specifying if the table contains photome...
4.416061
3.964185
1.11399
colnames = tab[0].keys() tmpdict = dict() for i in range(len(tab)): # If not working on the same source, continue if tab[i]['source_id'] != sourceid: continue # Check column names and create new ones for band-specific ones for elem in colnames: ...
def photaddline(tab, sourceid)
Loop through the dictionary list **tab** creating a line for the source specified in **sourceid** Parameters ---------- tab: Dictionary list of all the photometry data sourceid: ID of source in the photometry table (source_id) Returns ------- tmpdict: dict Dictionary wi...
4.282899
4.065968
1.053353
# Check that source_id column is present if 'source_id' not in tab[0].keys(): raise KeyError('phot=TRUE requires the source_id columb be included') # Loop through the table and grab unique band names and source IDs uniqueid = [] for i in range(len(tab)): tmpid = tab[i]['source...
def photparse(tab)
Parse through a photometry table to group by source_id Parameters ---------- tab: list SQL query dictionary list from running query_dict.execute() Returns ------- newtab: list Dictionary list after parsing to group together sources
4.890915
4.588315
1.06595
x = [] for i in range(len(data)): # If the particular key is not present, use a place-holder value (used for photometry tables) if col not in data[i]: temp = '' else: temp = data[i][col] # Fix up None elements if temp is None: temp = '' ...
def table_add(tab, data, col)
Function to parse dictionary list **data** and add the data to table **tab** for column **col** Parameters ---------- tab: Table class Table to store values data: list Dictionary list from the SQL query col: str Column name (ie, dictionary key) for the column to add
5.646476
5.683601
0.993468
# Get ordering model. model_label = order.utils.resolve_labels('.'.join(\ [self.model._meta.app_label, self.model._meta.object_name])) orderitem_set = getattr(self.model, \ order.utils.resolve_order_item_related_set_name(model_label)) order_model = orderitem_set.related.mode...
def user_order_by(self, field)
Queryset method ordering objects by user ordering field.
5.750319
5.513541
1.042945
def list_enabled_features_accounts(self, account_id): path = {} data = {} params = {} # REQUIRED - PATH - account_id path["account_id"] = account_id self.logger.debug("GET /api/v1/accounts/{account_id}/features/enabled with query params: {par...
List enabled features. List all features that are enabled on a given Account, Course, or User. Only the feature names are returned.
null
null
null
def set_feature_flag_courses(self, feature, course_id, state=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - feature path["feature"] = feature ...
Set feature flag. Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets a feature flag for the same feature in any state other than "allowed".
null
null
null
def set_feature_flag_accounts(self, feature, account_id, state=None): path = {} data = {} params = {} # REQUIRED - PATH - account_id path["account_id"] = account_id # REQUIRED - PATH - feature path["feature"] = feature ...
Set feature flag. Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets a feature flag for the same feature in any state other than "allowed".
null
null
null
def set_feature_flag_users(self, user_id, feature, state=None): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # REQUIRED - PATH - feature path["feature"] = feature # OPTION...
Set feature flag. Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets a feature flag for the same feature in any state other than "allowed".
null
null
null
def remove_feature_flag_courses(self, feature, course_id): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - feature path["feature"] = feature self.lo...
Remove feature flag. Remove feature flag for a given Account, Course, or User. (Note that the flag must be defined on the Account, Course, or User directly.) The object will then inherit the feature flags from a higher account, if any exist. If this flag was 'on' or 'off', then ...
null
null
null
def remove_feature_flag_accounts(self, feature, account_id): path = {} data = {} params = {} # REQUIRED - PATH - account_id path["account_id"] = account_id # REQUIRED - PATH - feature path["feature"] = feature se...
Remove feature flag. Remove feature flag for a given Account, Course, or User. (Note that the flag must be defined on the Account, Course, or User directly.) The object will then inherit the feature flags from a higher account, if any exist. If this flag was 'on' or 'off', then ...
null
null
null
def remove_feature_flag_users(self, user_id, feature): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # REQUIRED - PATH - feature path["feature"] = feature self.logger.debug...
Remove feature flag. Remove feature flag for a given Account, Course, or User. (Note that the flag must be defined on the Account, Course, or User directly.) The object will then inherit the feature flags from a higher account, if any exist. If this flag was 'on' or 'off', then ...
null
null
null
output_path = os.path.join(output_dir_path, output_filename) max_val_data = get_epoch_max_val_acc(data) max_val_label = round(max_val_data['acc'].values[0], 4) # max_val_epoch = max_val_data['epoch'].values[0] max_epoch_data = data[data['epoch'] == data['epoch'].max()] plot = ggplot(data...
def plot_accuracy(data, output_dir_path='.', output_filename='accuracy.png', width=10, height=8)
Plot accuracy. Args: data: Panda dataframe in *the* format.
2.553378
2.614844
0.976493
if not isinstance(data, pd.DataFrame): data = pd.DataFrame(data) plot_accuracy(data, output_dir_path=output_dir_path, width=width, height=height) plot_loss(data, output_dir_path, width=width, height=height)
def plot(data, output_dir_path='.', width=10, height=8)
Create two plots: 1) loss 2) accuracy. Args: data: Panda dataframe in *the* format.
2.355497
2.4395
0.965566
menu = {} for model, model_admin in self.admin_site._registry.items(): if hasattr(model_admin, 'app_config'): if model_admin.app_config.has_menu_permission(obj=self.user): menu.update({ 'app:' + model_admin.app_config.name:...
def get_apps_menu(self)
Temporal code, will change to apps.get_app_configs() for django 1.7 Generate a initial menu list using the AppsConfig registered
3.528507
3.384013
1.042699
_menu = self.get_site_menu() if _menu: site_menu = list(_menu) else: site_menu = [] had_urls = [] def get_url(menu, had_urls): if 'url' in menu: had_urls.append(menu['url']) if 'menus' in menu: ...
def get_nav_menu(self)
Method to generate the menu
2.449235
2.431958
1.007104
_logger.debug("Start connecting to broker") while True: try: self.client.connect(self.broker_host, self.broker_port, self.broker_keepalive) break except Exception: _logger.debug( ...
def connect(self)
connect
3.43274
3.359612
1.021767
orig_tunnel = self.tunnels.get(tunnel_type, (None, None))[0] if orig_tunnel is not None: _logger.debug("Unsubscribe: %s", (orig_tunnel,)) self.client.unsubscribe(str(orig_tunnel)) self.tunnels[tunnel_type] = (tunnel, callback) if callback is not None: ...
def set_tunnel(self, tunnel_type, tunnel, callback=None)
set_tunnel(self, tunnel_type, tunnel, callback=None):
2.739841
2.62475
1.043848
for tunnel_type, (tunnel, callback) in tunnels.iteritems(): if tunnel is None: continue self.set_tunnel(tunnel_type, tunnel, callback)
def set_tunnels(self, tunnels)
set_tunnels(self, tunnels):
3.6932
3.334225
1.107664
result = self.client.publish(topic, payload=json.dumps(payload), qos=qos) if result[0] == mqtt.MQTT_ERR_NO_CONN: raise RuntimeError("No connection") return result[1]
def publish(self, topic="/controller", qos=0, payload=None)
publish(self, topic, payload=None, qos=0, retain=False) Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the client is not currently connected. mid is the message ID for the publish request. The mid value can be used to track the...
2.580595
3.101656
0.832005
logger = logging.getLogger(__name__) logger.setLevel({ 0: DEFAULT_LOGGING_LEVEL, 1: logging.INFO, 2: logging.DEBUG }.get(min(2, verbosity), DEFAULT_LOGGING_LEVEL)) logger.handlers = [] handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) ha...
def get_logger(verbosity)
Returns simple console logger.
1.871296
1.860579
1.00576
def get_outcome_results(self, course_id, include=None, outcome_ids=None, user_ids=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # OPTIONAL - user_ids if user_ids is not N...
Get outcome results. Gets the outcome results for users and outcomes in the specified context.
null
null
null
def get_outcome_result_rollups(self, course_id, aggregate=None, include=None, outcome_ids=None, user_ids=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # OPTIONAL - aggregate ...
Get outcome result rollups. Gets the outcome rollups for the users and outcomes in the specified context.
null
null
null
if isinstance(command, str): self.method(command.split()) elif isinstance(command, list): self.method(command) else: raise TypeError("command should be either a string or list type") if self.error: raise IPMIError(self.error) ...
def execute(self, command)
Primary method to execute ipmitool commands :param command: ipmi command to execute, str or list e.g. > ipmi = ipmitool('consolename.prod', 'secretpass') > ipmi.execute('chassis status') >
3.754037
3.548053
1.058056
p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.output, self.error = p.communicate() self.status = p.returncode
def _subprocess_method(self, command)
Use the subprocess module to execute ipmitool commands and and set status
3.168928
2.743441
1.155092
child = pexpect.spawn(self._ipmitool_path, self.args + command) i = child.expect([pexpect.TIMEOUT, 'Password: '], timeout=10) if i == 0: child.terminate() self.error = 'ipmitool command timed out' self.status = 1 else: chi...
def _expect_method(self, command)
Use the expect module to execute ipmitool commands and set status
2.334294
2.209516
1.056473
p = subprocess.Popen(["which", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out.strip()
def _get_ipmitool_path(self, cmd='ipmitool')
Get full path to the ipmitool command using the unix `which` command
3.502434
3.556298
0.984854
if isinstance(table, (list, set, tuple)): for t in table: self._truncate(t) else: self._truncate(table)
def truncate(self, table)
Empty a table by deleting all of its rows.
2.899416
2.93631
0.987435
statement = "TRUNCATE TABLE {0}".format(wrap(table)) self.execute(statement) self._printer('\tTruncated table {0}'.format(table))
def _truncate(self, table)
Remove all records from a table in MySQL It performs the same function as a DELETE statement without a WHERE clause.
6.297142
6.655147
0.946206
# Change database if needed if database in self.databases and database is not self.database: self.change_db(database) # Get list of tables tables = self.tables if isinstance(self.tables, list) else [self.tables] if len(tables) > 0: self.drop(tabl...
def truncate_database(self, database=None)
Drop all tables in a database.
5.218023
5.171728
1.008951
existing_tables = self.tables if isinstance(table, (list, set, tuple)): for t in table: self._drop(t, existing_tables) else: self._drop(table, existing_tables) return table
def drop(self, table)
Drop a table from a database. Accepts either a string representing a table name or a list of strings representing a table names.
3.163748
3.119894
1.014056
# Retrieve list of existing tables for comparison existing_tables = existing_tables if existing_tables else self.tables # Only drop table if it exists if table in existing_tables: # Set to avoid foreign key errorrs self.execute('SET FOREIGN_KEY_CHECKS = ...
def _drop(self, table, existing_tables=None)
Private method for executing table drop commands.
4.18512
4.036253
1.036882
# Count number of rows in each table counts = self.count_rows_all() drops = [] # Loop through each table key and validate that rows count is not 0 for table, count in counts.items(): if count < 1: # Drop table if it contains no rows ...
def drop_empty_tables(self)
Drop all empty tables in a database.
4.863445
4.905285
0.99147
# Unpack WHERE clause dictionary into tuple where_col, where_val = where # Create column string from list of values cols = get_col_val_str(columns, query_type='update') # Concatenate statement statement = "UPDATE {0} SET {1} WHERE {2}='{3}'".format(wrap(table),...
def update(self, table, columns, values, where)
Update the values of a particular row where a value is met. :param table: table name :param columns: column(s) to update :param values: updated values :param where: tuple, (where_column, where_value)
6.911112
6.951617
0.994173
for row in values: wi = row.pop(where_index) self.update(table, columns, row, (where_col, wi))
def update_many(self, table, columns, values, where_col, where_index)
Update the values of several rows. :param table: Name of the MySQL table :param columns: List of columns :param values: 2D list of rows :param where_col: Column name for where clause :param where_index: Row index of value to be used for where comparison :return:
4.589385
5.488435
0.836192