code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
cmap = get_cmap(cmap) name = "%s-trunc-%.2g-%.2g" % (cmap.name, minval, maxval) return colors.LinearSegmentedColormap.from_list( name, cmap(np.linspace(minval, maxval, n)))
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=256)
Truncates a colormap, such that the new colormap consists of ``cmap[minval:maxval]``. If maxval is larger than minval, the truncated colormap will be reversed. Args: cmap (colormap): Colormap to be truncated minval (float): Lower bound. Should be a float betwee 0 and 1. maxval (float): U...
2.346139
2.718762
0.862944
A = get_cmap(lower) B = get_cmap(upper) name = "%s-%s" % (A.name, B.name) lin = np.linspace(0, 1, n) return array_cmap(np.vstack((A(lin), B(lin))), name, n=n)
def stack_colormap(lower, upper, n=256)
Stacks two colormaps (``lower`` and ``upper``) such that low half -> ``lower`` colors, high half -> ``upper`` colors Args: lower (colormap): colormap for the lower half of the stacked colormap. upper (colormap): colormap for the upper half of the stacked colormap. n (int): Number of colormap ...
3.784441
4.154463
0.910934
@functools.wraps(func) def decorated(*args, **kwargs): warnings.warn_explicit( "Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, filename=func.__code__.co_filename, lineno=func.__code__.co_firstlineno + 1 )...
def deprecated(func)
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
1.62515
1.527582
1.063871
# type: (ModelBase, Any)->Optional[AppModel] if model is None: return None app_model = model.get_app_model() is_dict = isinstance(nested_fields, dict) for field in nested_fields: field = get_nested_field_name(field) nested_nested = nested_fields.get( field...
def nested_model(model, nested_fields)
Return :class:`zsl.db.model.app_model import AppModel` with the nested models attached. ``nested_fields`` can be a simple list as model fields, or it can be a tree definition in dict with leafs as keys with ``None`` value
4.365024
4.309229
1.012948
df = partial(state.ast_dispatcher, name, priority=priority) sol_stmt_list = df(state.solution_ast) try: sol_stmt = sol_stmt_list[index] except IndexError: raise IndexError("Can't get %s statement at index %s" % (name, index)) stu_stmt_list = df(state.student_ast) try: ...
def check_node( state, name, index=0, missing_msg="Check the {ast_path}. Could not find the {index}{node_name}.", priority=None, )
Select a node from abstract syntax tree (AST), using its name and index position. Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). name : the name of the abstract syntax tree node to find. index: the position of that node (see below for det...
5.139233
5.123827
1.003007
try: sol_attr = getattr(state.solution_ast, name) if sol_attr and isinstance(sol_attr, list) and index is not None: sol_attr = sol_attr[index] except IndexError: raise IndexError("Can't get %s attribute" % name) # use speaker on ast dialect module to get message, or...
def check_edge( state, name, index=0, missing_msg="Check the {ast_path}. Could not find the {index}{field_name}.", )
Select an attribute from an abstract syntax tree (AST) node, using the attribute name. Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). name: the name of the attribute to select from current AST node. index: entry to get from a list field. ...
4.759504
4.759761
0.999946
stu_ast = state.student_ast stu_code = state.student_code # fallback on using complete student code if no ast ParseError = state.ast_dispatcher.ParseError def get_text(ast, code): if isinstance(ast, ParseError): return code try: return ast.get_text(code...
def has_code( state, text, incorrect_msg="Check the {ast_path}. The checker expected to find {text}.", fixed=False, )
Test whether the student code contains text. Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). text : text that student code must contain. Can be a regex pattern or a simple string. incorrect_msg: feedback message if text is not in student c...
4.94696
4.586663
1.078553
ast = state.ast_dispatcher.ast_mod sol_ast = state.solution_ast if sql is None else ast.parse(sql, start) # if sql is set, exact defaults to False. # if sql not set, exact defaults to True. if exact is None: exact = sql is None stu_rep = repr(state.student_ast) sol_rep = repr(...
def has_equal_ast( state, incorrect_msg="Check the {ast_path}. {extra}", sql=None, start=["expression", "subquery", "sql_script"][0], exact=None, )
Test whether the student and solution code have identical AST representations Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). incorrect_msg: feedback message if student and solution ASTs don't match sql : optional code to use instead of t...
4.576685
4.277159
1.070029
def decorator_fn(fn): return CacheModelDecorator().decorate(key_params, timeout, fn) return decorator_fn
def cache_model(key_params, timeout='default')
Caching decorator for app models in task.perform
5.748746
5.003399
1.148968
def decorator_fn(fn): d = CachePageDecorator() return d.decorate(key_params, timeout, fn) return decorator_fn
def cache_page(key_params, timeout='default')
Cache a page (slice) of a list of AppModels
5.476493
6.473128
0.846035
d = data.get_data() values = [] for k in key_params: if k in d and type(d[k]) is list: values.append("{0}:{1}".format(k, " -".join(d[k]))) else: value = d[k] if k in d else '' values.append("{0}:{1}".format(k, value)) return "{0}-{1}".format(pref...
def create_key_for_data(prefix, data, key_params)
From ``data`` params in task create corresponding key with help of ``key_params`` (defined in decorator)
2.619199
2.519348
1.039634
if isinstance(obj, set): return hash(frozenset(omnihash(e) for e in obj)) elif isinstance(obj, (tuple, list)): return hash(tuple(omnihash(e) for e in obj)) elif isinstance(obj, dict): return hash(frozenset((k, omnihash(v)) for k, v in obj.items())) else: return hash(...
def omnihash(obj)
recursively hash unhashable objects
1.603385
1.548572
1.035396
# short circuit common cases if len(jsonitems) == len(dbitems) == 0: # both are empty return False elif len(jsonitems) != len(dbitems): # if lengths differ, they're definitely different return True original_jsonitems = jsonitems jsonitems = copy.deepcopy(jsonit...
def items_differ(jsonitems, dbitems, subfield_dict)
check whether or not jsonitems and dbitems differ
3.845312
3.844099
1.000316
if not json_id: return None if json_id.startswith('~'): # keep caches of all the pseudo-ids to avoid doing 1000s of lookups during import if json_id not in self.pseudo_id_cache: spec = get_pseudo_id(json_id) spec = self.limit_...
def resolve_json_id(self, json_id, allow_no_match=False)
Given an id found in scraped JSON, return a DB id for the object. params: json_id: id from json allow_no_match: just return None if id can't be resolved returns: database id raises: ValueError if id couldn't be...
3.198522
3.213127
0.995455
def json_stream(): # load all json, mapped by json_id for fname in glob.glob(os.path.join(datadir, self._type + '_*.json')): with open(fname) as f: yield json.load(f) return self.import_data(json_stream())
def import_directory(self, datadir)
import a JSON directory into the database
5.030087
5.116976
0.983019
# hash(json): id seen_hashes = {} for data in dicts: json_id = data.pop('_id') # map duplicates (using omnihash to tell if json dicts are identical-ish) objhash = omnihash(data) if objhash not in seen_hashes: seen_hashes...
def _prepare_imports(self, dicts)
filters the import stream to remove duplicates also serves as a good place to override if anything special has to be done to the order of the import stream (see OrganizationImporter)
6.447805
6.502118
0.991647
# keep counts of all actions record = { 'insert': 0, 'update': 0, 'noop': 0, 'start': utcnow(), 'records': { 'insert': [], 'update': [], 'noop': [], } } for json_id, data in self._pr...
def import_data(self, data_items)
import a bunch of dicts together
6.000371
5.784564
1.037307
what = 'noop' # remove the JSON _id (may still be there if called directly) data.pop('_id', None) # add fields/etc. data = self.apply_transformers(data) data = self.prepare_for_db(data) try: obj = self.get_object(data) except self.m...
def import_item(self, data)
function used by import_data
4.11184
4.064003
1.011771
# keep track of whether or not anything was updated updated = False # for each related field - check if there are differences for field, items in related.items(): # skip subitem check if it's locked anyway if field in obj.locked_fields: c...
def _update_related(self, obj, related, subfield_dict)
update DB objects related to a base object obj: a base object to create related related: dict mapping field names to lists of related objects subfield_list: where to get the next layer of subfields
3.895861
3.850804
1.011701
for field, items in related.items(): subobjects = [] all_subrelated = [] Subtype, reverse_id_field, subsubdict = subfield_dict[field] for order, item in enumerate(items): # pull off 'subrelated' (things that are related to this obj) ...
def _create_related(self, obj, related, subfield_dict)
create DB objects related to a base object obj: a base object to create related related: dict mapping field names to lists of related objects subfield_list: where to get the next layer of subfields
4.092907
4.149696
0.986315
self.add_node(fro) self.add_node(to) self.edges[fro].add(to)
def add_edge(self, fro, to)
When doing topological sorting, the semantics of the edge mean that the depedency runs from the parent to the child - which is to say that the parent is required to be sorted *before* the child. [ FROM ] ------> [ TO ] Committee on Finance -> Subcommittee of the Finance Commit...
2.410799
3.084811
0.781506
# Now contains all nodes that contain dependencies. deps = {item for sublist in self.edges.values() for item in sublist} # contains all nodes *without* any dependencies (leaf nodes) return self.nodes - deps
def leaf_nodes(self)
Return an interable of nodes with no edges pointing at them. This is helpful to find all nodes without dependencies.
9.64055
8.402098
1.147398
if not remove_backrefs: for fro, connections in self.edges.items(): if node in self.edges[fro]: raise ValueError() # OK. Otherwise, let's do our removal. self.nodes.remove(node) if node in self.edges: # Remove add edg...
def prune_node(self, node, remove_backrefs=False)
remove node `node` from the network (including any edges that may have been pointing at `node`).
4.859291
4.573332
1.062527
while self.nodes: iterated = False for node in self.leaf_nodes(): iterated = True self.prune_node(node) yield node if not iterated: raise CyclicGraphError("Sorting has found a cyclic graph.")
def sort(self)
Return an iterable of nodes, toplogically sorted to correctly import dependencies before leaf nodes.
5.927319
5.114604
1.158901
buff = "digraph graphname {" for fro in self.edges: for to in self.edges[fro]: buff += "%s -> %s;" % (fro, to) buff += "}" return buff
def dot(self)
Return a buffer that represents something dot(1) can render.
3.932362
3.643872
1.079171
def walk_node(node, seen): if node in seen: yield (node,) return seen.add(node) for edge in self.edges[node]: for cycle in walk_node(edge, set(seen)): yield (node,) + cycle # F...
def cycles(self)
Fairly expensive cycle detection algorithm. This method will return the shortest unique cycles that were detected. Debug usage may look something like: print("The following cycles were found:") for cycle in network.cycles(): print(" ", " -> ".join(cycle))
4.608503
4.154338
1.109323
if organization and classification: raise ScrapeValueError('cannot specify both classification and organization') elif classification: return _make_pseudo_id(classification=classification) elif organization: if isinstance(organization, Organization): return organizat...
def pseudo_organization(organization, classification, default=None)
helper for setting an appropriate ID for organizations
3.166359
3.042513
1.040705
if isinstance(name_or_org, Organization): membership = Membership(person_id=self._id, person_name=self.name, organization_id=name_or_org._id, role=role, **kwargs) else: ...
def add_membership(self, name_or_org, role='member', **kwargs)
add a membership in an organization and return the membership object in case there are more details to add
2.36134
2.413859
0.978243
obj.pre_save(self.jurisdiction.jurisdiction_id) filename = '{0}_{1}.json'.format(obj._type, obj._id).replace('/', '-') self.info('save %s %s as %s', obj._type, obj, filename) self.debug(json.dumps(OrderedDict(sorted(obj.as_dict().items())), cls=ut...
def save_object(self, obj)
Save object to disk as JSON. Generally shouldn't be called directly.
4.170888
4.304869
0.968877
if schema is None: schema = self._schema type_checker = Draft3Validator.TYPE_CHECKER.redefine( "datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime)) ) ValidatorCls = jsonschema.validators.extend(Draft3Validator, type_checker=type_che...
def validate(self, schema=None)
Validate that we have a valid object. On error, this will raise a `ScrapeValueError` This also expects that the schemas assume that omitting required in the schema asserts the field is optional, not required. This is due to upstream schemas being in JSON Schema v3, and not validictory'...
3.263463
2.874504
1.135313
new = {'url': url, 'note': note} self.sources.append(new)
def add_source(self, url, *, note='')
Add a source URL from which data was collected
4.862455
4.203106
1.156872
import warnings # Test parameters while suppressing warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") # Will throw exception if anything is wrong: params.validate() from ._fwdpy11 import MutationRegions from ._fwdpy11 import evolve_without_tree_se...
def evolve_genomes(rng, pop, params, recorder=None)
Evolve a population without tree sequence recordings. In other words, complete genomes must be simulated and tracked. :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :class:`fwdpy11.DiploidPopulation` :param params: simulation paramete...
7.790896
6.353682
1.226202
# First, alive individuals: individal_nodes = {} for i in range(pop.N): individal_nodes[2*i] = i individal_nodes[2*i+1] = i metadata_strings = _generate_individual_metadata(pop.diploid_metadata, tc) # Now, preserved nodes num_ind_nodes = pop.N for i in pop.ancient_sampl...
def _initializeIndividualTable(pop, tc)
Returns node ID -> individual map
4.26531
4.255851
1.002223
node_view = np.array(pop.tables.nodes, copy=True) node_view['time'] -= node_view['time'].max() node_view['time'][np.where(node_view['time'] != 0.0)[0]] *= -1.0 edge_view = np.array(pop.tables.edges, copy=False) mut_view = np.array(pop.tables.mutations, copy=False) tc = tskit.TableCollectio...
def dump_tables_to_tskit(pop)
Converts fwdpy11.TableCollection to an tskit.TreeSequence
3.280653
3.208264
1.022563
import fwdpy11 if isinstance(pop, fwdpy11.DiploidPopulation) is False: raise ValueError("incorrect pop type: " + str(type(pop))) defaults = {'simlen': 10*pop.N, 'beg': 0.0, 'end': 1.0, 'theta': 100.0, 'pneutral': 1.0, ...
def mslike(pop, **kwargs)
Function to establish default parameters for a single-locus simulation for standard pop-gen modeling scenarios. :params pop: An instance of :class:`fwdpy11.DiploidPopulation` :params kwargs: Keyword arguments.
4.4354
3.782658
1.172561
if list(spec.keys()) == ['name']: # if we're just resolving on name, include other names return ((Q(name=spec['name']) | Q(other_names__name=spec['name'])) & Q(memberships__organization__jurisdiction_id=self.jurisdiction_id)) spec['memberships__organi...
def limit_spec(self, spec)
Whenever we do a Pseudo ID lookup from the database, we need to limit based on the memberships -> organization -> jurisdiction, so we scope the resolution.
5.635009
4.081728
1.380545
if self.nregions is None: raise TypeError("neutral regions cannot be None") if self.sregions is None: raise TypeError("selected regions cannot be None") if self.recregions is None: raise TypeError("recombination regions cannot be None") if sel...
def validate(self)
Error check model params. :raises TypeError: Throws TypeError if validation fails.
3.207646
3.139337
1.021759
# all pseudo parent ids we've seen pseudo_ids = set() # pseudo matches pseudo_matches = {} # get prepared imports from parent prepared = dict(super(OrganizationImporter, self)._prepare_imports(dicts)) # collect parent pseudo_ids for _, data in p...
def _prepare_imports(self, dicts)
an override for prepare imports that sorts the imports by parent_id dependencies
4.636312
4.479913
1.034911
import warnings # Currently, we do not support simulating neutral mutations # during tree sequence simulations, so we make sure that there # are no neutral regions/rates: if len(params.nregions) != 0: raise ValueError( "Simulation of neutral mutations on tree sequences not ...
def evolvets(rng, pop, params, simplification_interval, recorder=None, suppress_table_indexing=False, record_gvalue_matrix=False, stopping_criterion=None, track_mutation_counts=False, remove_extinct_variants=True)
Evolve a population with tree sequence recording :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :class:`fwdpy11.DiploidPopulation` :param params: simulation parameters :type params: :class:`fwdpy11.ModelParams` :param simplificatio...
6.770629
5.879358
1.151593
if time < 1: raise RuntimeError("time must be >= 1") if Nstart < 1 or Nstop < 1: raise RuntimeError("Nstart and Nstop must both be >= 1") G = math.exp((math.log(Nstop) - math.log(Nstart))/time) rv = [] for i in range(time): rv.append(round(Nstart*pow(G, i+1))) return...
def exponential_size_change(Nstart, Nstop, time)
Generate a list of population sizes according to exponential size_change model :param Nstart: population size at onset of size change :param Nstop: Population size to reach at end of size change :param time: Time (in generations) to get from Nstart to Nstop :return: A list of integers representing...
2.732241
2.716298
1.005869
bookends = ("\n", ";", "--", "/*", "*/") last_bookend_found = None start = 0 while start <= len(sql): results = get_next_occurence(sql, start, bookends) if results is None: yield (last_bookend_found, None, sql[start:]) start = len(sql) + 1 else: ...
def split_sql(sql)
generate hunks of SQL that are between the bookends return: tuple of beginning bookend, closing bookend, and contents note: beginning & end of string are returned as None
2.787393
2.526692
1.103179
# either work with sys.stdin or open the file if filename is not None: with open(filename, "r") as filelike: sql_string = filelike.read() else: with sys.stdin as filelike: sql_string = sys.stdin.read() success, msg = check_string(sql_string, add_semicolon=ad...
def check_file(filename=None, show_filename=False, add_semicolon=False)
Check whether an input file is valid PostgreSQL. If no filename is passed, STDIN is checked. Returns a status code: 0 if the input is valid, 1 if invalid.
3.663682
3.454054
1.06069
prepped_sql = sqlprep.prepare_sql(sql_string, add_semicolon=add_semicolon) success, msg = ecpg.check_syntax(prepped_sql) return success, msg
def check_string(sql_string, add_semicolon=False)
Check whether a string is valid PostgreSQL. Returns a boolean indicating validity and a message from ecpg, which will be an empty string if the input was valid, or a description of the problem otherwise.
5.488686
3.673287
1.494216
args = ["ecpg", "-o", "-", "-"] with open(os.devnull, "w") as devnull: try: proc = subprocess.Popen(args, shell=False, stdout=devnull, stdin=subprocess.PIPE, stderr=subprocess.PI...
def check_syntax(string)
Check syntax of a string of PostgreSQL-dialect SQL
3.33499
3.316334
1.005625
vcenter_vm_name = context.resource.attributes['vCenter VM'] vcenter_vm_name = vcenter_vm_name.replace('\\', '/') vcenter_name = context.resource.attributes['vCenter Name'] self.logger.info('start autoloading vm_path: {0} on vcenter: {1}'.format(vcenter_vm_name, vcenter_name)) ...
def get_inventory(self, context)
Will locate vm in vcenter and fill its uuid :type context: cloudshell.shell.core.context.ResourceCommandContext
3.411855
3.114164
1.095592
vm = self.pyvmomi_service.find_by_uuid(si, vm_uuid) logger.info("Get snapshots") snapshots = SnapshotRetriever.get_vm_snapshots(vm) return snapshots.keys()
def get_snapshots(self, si, logger, vm_uuid)
Restores a virtual machine to a snapshot :param vim.ServiceInstance si: py_vmomi service instance :param logger: Logger :param vm_uuid: uuid of the virtual machine
5.175375
5.819903
0.889254
'# Disabling urllib3 ssl warnings' requests.packages.urllib3.disable_warnings() '# Disabling SSL certificate verification' context = None import ssl if hasattr(ssl, 'SSLContext'): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.veri...
def connect(self, address, user, password, port=443)
Connect to vCenter via SSL and return SI object :param address: vCenter address (host / ip address) :param user: user name for authentication :param password:password for authentication :param port: port for the SSL connection. Default = 443
2.249254
2.166586
1.038156
return self.find_obj_by_path(si, path, name, self.Datacenter)
def find_datacenter_by_name(self, si, path, name)
Finds datacenter in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') :param name: the datacenter name to return
4.530794
5.976177
0.758143
if uuid is None: return None if path is not None: data_center = self.find_item_in_path_by_type(si, path, vim.Datacenter) search_index = si.content.searchIndex return search_index.FindByUuid(data_center, uuid, is_vm)
def find_by_uuid(self, si, uuid, is_vm=True, path=None, data_center=None)
Finds vm/host by his uuid in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param uuid: the object uuid :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') :param is_vm: if true, search for virtual mach...
3.19887
3.452353
0.926577
if obj_type is None: return None search_index = si.content.searchIndex sub_folder = si.content.rootFolder if path is None or not path: return sub_folder paths = path.split("/") for currPath in paths: if currPath is None or n...
def find_item_in_path_by_type(self, si, path, obj_type)
This function finds the first item of that type in path :param ServiceInstance si: pyvmomi ServiceInstance :param str path: the path to search in :param type obj_type: the vim type of the object :return: pyvmomi type instance object or None
4.246615
3.732761
1.137661
return self.find_obj_by_path(si, path, name, self.Host)
def find_host_by_name(self, si, path, name)
Finds datastore in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') :param name: the datastore name to return
5.269269
8.877848
0.59353
return self.find_obj_by_path(si, path, name, self.Datastore)
def find_datastore_by_name(self, si, path, name)
Finds datastore in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') :param name: the datastore name to return
5.105318
7.021624
0.727085
dv_switch = self.get_folder(si, dv_switch_path) if dv_switch and dv_switch.portgroup: for port in dv_switch.portgroup: if port.name == name: return port return None
def find_portgroup(self, si, dv_switch_path, name)
Returns the portgroup on the dvSwitch :param name: str :param dv_switch_path: str :param si: service instance
2.647581
3.044873
0.869521
return self.find_obj_by_path(si, path, name, self.Network)
def find_network_by_name(self, si, path, name)
Finds network in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') :param name: the datastore name to return
5.302454
7.625651
0.695344
return self.find_obj_by_path(si, path, name, self.VM)
def find_vm_by_name(self, si, path, name)
Finds vm in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') :param name: the vm name to return
4.648151
6.876022
0.675994
folder = self.get_folder(si, path) if folder is None: raise ValueError('vmomi managed object not found at: {0}'.format(path)) look_in = None if hasattr(folder, type_name): look_in = getattr(folder, type_name) if hasattr(folder, self.ChildEntity)...
def find_obj_by_path(self, si, path, name, type_name)
Finds object in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') :param name: the object name to return :param type_name: the name of the type, can be (vm,...
4.168643
4.106809
1.015057
dvs = self.get_folder(si, path) if not dvs: raise ValueError('Could not find Default DvSwitch in path {0}'.format(path)) elif not isinstance(dvs, vim.dvs.VmwareDistributedVirtualSwitch): raise ValueError('The object in path {0} is {1} and not a DvSwitch'.format(...
def find_dvs_by_path(self,si ,path)
Finds vm in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
4.051916
3.492912
1.16004
search_index = si.content.searchIndex sub_folder = root if root else si.content.rootFolder if not path: return sub_folder paths = [p for p in path.split("/") if p] child = None try: new_root = search_index.FindChild(sub_folder, paths[0...
def get_folder(self, si, path, root=None)
Finds folder in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
1.466571
1.435619
1.02156
path, name = get_path_and_name(default_network_full_name) return self.find_network_by_name(si, path, name) if name else None
def get_network_by_full_name(self, si, default_network_full_name)
Find network by a Full Name :param default_network_full_name: <str> Full Network Name - likes 'Root/Folder/Network' :return:
4.2374
4.534725
0.934434
obj = None container = self._get_all_objects_by_type(content, vimtype) # If no name was given will return the first object from list of a objects matching the given vimtype type for c in container.view: if name: if c.name == name: ...
def get_obj(self, content, vimtype, name)
Return an object by name for a specific type, if name is None the first found object is returned :param content: pyvmomi content object :param vimtype: the type of object too search :param name: the object name to return
5.328561
5.831728
0.913719
result = self.CloneVmResult() if not isinstance(clone_params.si, self.vim.ServiceInstance): result.error = 'si must be init as ServiceInstance' return result if clone_params.template_name is None: result.error = 'template_name param cannot be None' ...
def clone_vm(self, clone_params, logger, cancellation_context)
Clone a VM from a template/VM and return the vm oject or throws argument is not valid :param cancellation_context: :param clone_params: CloneVmParameters = :param logger:
3.42848
3.385424
1.012718
self.power_off_before_destroy(logger, vm) logger.info(("Destroying VM {0}".format(vm.name))) task = vm.Destroy_Task() return self.task_waiter.wait_for_task(task=task, logger=logger, action_name="Destroy VM")
def destroy_vm(self, vm, logger)
destroy the given vm :param vm: virutal machine pyvmomi object :param logger:
4.116158
4.285222
0.960547
if vm_name is not None: vm = self.find_vm_by_name(si, vm_path, vm_name) if vm: return self.destroy_vm(vm, logger) raise ValueError('vm not found')
def destroy_vm_by_name(self, si, vm_name, vm_path, logger)
destroy the given vm :param si: pyvmomi 'ServiceInstance' :param vm_name: str name of the vm to destroyed :param vm_path: str path to the vm that will be destroyed :param logger:
2.972086
3.360007
0.884548
if vm_uuid is not None: vm = self.find_by_uuid(si, vm_uuid, vm_path) if vm: return self.destroy_vm(vm, logger) # return 'vm not found' # for apply the same Interface as for 'destroy_vm_by_name' raise ValueError('vm not found')
def destroy_vm_by_uuid(self, si, vm_uuid, vm_path, logger)
destroy the given vm :param si: pyvmomi 'ServiceInstance' :param vm_uuid: str uuid of the vm to destroyed :param vm_path: str path to the vm that will be destroyed :param logger:
5.319625
5.956815
0.893032
config_spec = vim.vm.ConfigSpec(deviceChange=device_change) task = vm.ReconfigVM_Task(config_spec) return task
def vm_reconfig_task(vm, device_change)
Create Task for VM re-configure :param vm: <vim.vm obj> VM which will be re-configure :param device_change: :return: Task
2.250528
2.742584
0.820587
# return None for network in vm.network: if hasattr(network, "name") and network_name == network.name: return network return None
def vm_get_network_by_name(vm, network_name)
Try to find Network scanning all attached to VM networks :param vm: <vim.vm> :param network_name: <str> name of network :return: <vim.vm.Network or None>
3.528057
3.933358
0.896958
folder_name = None folder = vm.parent if folder: folder_name = folder.name folder_parent = folder.parent while folder_parent and folder_parent.name and folder_parent != si.content.rootFolder and not isinstance(folder_parent, vim.Datacenter): ...
def get_vm_full_path(self, si, vm)
:param vm: vim.VirtualMachine :return:
4.401843
4.361055
1.009353
path = VMLocation.combine([vcenter_data_model.default_datacenter, vm_name]) paths = path.split('/') name = paths[len(paths) - 1] path = VMLocation.combine(paths[:len(paths) - 1]) vm = self.pv_service.find_vm_by_name(si, path, name) if not vm: raise Va...
def load_vm_uuid_by_name(self, si, vcenter_data_model, vm_name)
Returns the vm uuid :param si: Service instance to the vcenter :param vcenter_data_model: vcenter data model :param vm_name: the vm name :return: str uuid
3.085911
3.104386
0.994049
logger.info('retrieving vm by uuid: {0}'.format(vm_uuid)) vm = self.pv_service.find_by_uuid(si, vm_uuid) if vm.summary.runtime.powerState == 'poweredOff': logger.info('vm already powered off') task_result = 'Already powered off' else: # hard...
def power_off(self, si, logger, session, vcenter_data_model, vm_uuid, resource_fullname)
Power off of a vm :param vcenter_data_model: vcenter model :param si: Service Instance :param logger: :param session: :param vcenter_data_model: vcenter_data_model :param vm_uuid: the uuid of the vm :param resource_fullname: the full name of the deployed app resou...
2.782609
2.874555
0.968014
logger.info('retrieving vm by uuid: {0}'.format(vm_uuid)) vm = self.pv_service.find_by_uuid(si, vm_uuid) if vm.summary.runtime.powerState == 'poweredOn': logger.info('vm already powered on') task_result = 'Already powered on' else: logger.inf...
def power_on(self, si, logger, session, vm_uuid, resource_fullname)
power on the specified vm :param si: :param logger: :param session: :param vm_uuid: the uuid of the vm :param resource_fullname: the full name of the deployed app resource :return:
2.786943
2.82067
0.988043
if self._is_instance_of(context, 'AutoLoadCommandContext'): reservation_id = 'Autoload' handler_name = context.resource.name elif self._is_instance_of(context, 'UnreservedResourceCommandContext'): reservation_id = 'DeleteArtifacts' handler_name =...
def create_logger_for_context(self, logger_name, context)
Create QS Logger for command context AutoLoadCommandContext or ResourceCommandContext :param logger_name: :type logger_name: str :param context: :return:
4.20912
3.440533
1.223392
vm = self.pv_service.find_by_uuid(si, vm_uuid) if not vm: raise ValueError('VM having UUID {0} not found'.format(vm_uuid)) default_network_instance = self.pv_service.get_network_by_full_name(si, default_network_name) if not default_network_instance: ra...
def connect_to_networks(self, si, logger, vm_uuid, vm_network_mappings, default_network_name, reserved_networks, dv_switch_name, promiscuous_mode)
Connect VM to Network :param si: VmWare Service Instance - defined connection to vCenter :param logger: :param vm_uuid: <str> UUID for VM :param vm_network_mappings: <collection of 'VmNetworkMapping'> :param default_network_name: <str> Full Network name - likes 'DataCenterName/Ne...
2.821747
2.766048
1.020137
mapping = dict() reserved_networks = reserved_networks if reserved_networks else [] vnics_to_network_mapping = self._map_vnic_to_network(vnics, existing_network, default_network, reserved_networks) for request in requests: if request.vnic_name: if re...
def map_request_to_vnics(self, requests, vnics, existing_network, default_network, reserved_networks)
gets the requests for connecting netwoks and maps it the suitable vnic of specific is not specified :param reserved_networks: array of reserved networks :param requests: :param vnics: :param existing_network: :param default_network: :return:
2.352476
2.4142
0.974433
ovf_tool_exe_path = vcenter_data_model.ovf_tool_path self._validate_url_exists(ovf_tool_exe_path, 'OVF Tool', logger) args = self._get_args(ovf_tool_exe_path, image_params, logger) logger.debug('opening ovf tool process with the params: {0}'.format(','.join(args))) pro...
def deploy_image(self, vcenter_data_model, image_params, logger)
Receives ovf image parameters and deploy it on the designated vcenter :param VMwarevCenterResourceModel vcenter_data_model: :type image_params: vCenterShell.vm.ovf_image_params.OvfImageParams :param logger:
3.371454
3.397938
0.992206
# create vm name vm_name_param = VM_NAME_PARAM.format(image_params.vm_name) # datastore name datastore_param = DATA_STORE_PARAM.format(image_params.datastore) # power state # power_state = POWER_ON_PARAM if image_params.power_on else POWER_OFF_PARAM # d...
def _get_args(self, ovf_tool_exe_path, image_params, logger)
:type image_params: vCenterShell.vm.ovf_image_params.OvfImageParams
3.788384
3.708192
1.021626
logger = self.context_based_logger_factory.create_logger_for_context( logger_name='vCenterShell', context=context) if not command: logger.error(COMMAND_CANNOT_BE_NONE) raise Exception(COMMAND_CANNOT_BE_NONE) try: command_nam...
def execute_command_with_connection(self, context, command, *args)
Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command :param command: :param context: instance of ResourceCommandContext or AutoLoadCommandContext :type context: cloudshell.shell.core.context.ResourceCommandContext :param args:
2.616165
2.501716
1.045748
if self.connection_details is None and req_connection_details is None: return False if self.connection_details is None or req_connection_details is None: return True return not all([self.connection_details.host == req_connection_details.host, ...
def has_connection_details_changed(self, req_connection_details)
:param cloudshell.cp.vcenter.models.VCenterConnectionDetails.VCenterConnectionDetails req_connection_details: :return:
1.592907
1.502325
1.060294
vm = self.pyvmomi_service.find_by_uuid(si, vm_uuid) logger.info("Revert snapshot") snapshot = SnapshotRestoreCommand._get_snapshot(vm=vm, snapshot_name=snapshot_name) session.SetResourceLiveStatus(resource_fullname, "Offline", "Powered Off") task = snapshot.RevertToSna...
def restore_snapshot(self, si, logger, session, vm_uuid, resource_fullname, snapshot_name)
Restores a virtual machine to a snapshot :param vim.ServiceInstance si: py_vmomi service instance :param logger: Logger :param session: CloudShellAPISession :type session: cloudshell_api.CloudShellAPISession :param vm_uuid: uuid of the virtual machine :param resource_full...
4.885627
4.989543
0.979173
snapshots = SnapshotRetriever.get_vm_snapshots(vm) if snapshot_name not in snapshots: raise SnapshotNotFoundException('Snapshot {0} was not found'.format(snapshot_name)) return snapshots[snapshot_name]
def _get_snapshot(vm, snapshot_name)
Returns snapshot object by its name :param vm: :param snapshot_name: :type snapshot_name: str :return: Snapshot by its name :rtype vim.vm.Snapshot
4.137896
4.485917
0.922419
results = [] logger.info('Save Sandbox command starting on ' + vcenter_data_model.default_datacenter) if not save_app_actions: raise Exception('Failed to save app, missing data in request.') actions_grouped_by_save_types = groupby(save_app_actions, lambda x: x.act...
def save_app(self, si, logger, vcenter_data_model, reservation_id, save_app_actions, cancellation_context)
Cretaes an artifact of an app, that can later be restored :param vcenter_data_model: VMwarevCenterResourceModel :param vim.ServiceInstance si: py_vmomi service instance :type si: vim.ServiceInstance :param logger: Logger :type logger: cloudshell.core.logger.qs_logger.get_qs_logg...
8.212232
7.892837
1.040466
''' To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary. ''' return household('rent', period) * parameters(period).benefits.housing_allowance
def formula_1980(household, period, parameters)
To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary.
22.235165
3.833549
5.800152
''' A person's pension depends on their birth date. In French: retraite selon l'âge. In Arabic: تقاعد. ''' age_condition = person('age', period) >= parameters(period).general.age_of_retirement return age_condition
def formula(person, period, parameters)
A person's pension depends on their birth date. In French: retraite selon l'âge. In Arabic: تقاعد.
16.867531
4.472158
3.771676
# we do not need to serialize an empty response from the vCenter if result is None: return if isinstance(result, basestring): return result json = jsonpickle.encode(result, unpicklable=unpicklable) result_for_output = str(json) return result_for_output
def set_command_result(result, unpicklable=False)
Serializes output as JSON and writes it to console output wrapped with special prefix and suffix :param result: Result to return :param unpicklable: If True adds JSON can be deserialized as real object. When False will be deserialized as dictionary
5.116815
5.734883
0.892227
logger = self._get_logger(context) logger.info('Autodiscovery started') si = None resource = None with CloudShellSessionContext(context) as cloudshell_session: self._check_if_attribute_not_empty(context.resource, ADDRESS) resource = context.resou...
def validate_and_discover(self, context)
:type context: models.QualiDriverModels.AutoLoadCommandContext
4.748114
4.503559
1.054303
attributes_with_slash = dict() for key, value in attributes_with_slash_or_backslash.items(): if key in ATTRIBUTE_NAMES_THAT_ARE_SLASH_BACKSLASH_AGNOSTIC: value = back_slash_to_front_converter(value) attributes_with_slash[key] = value return attri...
def _make_attributes_slash_backslash_agnostic(attributes_with_slash_or_backslash)
:param attributes_with_slash_or_backslash: resource attributes from cloudshell.cp.vcenter.models.QualiDriverModels.ResourceContextDetails :type attributes_with_slash_or_backslash: dict[str,str] :return: attributes_with_slash :rtype attributes_with_slash: dict[str,str]
3.134044
2.858171
1.096521
connection = self.command_wrapper.execute_command_with_connection(context, self.save_app_command.save_app, save_actions, cancellation_context, ) save_app_results = connection return save_app_results
def save_sandbox(self, context, save_actions, cancellation_context)
Save sandbox command, persists an artifact of existing VMs, from which new vms can be restored :param ResourceCommandContext context: :param list[SaveApp] save_actions: :param CancellationContext cancellation_context: :return: list[SaveAppResult] save_app_results
7.797465
5.840424
1.335086
connection = self.command_wrapper.execute_command_with_connection(context, self.delete_saved_sandbox_command.delete_sandbox, delete_saved_apps, cancellatio...
def delete_saved_sandbox(self, context, delete_saved_apps, cancellation_context)
Delete a saved sandbox, along with any vms associated with it :param ResourceCommandContext context: :param list[DeleteSavedApp] delete_saved_apps: :param CancellationContext cancellation_context: :return: list[SaveAppResult] save_app_results
5.36236
5.038461
1.064285
deploy_from_template_model = self.resource_model_parser.convert_to_resource_model( attributes=deploy_action.actionParams.deployment.attributes, resource_model_type=vCenterVMFromTemplateResourceModel) data_holder = DeployFromTemplateDetails(deploy_from_template_model, dep...
def deploy_from_template(self, context, deploy_action, cancellation_context)
Deploy From Template Command, will deploy vm from template :param CancellationContext cancellation_context: :param ResourceCommandContext context: the context of the command :param DeployApp deploy_action: :return DeployAppResult deploy results
4.964646
4.794223
1.035548
deploy_from_vm_model = self.resource_model_parser.convert_to_resource_model( attributes=deploy_action.actionParams.deployment.attributes, resource_model_type=vCenterCloneVMFromVMResourceModel) data_holder = DeployFromTemplateDetails(deploy_from_vm_model, deploy_action.ac...
def deploy_clone_from_vm(self, context, deploy_action, cancellation_context)
Deploy Cloned VM From VM Command, will deploy vm from template :param CancellationContext cancellation_context: :param ResourceCommandContext context: the context of the command :param DeployApp deploy_action: :return DeployAppResult deploy results
5.04988
4.981844
1.013657
linked_clone_from_vm_model = self.resource_model_parser.convert_to_resource_model( attributes=deploy_action.actionParams.deployment.attributes, resource_model_type=VCenterDeployVMFromLinkedCloneResourceModel) data_holder = DeployFromTemplateDetails(linked_clone_from_vm_m...
def deploy_from_linked_clone(self, context, deploy_action, cancellation_context)
Deploy Cloned VM From VM Command, will deploy vm from template :param CancellationContext cancellation_context: :param ResourceCommandContext context: the context of the command :param DeployApp deploy_action: :return DeployAppResult deploy results
5.167756
5.08485
1.016305
deploy_action.actionParams.deployment.attributes['vCenter Name'] = context.resource.name deploy_from_image_model = self.resource_model_parser.convert_to_resource_model( attributes=deploy_action.actionParams.deployment.attributes, resource_model_type=vCenterVMFromImageRes...
def deploy_from_image(self, context, deploy_action, cancellation_context)
Deploy From Image Command, will deploy vm from ovf image :param CancellationContext cancellation_context: :param ResourceCommandContext context: the context of the command :param DeployApp deploy_action: :return str deploy results
4.915868
4.781559
1.028089
resource_details = self._parse_remote_model(context) # execute command res = self.command_wrapper.execute_command_with_connection( context, self.virtual_switch_disconnect_command.disconnect_all, resource_details.vm_uuid) return set_command_re...
def disconnect_all(self, context, ports)
Disconnect All Command, will the assign all the vnics on the vm to the default network, which is sign to be disconnected :param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on :param list[string] ports: the ports of the connection between the remot...
11.563906
8.82361
1.310564
resource_details = self._parse_remote_model(context) # execute command res = self.command_wrapper.execute_command_with_connection( context, self.destroy_virtual_machine_command.DeleteInstance, resource_details.vm_uuid, resource_details.ful...
def DeleteInstance(self, context, ports)
Destroy Vm Command, will only destroy the vm and will not remove the resource :param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on :param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
11.008785
8.728592
1.261233
resource_details = self._parse_remote_model(context) # execute command res = self.command_wrapper.execute_command_with_connection(context, self.refresh_ip_command.refresh_ip, ...
def refresh_ip(self, context, cancellation_context, ports)
Refresh IP Command, will refresh the ip of the vm and will update it on the resource :param ResourceRemoteCommandContext context: the context the command runs on :param cancellation_context: :param list[string] ports: the ports of the connection between the remote resource and the local resource...
10.748973
8.283721
1.297602
return self._power_command(context, ports, self.vm_power_management_command.power_off)
def power_off(self, context, ports)
Powers off the remote vm :param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on :param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
8.16961
8.985065
0.909243
return self._power_command(context, ports, self.vm_power_management_command.power_on)
def power_on(self, context, ports)
Powers on the remote vm :param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on :param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
8.746196
9.59272
0.911753
self.power_off(context, ports) time.sleep(float(delay)) return self.power_on(context, ports)
def power_cycle(self, context, ports, delay)
preforms a restart to the vm :param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on :param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! :param number delay: the time to wait betwee...
2.802028
3.869286
0.724172
if not context.remote_endpoints: raise Exception('no remote resources found in context: {0}', jsonpickle.encode(context, unpicklable=False)) resource = context.remote_endpoints[0] dictionary = jsonpickle.decode(resource.app_context.deployed_app_json) holder = Deploy...
def _parse_remote_model(self, context)
parse the remote resource model and adds its full name :type context: models.QualiDriverModels.ResourceRemoteCommandContext
6.174473
5.45878
1.131109
resource_details = self._parse_remote_model(context) created_snapshot_path = self.command_wrapper.execute_command_with_connection(context, self.snapshot_saver.save_snapshot, ...
def save_snapshot(self, context, snapshot_name, save_memory='No')
Saves virtual machine to a snapshot :param context: resource context of the vCenterShell :type context: models.QualiDriverModels.ResourceCommandContext :param snapshot_name: snapshot name to save to :type snapshot_name: str :param save_memory: Snapshot the virtual machine's memor...
6.484513
6.149537
1.054472
resource_details = self._parse_remote_model(context) self.command_wrapper.execute_command_with_connection(context, self.snapshot_restorer.restore_snapshot, resource_details....
def restore_snapshot(self, context, snapshot_name)
Restores virtual machine from a snapshot :param context: resource context of the vCenterShell :type context: models.QualiDriverModels.ResourceCommandContext :param snapshot_name: snapshot name to save to :type snapshot_name: str :return:
8.211261
7.418107
1.106921