code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
token_file = os.path.expanduser('~/.nikeplus_access_token') parser = argparse.ArgumentParser(description='Export NikePlus data to CSV') parser.add_argument('-t', '--token', required=False, default=None, help=('Access token for API, can also store in file %s' ...
def _parse_args()
Parse sys.argv arguments
3.671731
3.680005
0.997752
es = set([e.name for e in d.entities]) es_ = set([e.name for e in d_.entities]) e_weight = (len(es) + len(es_) - abs(len(es) - len(es_)))/2 e_score = sum(self.idf_entity[t] for t in es & es_) toks = set(d.tokens) toks_ = set(d_.tokens) t_weight = (len(to...
def similarity(self, d, d_)
Compute a similarity score for two documents. Optionally pass in a `term_sim_ref` dict-like, which should be able to take `term1, term2` as args and return their similarity.
2.615786
2.537524
1.030842
info = match.groupdict() # Put special delimiter cases in terms of normal ones if info['change']: info.update({ 'tag_type' : '=', 'tag_key' : info['delims'], }) elif info['raw']: info.update({ 'tag_type' : '&', 'tag_key' : inf...
def get_match_info(template, match, state)
Given a template and a regex match within said template, return a dictionary of information about the match to be used to help parse the template.
2.755544
2.762893
0.99734
new_contexts = 0 ctm = None while True: try: ctx_key, name = name.split('.', 1) ctm = state.context.get(ctx_key) except ValueError: break if not ctm: break else: state.context.push(ctm) new_contexts ...
def get_tag_context(name, state)
Given a tag name, return its associated value as defined in the current context stack.
3.809361
3.679033
1.035425
state.section.push(tag_key) match = None matchinfo = None search_index = index while state.section: match = state.tag_re.search(template, search_index) if not match: raise Exception("Open section %s never closed" % tag_key) matchinfo = get_match_info(templ...
def section_end_info(template, tag_key, state, index)
Given the tag key of an opening section tag, find the corresponding closing tag (if it exists) and return information about that match.
3.74811
3.495065
1.072401
# Create a new state by default state = state or State() # Add context to the state dict if isinstance(context, Context): state.context = context else: state.context = Context(context) # Add any partials to the state dict if partials: state.partials.push(partia...
def render(template, context, partials={}, state=None)
Renders a given mustache template, with sane defaults.
3.92682
3.899601
1.00698
new_contexts, context_match = get_tag_context(info['tag_key'], state) replacement = '' if context_match or context_match == 0: replacement = context_match elif info['tag_key'] == '.': replacement = state.context() else: replacement = '' # Call all callables / metho...
def __render_tag(info, state)
Render an individual tag by making the appropriate replacement within the current context (if any).
6.460142
6.199381
1.042062
result = '' for k, v in dict.items(): result = result + str(k) + format + str(v) + ', ' return result[:-2]
def format_dict_to_str(dict, format)
Format a dictionary to the string, param format is a specified format rule such as dict = '{'name':'Sylvanas', 'gender':'Boy'}' format = '-' so result is 'name-Sylvanas, gender-Boy'. >>> dict = {'name': 'Sylvanas', 'gender': 'Boy'} >>> format_dict_to_str(dict, format='-') 'name-Sylvanas, gender-Boy...
2.507127
3.113538
0.805234
list = [str(x) for x in list] return separator.join(list)
def list_to_str(list, separator=',')
>>> list = [0, 0, 7] >>> list_to_str(list) '0,0,7'
2.714257
6.20259
0.437601
c = {} c.update(a) c.update(b) return c
def unite_dict(a, b)
>>> a = {'name': 'Sylvanas'} >>> b = {'gender': 'Man'} >>> unite_dict(a, b) {'name': 'Sylvanas', 'gender': 'Man'}
2.656444
5.362
0.49542
for key in keys: if key not in dict or dict[key] is '' or dict[key] is None: return False return True
def check_validity_for_dict(keys, dict)
>>> dict = {'a': 0, 'b': 1, 'c': 2} >>> keys = ['a', 'd', 'e'] >>> check_validity_for_dict(keys, dict) == False True >>> keys = ['a', 'b', 'c'] >>> check_validity_for_dict(keys, dict) == False False
2.635175
3.476292
0.758042
if expand_args: return Parallel(n_jobs=n_jobs)(delayed(func)(*args) for args in inputs) else: return Parallel(n_jobs=n_jobs)(delayed(func)(arg) for arg in inputs)
def parallel(func, inputs, n_jobs, expand_args=False)
Convenience wrapper around joblib's parallelization.
1.581223
1.635682
0.966706
breeding = get_object_or_404(Breeding, pk=breeding_id) if request.method == "POST": form = BreedingPlugForm(request.POST, request.FILES) if form.is_valid(): plug = form.save(commit=False) plug.Breeding_id = breeding.id plug.save() form.save() ...
def breeding_plugevent(request, breeding_id)
This view defines a form for adding new plug events from a breeding cage. This form requires a breeding_id from a breeding set and restricts the PlugFemale and PlugMale to animals that are defined in that breeding cage.
2.007257
1.883867
1.065499
self.strain = get_object_or_404(Strain, Strain_slug__iexact=self.kwargs['slug']) return PlugEvents.objects.filter(Breeding__Strain=self.strain)
def get_queryset(self)
The queryset is over-ridden to show only plug events in which the strain matches the breeding strain.
6.463934
3.009778
2.147645
if len(args) > 1: print(f'Usage: {args[0]}') return db = state.db _refresh_incomplete_anime(db) _fix_cached_completed(db)
def command(state, args)
Fix cache issues caused by schema pre-v4.
8.190762
7.368568
1.111581
self.convertRSTmetaToMD() self._md = Markdown(extensions=['meta', 'codehilite(linenums=True)']) content = self._md.convert(self.source) metadata = self._parse_metadata(self._md.Meta) return content, metadata
def read(self)
Parse content and metadata of markdown files
7.350352
5.366693
1.369624
assert "psql_user" in env, "Missing psql_user in env" assert "psql_db" in env, "Missing psql_db in env" assert "psql_password" in env, "Missing psql_password in env" if not release: release = paths.get_current_release_name() max_versions = limit+1 if not release: logger....
def backup_db(release=None, limit=5)
Backup database and associate it with current release
3.040179
3.048071
0.997411
if not release: release = paths.get_current_release_name() if not release: raise Exception("Release %s was not found" % release) backup_file = "postgresql/%s.sql.gz" % release backup_path = paths.get_backup_path(backup_file) if not env.exists(backup_path): raise Exce...
def restore_db(release=None)
Restores backup back to version, uses current version by default.
2.94845
2.890733
1.019966
_check_requirements() if force != "yes": message = "This will replace the remote database '%s' with your "\ "local '%s', are you sure [y/n]" % (env.psql_db, env.local_psql_db) answer = prompt(message, "y") if answer != "y": logger.info("Sync stopped") ...
def sync_local_to_remote(force="no")
Sync your local postgres database with remote Example: fabrik prod sync_local_to_remote:force=yes
3.816612
3.826596
0.997391
_check_requirements() if force != "yes": message = "This will replace your local database '%s' with the "\ "remote '%s', are you sure [y/n]" % (env.local_psql_db, env.psql_db) answer = prompt(message, "y") if answer != "y": logger.info("Sync stopped") ...
def sync_remote_to_local(force="no")
Sync your remote postgres database with local Example: fabrik prod sync_remote_to_local
3.691152
3.683405
1.002103
if DJANGO_VERSION >= (1, 5): from django.contrib.auth import get_user_model return get_user_model() # NOQA else: from django.contrib.auth.models import User # NOQA return User
def get_user_model()
Returns the user model to use at runtime. :return: User or custom user
2.376307
2.832278
0.839009
if DJANGO_VERSION >= (1, 7): from django.apps import apps return apps.is_installed(app_name) else: from django.conf import settings return app_name in settings.INSTALLED_APPS
def has_app(app_name)
Determines whether an app is listed in INSTALLED_APPS or the app registry. :param app_name: string :return: bool
2.267907
2.469639
0.918315
self.query = config.get("query") self.expected_response = config.get("response")
def apply_check_config(self, config)
Takes the `query` and `response` fields from a validated config dictionary and sets the proper instance attributes.
6.534645
3.321237
1.967534
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) # if no query/response is defined, a successful connection is a pass if not self.query: sock.close() return True try: sock.sendall(self.qu...
def perform(self)
Performs a straightforward TCP request and response. Sends the TCP `query` to the proper host and port, and loops over the socket, gathering response chunks until a full line is acquired. If the response line matches the expected value, the check passes. If not, the check fails. The c...
3.315648
3.074824
1.078321
src_host = self._get_hosts_from_names(config.get(section, 'src.host')) \ if config.has_option(section, 'src.host') else None src_file = [self._get_abs_filepath(config.get(section, 'src.file'))] \ if config.has_option(section, 'src.file') else None if src_host is ...
def _get_section_values(self, config, section)
extract src and dst values from a section
1.853562
1.751667
1.05817
values = map(lambda x: [] if x is None else x, values) src = values[0] + values[1] dst = values[2] + values[3] thistable = dict() for s in src: thistable[s] = dst return thistable
def _assemble_flowtable(self, values)
generate a flowtable from a tuple of descriptors.
3.954327
3.555381
1.112209
for source, dests in self.flowtable.items(): if source in dests: raise conferr('Loops detected: %s --> %s' % (source, source))
def _detect_loop(self)
detect loops in flow table, raise error if being present
9.980742
6.243045
1.598698
hosts = map(lambda x: 'localhost:%d' % int(x.strip()), ports.split(',')) return list(set(hosts))
def _get_hosts_from_ports(self, ports)
validate hostnames from a list of ports
5.282133
4.613341
1.144969
result = set() hosts = map(lambda x: x.strip(), names.split(',')) for h in hosts: if valid_hostname(h.split(':')[0]): result.add(h if ':' in h else '%s:%d' % (h, self.PORT)) else: raise conferr('Invalid hostname: %s' % h.split(':')...
def _get_hosts_from_names(self, names)
validate hostnames from a list of names
3.607829
3.340056
1.08017
assert ifile is not None ifile = ifile[7:] if ifile.startswith('file://') else ifile if ifile[0] != '/': basedir = os.path.abspath(os.path.dirname(self.config_file)) ifile = os.path.join(basedir, ifile) return 'file://' + ifile
def _get_abs_filepath(self, ifile)
validate src or dst file path with self.config_file
2.671776
2.375355
1.12479
ftable = dict() for table in self.flow_table: for k, v in table.items(): if k not in ftable: ftable[k] = set(v) else: [ftable[k].add(i) for i in v] # convert set to list for k in ftable: ...
def flowtable(self)
get a flat flow table globally
2.450653
2.225058
1.101388
@functools.wraps(func) def new_func(self, *args, **kwargs): # pylint: disable=missing-docstring aid = func(self, *args, **kwargs) self.last_aid = aid return aid return new_func
def _set_last_aid(func)
Decorator for setting last_aid.
2.125757
1.994958
1.065565
if default_key not in self: raise ResultKeyError(default_key) if text == '.': return self.last_aid elif text.startswith('aid:'): return int(text[len('aid:'):]) if ':' in text: match = self._key_pattern.search(text) i...
def parse_aid(self, text, default_key)
Parse argument text for aid. May retrieve the aid from search result tables as necessary. aresults determines which search results to use by default; True means aresults is the default. The last aid when no aid has been parsed yet is undefined. The accepted formats, in order:...
2.612406
2.42664
1.076553
directory, filename = os.path.split(relative_path) partials_dir = os.path.abspath(directory) name, ext = os.path.splitext(filename) state = State(partials_dir=directory, extension=ext, *args, **kwargs) template = load_template(name, directory, ext, state.encoding, state.encoding_error) d...
def template(relative_path, *args, **kwargs)
A decorator for easily rendering templates. Use as follows: main.py: from mustache import (template) @template('../tests/static/say_hello.html') def index(): context = {'name' : 'world'} partials = {} return context, partials if __name__=="_...
2.638915
2.792711
0.94493
conn = apsw.Connection(os.fspath(dbfile)) _set_foreign_keys(conn, 1) assert _get_foreign_keys(conn) == 1 return conn
def _connect(dbfile: 'PathLike') -> apsw.Connection
Connect to SQLite database file.
4.071998
3.508373
1.160651
while True: cmdline = input(self.prompt) tokens = shlex.split(cmdline) if not tokens: if self.last_cmd: tokens = self.last_cmd else: print('No previous command.') continue ...
def cmdloop(self)
Start CLI REPL.
3.134662
3.120986
1.004382
return np.linspace(self.volume, self.volume, self.duration * channels).reshape(self.duration, channels)
def to_array(self, channels=2)
Generate the array of multipliers for the dynamic
8.155419
8.462399
0.963724
experiment = get_object_or_404(Experiment, pk=experiment_id) if request.method == 'POST': form = MeasurementForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect( experiment.get_absolute_url() ) else: form = MeasurementForm() return render(request, "data_entry_form.html", {"...
def add_measurement(request, experiment_id)
This is a view to display a form to add single measurements to an experiment. It calls the object MeasurementForm, which has an autocomplete field for animal.
1.910612
1.932093
0.988882
experiment = get_object_or_404(Experiment, pk=pk) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=experiment.csv' writer = csv.writer(response) writer.writerow(["Animal","Cage", "Strain", "Genotype", "Gender","Age", "Assay", "Values", "Fe...
def experiment_details_csv(request, pk)
This view generates a csv output file of an experiment. The view writes to a csv table the animal, genotype, age (in days), assay and values.
2.888586
2.659177
1.08627
animal_list = Animal.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=aging.csv' writer = csv.writer(response) writer.writerow(["Animal", "Strain", "Genotype", "Gender", "Age", "Death", "Alive"]) for animal in animal_list...
def aging_csv(request)
This view generates a csv output file of all animal data for use in aging analysis. The view writes to a csv table the animal, strain, genotype, age (in days), and cause of death.
2.71596
2.434072
1.115809
animal_list = Animal.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=litters.csv' writer = csv.writer(response) writer.writerow(["Born", "Breeding", "Strain"]) for animal in animal_list: writer.writerow([ ...
def litters_csv(request)
This view generates a csv output file of all animal data for use in litter analysis. The view writes to a csv table the birthdate, breeding cage and strain.
2.163899
1.842418
1.174489
response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=data.csv' writer = csv.writer(response) writer.writerow(["Animal", "Genotype", "Gender","Assay", "Value","Strain", "Background","Age", "Cage", "Feeding", "Treatment"]) for measurement in me...
def data_csv(request, measurement_list)
This view generates a csv output of all data for a strain. For this function to work, you have to provide the filtered set of measurements.
3.183804
3.08678
1.031432
'''The queryset is filtered by measurements of animals which are part of that strain.''' cohort = get_object_or_404(Cohort, slug=self.kwargs['slug']) animals = cohort.animals.all() return Measurement.objects.filter(animal=animals)
def get_queryset(self)
The queryset is filtered by measurements of animals which are part of that strain.
6.284286
2.574136
2.441319
'''The queryset is filtered by measurements of animals which are part of that strain.''' cohort = get_object_or_404(Cohort, slug=self.kwargs['slug']) animals = cohort.animals.all() measurements = Measurement.objects.filter(animal=animals) return data_csv(self.request, measure...
def get(self, request, *args, **kwargs)
The queryset is filtered by measurements of animals which are part of that strain.
6.411858
3.096872
2.070431
'''The queryset returns all measurement objects''' measurements = Measurement.objects.all() return data_csv(self.request, measurements)
def get(self, request, *args, **kwargs)
The queryset returns all measurement objects
21.908197
9.315436
2.351817
'''The queryset is filtered by measurements of animals which are part of that strain.''' strain = get_object_or_404(Strain, Strain_slug=self.kwargs['strain_slug']) animals = Animal.objects.filter(Strain=strain) return Measurement.objects.filter(animal=animals)
def get_queryset(self)
The queryset is filtered by measurements of animals which are part of that strain.
6.096613
2.709835
2.24981
'''The queryset is filtered by measurements of animals which are part of that strain.''' strain = get_object_or_404(Strain, Strain_slug=self.kwargs['strain_slug']) animals = Animal.objects.filter(Strain=strain) measurements = Measurement.objects.filter(animal=animals) return ...
def get(self, request, *args, **kwargs)
The queryset is filtered by measurements of animals which are part of that strain.
5.9448
3.011665
1.973925
''' Returns the feature vectors for a set of docs. If model is not already be trained, then self.train() is called. Args: docs (dict or list of tuples): asset_id, body_text of documents you wish to featurize. ''' if type(docs) == dict: ...
def vectorize( self, docs )
Returns the feature vectors for a set of docs. If model is not already be trained, then self.train() is called. Args: docs (dict or list of tuples): asset_id, body_text of documents you wish to featurize.
4.379107
2.812317
1.557117
''' Train Doc2Vec on a series of docs. Train from scratch or update. Args: docs: list of tuples (assetid, body_text) or dictionary {assetid : body_text} retrain: boolean, retrain from scratch or update model saves model in class to self.model Returns...
def train(self, docs, retrain=False)
Train Doc2Vec on a series of docs. Train from scratch or update. Args: docs: list of tuples (assetid, body_text) or dictionary {assetid : body_text} retrain: boolean, retrain from scratch or update model saves model in class to self.model Returns: 0 if successful
5.218668
2.487405
2.098037
''' takes a list of sentenes and updates an existing model. Vectors will be callable through self.model[label] update_labels_bool: boolean that says whether to train the model (self.model.train_words = True) or simply to get vectors for the documents (self.model.train_words = F...
def update_model(self, sentences, update_labels_bool)
takes a list of sentenes and updates an existing model. Vectors will be callable through self.model[label] update_labels_bool: boolean that says whether to train the model (self.model.train_words = True) or simply to get vectors for the documents (self.model.train_words = False) s...
4.495905
2.378012
1.890615
''' Takes in html-mixed body text as a string and returns a list of strings, lower case and with punctuation given spacing. Called by self._gen_sentence() Args: inpnut (string): body text ''' input = re.sub("<[^>]*>", " ", input) punct = l...
def _process(self, input)
Takes in html-mixed body text as a string and returns a list of strings, lower case and with punctuation given spacing. Called by self._gen_sentence() Args: inpnut (string): body text
8.473676
2.524045
3.357181
''' Takes an assetid_body_tuple and returns a Doc2Vec LabeledSentence Args: assetid_body_tuple (tuple): (assetid, bodytext) pair ''' asset_id, body = assetid_body_tuple text = self._process(body) sentence = LabeledSentence(text, labels=['DOC_%s' % s...
def _gen_sentence(self, assetid_body_tuple)
Takes an assetid_body_tuple and returns a Doc2Vec LabeledSentence Args: assetid_body_tuple (tuple): (assetid, bodytext) pair
5.341574
2.932568
1.821466
''' Adds new sentences to the internal indexing of the model. Args: sentences (list): LabeledSentences for each doc to be added Returns: int: number of sentences added to the model ''' sentence_no = -1 total_words = 0 vocab = se...
def _add_new_labels(self, sentences)
Adds new sentences to the internal indexing of the model. Args: sentences (list): LabeledSentences for each doc to be added Returns: int: number of sentences added to the model
3.980437
2.873779
1.385088
# type: (List[str], str, bool) -> None pylint_return_state = False flake8_return_state = False if check_licenses: run_license_checker(config_path=get_license_checker_config_path(config_dir)) pylint_options = get_pylint_options(config_dir=config_dir) flake8_options = get_flake8_opt...
def run(targets, config_dir='.', check_licenses=False)
Runs `pylint` and `flake8` commands and exits based off the evaluation of both command results. :param targets: List[str] :param config_dir: str :param check_licenses: bool :return:
2.169132
2.448124
0.886039
# type: (str, List[str], List[str]) -> bool print('{0}: targets={1} options={2}'.format(command, targets, options)) cmd = [command] + targets + options process = Popen(cmd) process.wait() return bool(process.returncode)
def _run_command(command, targets, options)
Runs `command` + `targets` + `options` in a subprocess and returns a boolean determined by the process return code. >>> result = run_command('pylint', ['foo.py', 'some_module'], ['-E']) >>> result True :param command: str :param targets: List[str] :param options: List[str] :return:...
3.016787
4.096478
0.736434
def ynnm(n, m): a = 1.0 / np.sqrt(4.0 * np.pi) pm = np.abs(m) out = 0.0 if(n < pm): out = 0.0 elif(n == 0): out = a else: out = a for k in xrange(1, n + 1): out *= np.sqrt((2.0 * k + 1.0) / 8.0 / k) if(n != pm): ...
Initial value for recursion formula
null
null
null
def ynunm(n, m, L): out = np.zeros(L, dtype=np.float64) tmp1 = 0 tmp2 = 0 tmp3 = 0 tmp4 = 0 if(np.abs(m) <= n): out[n] = ynnm(n, m) k = n - 2 if(k >= 0): tmp1 = (n - k - 1.0) * (n + k + 2.0) tmp2 = (n - k - 2.0) * (n + k ...
Fourier coefficients for spherical harmonics
null
null
null
def smallest_prime_factor(Q): A = Q; while(A != 1): if(np.mod(A, 2) == 0): A = A / 2 elif(np.mod(A, 3) == 0): A = A / 3 elif(np.mod(A, 5) == 0): A = A / 5 elif(np.mod(A, 7) == 0): A = A / 7; else: ...
Find the smallest number factorable by the small primes 2, 3, 4, and 7 that is larger than the argument Q
null
null
null
def s_data(nrows_fdata, Nmax, Q): if np.mod(nrows_fdata, 2) == 1: raise Exception("nrows_fdata must be even.") L1 = nrows_fdata s = np.zeros(Q, dtype=np.complex128) MM = int(L1 / 2) for nu in xrange(-MM, MM + Nmax + 1): if np.mod(nu, 2) == 1: s[n...
I am going to assume we will always have even data. This is pretty safe because it means that we have measured both poles of the sphere and have data that has been continued. nrows_fdata: Number of rows in fdata. Nmax: The largest number of n values desired. Q: ...
null
null
null
def hkm_fc(fdata, Nmax, m, s): f = fdata[:, m] L1 = f.size MM = int(L1 / 2) Q = s.size ff = np.zeros(Q, dtype=np.complex128) for n in xrange(MM, L1): ff[n] = f[n - MM] for n in xrange(0, MM): ff[n] = f[n + MM] # For larger problems, this speeds thi...
Assume fdata has even rows
null
null
null
def mindx(m, nmax, mmax): ind = 0 NN = nmax + 1 if np.abs(m) > mmax: raise Exception("|m| cannot be larger than mmax") if (m != 0): ind = NN ii = 1 for i in xrange(1, np.abs(m)): ind = ind + 2 * (NN - i) ii = i + 1 ...
index to the first n value for a give m within the spherical coefficients vector. Used by sc_to_fc
null
null
null
def sc_to_fc(spvec, nmax, mmax, nrows, ncols): fdata = np.zeros([int(nrows), ncols], dtype=np.complex128) for k in xrange(0, int(ncols / 2)): if k < mmax: kk = k ind = mindx(kk, nmax, mmax) vec = spvec[ind:ind + nmax - np.abs(kk) + 1] fdat...
assume Ncols is even
null
null
null
use_dict = JobCalculation._use_methods use_dict.update({ "parameters": { 'valid_types': RipsDistanceMatrixParameters, 'additional_parameter': None, 'linkname': 'parameters', 'docstring': 'add command line parameters', ...
def _use_methods(cls)
Add use_* methods for calculations. Code below enables the usage my_calculation.use_parameters(my_parameters)
3.085301
3.071637
1.004449
# Check inputdict try: parameters = inputdict.pop(self.get_linkname('parameters')) except KeyError: raise InputValidationError("No parameters specified for this " "calculation") if not isinstance(parameters, RipsDist...
def _validate_inputs(self, inputdict)
Validate input links.
2.595584
2.555152
1.015824
parameters, code, distance_matrix, symlink = \ self._validate_inputs(inputdict) # Prepare CalcInfo to be returned to aiida calcinfo = CalcInfo() calcinfo.uuid = self.uuid calcinfo.remote_copy_list = [] calcinfo.retrieve_list = parameters.output_f...
def _prepare_for_submission(self, tempfolder, inputdict)
Create input files. :param tempfolder: aiida.common.folders.Folder subclass where the plugin should put all its files. :param inputdict: dictionary of the input nodes as they would be returned by get_inputs_dict
2.833398
3.165453
0.8951
with db: cur = db.cursor() if not force: # We don't do anything if we already have this aid in our # cache. cur.execute('SELECT 1 FROM cache_anime WHERE aid=?', (aid,)) if cur.fetchone() is not None: return # Retrieve info...
def cache_status(db, aid, force=False)
Calculate and cache status for given anime. Don't do anything if status already exists and force is False.
5.59493
5.390409
1.037942
upsert(db, 'cache_anime', ['aid'], { 'aid': aid, 'complete': 1 if complete else 0, 'watched_episodes': watched_episodes, })
def set_status( db, aid: int, complete: Any, watched_episodes: int, ) -> None
Set anime status.
4.523324
3.953324
1.144183
cur = db.cursor() cur.execute( , (1,)) for row in cur: yield row[0]
def get_complete(db) -> Iterator[int]
Return AID of complete anime.
5.503338
5.537071
0.993908
'''Create a component out of a loaded module. Turns a previously-loaded shared module into a component in the manager. This will invalidate any objects that are children of this node. The @ref module_name argument can contain options that set various properties of the n...
def create_component(self, module_name)
Create a component out of a loaded module. Turns a previously-loaded shared module into a component in the manager. This will invalidate any objects that are children of this node. The @ref module_name argument can contain options that set various properties of the new componen...
7.225063
2.021121
3.57478
'''Delete a component. Deletes the component specified by @ref instance_name from the manager. This will invalidate any objects that are children of this node. @param instance_name The instance name of the component to delete. @raises FailedToDeleteComponentError ''' ...
def delete_component(self, instance_name)
Delete a component. Deletes the component specified by @ref instance_name from the manager. This will invalidate any objects that are children of this node. @param instance_name The instance name of the component to delete. @raises FailedToDeleteComponentError
6.496684
3.313513
1.960663
'''Load a shared library. Call this function to load a shared library (DLL file under Windows, shared object under UNIX) into the manager. @param path The path to the shared library. @param init_func The name entry function in the library. @raises FailedToLoadModuleErro...
def load_module(self, path, init_func)
Load a shared library. Call this function to load a shared library (DLL file under Windows, shared object under UNIX) into the manager. @param path The path to the shared library. @param init_func The name entry function in the library. @raises FailedToLoadModuleError
6.376245
3.244289
1.965375
'''Unload a loaded shared library. Call this function to remove a shared library (e.g. a component) that was previously loaded. @param path The path to the shared library. @raises FailedToUnloadModuleError ''' with self._mutex: if self._obj.unload_m...
def unload_module(self, path)
Unload a loaded shared library. Call this function to remove a shared library (e.g. a component) that was previously loaded. @param path The path to the shared library. @raises FailedToUnloadModuleError
6.833747
3.017473
2.264725
'''The list of components in this manager, if any. This information can also be found by listing the children of this node that are of type @ref Component. That method is more useful as it returns the tree entries for the components. ''' with self._mutex: if...
def components(self)
The list of components in this manager, if any. This information can also be found by listing the children of this node that are of type @ref Component. That method is more useful as it returns the tree entries for the components.
8.231048
2.330013
3.532619
'''The factory profiles of all loaded modules.''' with self._mutex: if not self._factory_profiles: self._factory_profiles = [] for fp in self._obj.get_factory_profiles(): self._factory_profiles.append(utils.nvlist_to_dict(fp.properties)) ...
def factory_profiles(self)
The factory profiles of all loaded modules.
4.849164
3.950997
1.227327
'''Set a configuration parameter of the manager. @param The parameter to set. @value The new value for the parameter. @raises FailedToSetConfigurationError ''' with self._mutex: if self._obj.set_configuration(param, value) != RTC.RTC_OK: rais...
def set_config_parameter(self, param, value)
Set a configuration parameter of the manager. @param The parameter to set. @value The new value for the parameter. @raises FailedToSetConfigurationError
6.533834
3.933283
1.661165
'''The configuration dictionary of the manager.''' with self._mutex: if not self._configuration: self._configuration = utils.nvlist_to_dict(self._obj.get_configuration()) return self._configuration
def configuration(self)
The configuration dictionary of the manager.
6.339044
5.116691
1.238895
'''The manager's profile.''' with self._mutex: if not self._profile: profile = self._obj.get_profile() self._profile = utils.nvlist_to_dict(profile.properties) return self._profile
def profile(self)
The manager's profile.
6.354617
5.491945
1.15708
'''The list of loadable module profile dictionaries.''' with self._mutex: if not self._loadable_modules: self._loadable_modules = [] for mp in self._obj.get_loadable_modules(): self._loadable_modules.append(utils.nvlist_to_dict(mp.propertie...
def loadable_modules(self)
The list of loadable module profile dictionaries.
4.624448
3.43512
1.346226
'''The list of loaded module profile dictionaries.''' with self._mutex: if not self._loaded_modules: self._loaded_modules = [] for mp in self._obj.get_loaded_modules(): self._loaded_modules.append(utils.nvlist_to_dict(mp.properties)) ...
def loaded_modules(self)
The list of loaded module profile dictionaries.
4.812211
3.66924
1.311501
'''The list of slave managers of this manager, if any. This information can also be found by listing the children of this node that are of type @ref Manager. ''' with self._mutex: if not self._slaves: self._slaves = [c for c in self.children if c.is_...
def slaves(self)
The list of slave managers of this manager, if any. This information can also be found by listing the children of this node that are of type @ref Manager.
7.037307
2.705577
2.601038
try: token = oauth2_provider.oauth2.models.AccessToken.objects.select_related('user') # provider_now switches to timezone aware datetime when # the oauth2_provider version supports to it. token = token.get(token=access_token, expires__gt=provider_now()) ...
def authenticate_credentials(self, request, access_token)
Authenticate the request, given the access token.
3.805506
3.776299
1.007734
return RequestsHandler(*args, api_token=self.api_token, verify=self.mist_client.verify, job_id=self.mist_client.job_id, **kwargs)
def request(self, *args, **kwargs)
The main purpose of this is to be a wrapper-like function to pass the api_token and all the other params to the requests that are being made :returns: An instance of RequestsHandler
7.852651
6.602049
1.189426
req = self.request(self.mist_client.uri + '/clouds/' + self.id) req.delete() self.mist_client.update_clouds()
def delete(self)
Delete the cloud from the list of added clouds in mist.io service. :returns: A list of mist.clients' updated clouds.
7.875427
5.75617
1.368171
payload = { "new_state": "1" } data = json.dumps(payload) req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data) req.post() self.enabled = True self.mist_client.update_clouds()
def enable(self)
Enable the Cloud. :returns: A list of mist.clients' updated clouds.
6.220538
5.226795
1.190125
payload = { "new_state": "0" } data = json.dumps(payload) req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data) req.post() self.enabled = False self.mist_client.update_clouds()
def disable(self)
Disable the Cloud. :returns: A list of mist.clients' updated clouds.
6.018848
5.048109
1.192298
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/sizes') sizes = req.get().json() return sizes
def sizes(self)
Available machine sizes to be used when creating a new machine. :returns: A list of available machine sizes.
12.135633
10.433912
1.163095
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/locations') locations = req.get().json() return locations
def locations(self)
Available locations to be used when creating a new machine. :returns: A list of available locations.
11.837616
11.374287
1.040735
if self.provider in ['openstack', 'nephoscale']: req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/networks') networks = req.get().json() return networks else: print "Network actions not supported yet for %s provider" % self.provider
def networks(self)
Available networks. :returns: A list of available networks associated to a provider.
8.49402
8.342522
1.01816
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/images') images = req.get().json() return images
def images(self)
Available images to be used when creating a new machine. :returns: A list of all available images.
11.753784
10.837763
1.084521
payload = { 'search_term': search_term } data = json.dumps(payload) req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/images', data=data) images = req.get().json() return images
def search_image(self, search_term)
Search for a specific image by providing a search term (mainly used with ec2's community and public images) :param search_term: Search term to be used when searching for images's names containing this term. :returns: A list of all images, whose names contain the given search_term.
6.029801
6.011257
1.003085
try: req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/machines') machines = req.get().json() except: # Eg invalid cloud credentials machines = {} if machines: for machine in machines: self._machines...
def _list_machines(self)
Request a list of all added machines. Populates self._machines dict with mist.client.model.Machine instances
5.495579
4.732792
1.161171
if self._machines is None: self._machines = {} self._list_machines() if id: return [self._machines[machine_id] for machine_id in self._machines.keys() if str(id) == str(self._machines[machine_id].id)] elif name: return...
def machines(self, id=None, name=None, search=None)
Property-like function to call the _list_machines function in order to populate self._machines dict :returns: A list of Machine instances.
1.566603
1.526435
1.026314
payload = { 'action': action } data = json.dumps(payload) req = self.request(self.mist_client.uri+'/clouds/'+self.cloud.id+'/machines/'+self.id, data=data) req.post() self.cloud.update_machines()
def _machine_actions(self, action)
Actions for the machine (e.g. stop, start etc) :param action: Can be "reboot", "start", "stop", "destroy" :returns: An updated list of the added machines
6.194614
6.719777
0.921848
ips = [ip for ip in self.info['public_ips'] if ':' not in ip] if not ips: raise Exception("No public IPv4 address available to connect to") payload = { 'host': ips[0], 'key': key_id, 'ssh_user': ssh_user } data = json.dump...
def probe(self, key_id=None, ssh_user=None)
If no parameter is provided, mist.io will try to probe the machine with the default :param key_id: Optional. Give if you explicitly want to probe with this key_id :param ssh_user: Optional. Give if you explicitly want a specific user :returns: A list of data received by the probi...
4.260323
4.287592
0.99364
payload = { 'action': action, 'name': self.name, 'no_ssh': no_ssh, 'public_ips': self.info['public_ips'], 'dns_name': self.info['extra'].get('dns_name', 'n/a') } data = json.dumps(payload) req = self.request(self.mist...
def _toggle_monitoring(self, action, no_ssh=False)
Enable or disable monitoring on a machine :param action: Can be either "enable" or "disable"
4.50443
4.667056
0.965154
payload = { 'v': 2, 'start': start, 'stop': stop, 'step': step } data = json.dumps(payload) req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/stats", data=data) stats = req.get().json(...
def get_stats(self, start=int(time()), stop=int(time())+10, step=10)
Get stats of a monitored machine :param start: Time formatted as integer, from when to fetch stats (default now) :param stop: Time formatted as integer, until when to fetch stats (default +10 seconds) :param step: Step to fetch stats (default 10 seconds) :returns: A dict of stats
4.826836
5.14595
0.937987
req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics") metrics = req.get().json() return metrics
def available_metrics(self)
List all available metrics that you can add to this machine :returns: A list of dicts, each of which is a metric that you can add to a monitored machine
9.935064
9.173052
1.083071
payload = { 'metric_id': metric_id } data = json.dumps(payload) req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics", data=data) req.put()
def add_metric(self, metric_id)
Add a metric to a monitored machine :param metric_id: Metric_id (provided by self.available_metrics)
6.104587
5.572134
1.095556
payload = { 'metric_id': metric_id } data = json.dumps(payload) req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics", data=data) req.delete()
def remove_metric(self, metric_id)
Remove a metric from a monitored machine :param metric_id: Metric_id (provided by self.get_stats() )
6.231542
5.786557
1.0769
if not os.path.isfile(python_file): raise Exception(python_file, "is not a file or could not be found in tho given path") with open(python_file) as f: script = f.read() payload = { 'plugin_type': 'python', 'name': name, 'uni...
def add_python_plugin(self, name, python_file, value_type="gauge", unit=None)
Add a custom python plugin to the collectd instance of a monitored plugin :param python_file: Path of the python file to be added as custom python plugin :param name: Name of the plugin :param value_type: Optional. Can be either "gauge" or "derive" :param unit: Optional. If given the ne...
3.708271
3.813899
0.972304