input
stringlengths
11
7.65k
target
stringlengths
22
8.26k
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def encode(self): if self.version == 6: return {'ip6': self.ip_addr} else: return {'ip4': self.ip_addr}
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def version(self): return self.ip_addr.version
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def address(self): return self.addr
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def length(self): return self.ip_addr.max_prefixlen
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def bytes(self): return self.ip_addr.packed
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __eq__(self, other): if isinstance(other, self.__class__): return self.ip_addr == other.ip_addr elif hasattr(other, "ip4") and hasattr(other, "ip6"): # vl_api_address_union_t if 4 == self.version: return self.ip_addr == other.ip4 else: return self.ip_addr == other.ip6 else: raise Exception("Comparing VppIpAddressUnions:%s" " with incomparable type: %s", self, other)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __ne__(self, other): return not (self == other)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __str__(self): return str(self.ip_addr)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self, saddr, gaddr, glen): self.saddr = saddr self.gaddr = gaddr self.glen = glen if ip_address(self.saddr).version != \ ip_address(self.gaddr).version: raise ValueError('Source and group addresses must be of the ' 'same address family.')
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def encode(self): return { 'af': ip_address(self.gaddr).vapi_af, 'grp_address': { ip_address(self.gaddr).vapi_af_name: self.gaddr }, 'src_address': { ip_address(self.saddr).vapi_af_name: self.saddr }, 'grp_address_length': self.glen, }
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def length(self): return self.glen
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def version(self): return ip_address(self.gaddr).version
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __str__(self): return "(%s,%s)/%d" % (self.saddr, self.gaddr, self.glen)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __eq__(self, other): if isinstance(other, self.__class__): return (self.glen == other.glen and self.saddr == other.gaddr and self.saddr == other.saddr) elif (hasattr(other, "grp_address_length") and hasattr(other, "grp_address") and hasattr(other, "src_address")): # vl_api_mprefix_t if 4 == self.version: return (self.glen == other.grp_address_length and self.gaddr == str(other.grp_address.ip4) and self.saddr == str(other.src_address.ip4)) else: return (self.glen == other.grp_address_length and self.gaddr == str(other.grp_address.ip6) and self.saddr == str(other.src_address.ip6)) return NotImplemented
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self, test, policer_index, is_ip6=False): self._test = test self._policer_index = policer_index self._is_ip6 = is_ip6
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def add_vpp_config(self): self._test.vapi.ip_punt_police(policer_index=self._policer_index, is_ip6=self._is_ip6, is_add=True)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def remove_vpp_config(self): self._test.vapi.ip_punt_police(policer_index=self._policer_index, is_ip6=self._is_ip6, is_add=False)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self, test, rx_index, tx_index, nh_addr): self._test = test self._rx_index = rx_index self._tx_index = tx_index self._nh_addr = ip_address(nh_addr)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def encode(self): return {"rx_sw_if_index": self._rx_index, "tx_sw_if_index": self._tx_index, "nh": self._nh_addr}
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def add_vpp_config(self): self._test.vapi.ip_punt_redirect(punt=self.encode(), is_add=True) self._test.registry.register(self, self._test.logger)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def remove_vpp_config(self): self._test.vapi.ip_punt_redirect(punt=self.encode(), is_add=False)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_vpp_config(self): is_ipv6 = True if self._nh_addr.version == 6 else False return self._test.vapi.ip_punt_redirect_dump( sw_if_index=self._rx_index, is_ipv6=is_ipv6)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def query_vpp_config(self): if self.get_vpp_config(): return True return False
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self, test, nh, pmtu, table_id=0): self._test = test self.nh = nh self.pmtu = pmtu self.table_id = table_id
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def add_vpp_config(self): self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, 'table_id': self.table_id, 'path_mtu': self.pmtu}) self._test.registry.register(self, self._test.logger) return self
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def modify(self, pmtu): self.pmtu = pmtu self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, 'table_id': self.table_id, 'path_mtu': self.pmtu}) return self
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def remove_vpp_config(self): self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, 'table_id': self.table_id, 'path_mtu': 0})
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def query_vpp_config(self): ds = list(self._test.vapi.vpp.details_iter( self._test.vapi.ip_path_mtu_get)) for d in ds: if self.nh == str(d.pmtu.nh) \ and self.table_id == d.pmtu.table_id \ and self.pmtu == d.pmtu.path_mtu: return True return False
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def object_id(self): return ("ip-path-mtu-%d-%s-%d" % (self.table_id, self.nh, self.pmtu))
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def gaussian(data, mean, covariance): """! @brief Calculates gaussian for dataset using specified mean (mathematical expectation) and variance or covariance in case multi-dimensional data.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self, sample, amount): """! @brief Constructs EM initializer.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def initialize(self, init_type = ema_init_type.KMEANS_INITIALIZATION): """! @brief Calculates initial parameters for EM algorithm: means and covariances using specified strategy.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __calculate_initial_clusters(self, centers): """! @brief Calculate Euclidean distance to each point from the each cluster. @brief Nearest points are captured by according clusters and as a result clusters are updated.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __calculate_initial_covariances(self, initial_clusters): covariances = [] for initial_cluster in initial_clusters: if len(initial_cluster) > 1: cluster_sample = [self.__sample[index_point] for index_point in initial_cluster] covariances.append(numpy.cov(cluster_sample, rowvar=False)) else: dimension = len(self.__sample[0]) covariances.append(numpy.zeros((dimension, dimension)) + random.random() / 10.0)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __initialize_random(self): initial_means = []
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __initialize_kmeans(self): initial_centers = kmeans_plusplus_initializer(self.__sample, self.__amount).initialize() kmeans_instance = kmeans(self.__sample, initial_centers, ccore = True) kmeans_instance.process()
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self): """! @brief Initializes EM observer.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_iterations(self): """! @return (uint) Amount of iterations that were done by the EM algorithm.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_evolution_means(self): """! @return (list) Mean of each cluster on each step of clustering.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_evolution_covariances(self): """! @return (list) Covariance matrix (or variance in case of one-dimensional data) of each cluster on each step of clustering.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_evolution_clusters(self): """! @return (list) Allocated clusters on each step of clustering.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def notify(self, means, covariances, clusters): """! @brief This method is used by the algorithm to notify observer about changes where the algorithm should provide new values: means, covariances and allocated clusters.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def show_clusters(clusters, sample, covariances, means, figure=None, display=True): """! @brief Draws clusters and in case of two-dimensional dataset draws their ellipses. @details Allocated figure by this method should be closed using `close()` method of this visualizer.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def close(figure): """! @brief Closes figure object that was used or allocated by the visualizer.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def animate_cluster_allocation(data, observer, animation_velocity = 75, movie_fps = 1, save_movie = None): """! @brief Animates clustering process that is performed by EM algorithm.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def init_frame(): return frame_generation(0)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def frame_generation(index_iteration): figure.clf()
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __draw_ellipses(figure, visualizer, clusters, covariances, means): ax = figure.get_axes()[0]
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __draw_ellipse(ax, x, y, angle, width, height, color): if (width > 0.0) and (height > 0.0): ax.plot(x, y, color=color, marker='x', markersize=6) ellipse = patches.Ellipse((x, y), width, height, alpha=0.2, angle=-angle, linewidth=2, fill=True, zorder=2, color=color) ax.add_patch(ellipse)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self, data, amount_clusters, means=None, variances=None, observer=None, tolerance=0.00001, iterations=100): """! @brief Initializes Expectation-Maximization algorithm for cluster analysis.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def process(self): """! @brief Run clustering process of the algorithm.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_clusters(self): """! @return (list) Allocated clusters where each cluster is represented by list of indexes of points from dataset, for example, two cluster may have following representation [[0, 1, 4], [2, 3, 5, 6]].
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_centers(self): """! @return (list) Corresponding centers (means) of clusters.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_covariances(self): """! @return (list) Corresponding variances (or covariances in case of multi-dimensional data) of clusters.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_probabilities(self): """! @brief Returns 2-dimensional list with belong probability of each object from data to cluster correspondingly, where that first index is for cluster and the second is for point.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __erase_empty_clusters(self): clusters, means, variances, pic, gaussians, rc = [], [], [], [], [], []
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __notify(self): if self.__observer is not None: self.__observer.notify(self.__means, self.__variances, self.__clusters)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __extract_clusters(self): self.__clusters = [[] for _ in range(self.__amount_clusters)] for index_point in range(len(self.__data)): candidates = [] for index_cluster in range(self.__amount_clusters): candidates.append((index_cluster, self.__rc[index_cluster][index_point]))
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __log_likelihood(self): likelihood = 0.0
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __probabilities(self, index_cluster, index_point): divider = 0.0 for i in range(self.__amount_clusters): divider += self.__pic[i] * self.__gaussians[i][index_point]
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __expectation_step(self): self.__gaussians = [ [] for _ in range(self.__amount_clusters) ] for index in range(self.__amount_clusters): self.__gaussians[index] = gaussian(self.__data, self.__means[index], self.__variances[index])
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __maximization_step(self): self.__pic = [] self.__means = [] self.__variances = []
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __get_stop_condition(self): for covariance in self.__variances: if numpy.linalg.norm(covariance) == 0.0: return True
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __update_covariance(self, means, rc, mc): covariance = 0.0 for index_point in range(len(self.__data)): deviation = numpy.array([self.__data[index_point] - means]) covariance += rc[index_point] * deviation.T.dot(deviation)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __update_mean(self, rc, mc): mean = 0.0 for index_point in range(len(self.__data)): mean += rc[index_point] * self.__data[index_point]
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __normalize_probabilities(self): for index_point in range(len(self.__data)): probability = 0.0 for index_cluster in range(len(self.__clusters)): probability += self.__rc[index_cluster][index_point]
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __normalize_probability(self, index_point, probability): if probability == 0.0: return
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __verify_arguments(self): """! @brief Verify input parameters for the algorithm and throw exception in case of incorrectness.
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __enter__(self): """ Syntax sugar which helps in celery tasks, cron jobs, and other scripts Usage: with Tenant.objects.get(schema_name='test') as tenant: # run some code in tenant test # run some code in previous tenant (public probably) """ connection = connections[get_tenant_database_alias()] self._previous_tenant.append(connection.tenant) self.activate() return self
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
async def handler(client, request): if request.path == "/v6/challenge": assert request.encode().decode() == CHALLENGE_REQUEST response = http.HTTPResponse(200) response.json = { "challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=", "data": "dlL7ZBNSLmYo1hUlKYZiUA==" } return response else: assert request.encode().decode() == TOKEN_REQUEST response = http.HTTPResponse(200) response.json = { "device_auth_token": "device token" } return response
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __exit__(self, exc_type, exc_val, exc_tb): connection = connections[get_tenant_database_alias()] connection.set_tenant(self._previous_tenant.pop())
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def activate(self): """ Syntax sugar that helps at django shell with fast tenant changing Usage: Tenant.objects.get(schema_name='test').activate() """ connection = connections[get_tenant_database_alias()] connection.set_tenant(self)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def deactivate(cls): """ Syntax sugar, return to public schema Usage: test_tenant.deactivate() # or simpler Tenant.deactivate() """ connection = connections[get_tenant_database_alias()] connection.set_schema_to_public()
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def save(self, verbosity=1, *args, **kwargs): connection = connections[get_tenant_database_alias()] is_new = self.pk is None has_schema = hasattr(connection, 'schema_name') if has_schema and is_new and connection.schema_name != get_public_schema_name(): raise Exception("Can't create tenant outside the public schema. " "Current schema is %s." % connection.schema_name) elif has_schema and not is_new and connection.schema_name not in (self.schema_name, get_public_schema_name()): raise Exception("Can't update tenant outside it's own schema or " "the public schema. Current schema is %s." % connection.schema_name) super().save(*args, **kwargs) if has_schema and is_new and self.auto_create_schema: try: self.create_schema(check_if_exists=True, verbosity=verbosity) post_schema_sync.send(sender=TenantMixin, tenant=self.serializable_fields()) except Exception: # We failed creating the tenant, delete what we created and # re-raise the exception self.delete(force_drop=True) raise elif is_new: # although we are not using the schema functions directly, the signal might be registered by a listener schema_needs_to_be_sync.send(sender=TenantMixin, tenant=self.serializable_fields()) elif not is_new and self.auto_create_schema and not schema_exists(self.schema_name): # Create schemas for existing models, deleting only the schema on failure try: self.create_schema(check_if_exists=True, verbosity=verbosity) post_schema_sync.send(sender=TenantMixin, tenant=self.serializable_fields()) except Exception: # We failed creating the schema, delete what we created and # re-raise the exception self._drop_schema() raise
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def serializable_fields(self): """ in certain cases the user model isn't serializable so you may want to only send the id """ return self
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def _drop_schema(self, force_drop=False): """ Drops the schema""" connection = connections[get_tenant_database_alias()] has_schema = hasattr(connection, 'schema_name') if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()): raise Exception("Can't delete tenant outside it's own schema or " "the public schema. Current schema is %s." % connection.schema_name) if has_schema and schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop): self.pre_drop() cursor = connection.cursor() cursor.execute('DROP SCHEMA "%s" CASCADE' % self.schema_name)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def pre_drop(self): """ This is a routine which you could override to backup the tenant schema before dropping. :return: """
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def delete(self, force_drop=False, *args, **kwargs): """ Deletes this row. Drops the tenant's schema if the attribute auto_drop_schema set to True. """ self._drop_schema(force_drop) super().delete(*args, **kwargs)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def create_schema(self, check_if_exists=False, sync_schema=True, verbosity=1): """ Creates the schema 'schema_name' for this tenant. Optionally checks if the schema already exists before creating it. Returns true if the schema was created, false otherwise. """ # safety check connection = connections[get_tenant_database_alias()] _check_schema_name(self.schema_name) cursor = connection.cursor() if check_if_exists and schema_exists(self.schema_name): return False fake_migrations = get_creation_fakes_migrations() if sync_schema: if fake_migrations: # copy tables and data from provided model schema base_schema = get_tenant_base_schema() clone_schema = CloneSchema() clone_schema.clone_schema(base_schema, self.schema_name) call_command('migrate_schemas', tenant=True, fake=True, schema_name=self.schema_name, interactive=False, verbosity=verbosity) else: # create the schema cursor.execute('CREATE SCHEMA "%s"' % self.schema_name) call_command('migrate_schemas', tenant=True, schema_name=self.schema_name, interactive=False, verbosity=verbosity) connection.set_schema_to_public()
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_primary_domain(self): """ Returns the primary domain of the tenant """ try: domain = self.domains.get(is_primary=True) return domain except get_tenant_domain_model().DoesNotExist: return None
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def reverse(self, request, view_name): """ Returns the URL of this tenant. """ http_type = 'https://' if request.is_secure() else 'http://' domain = get_current_site(request).domain url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name))) return url
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def get_tenant_type(self): """ Get the type of tenant. Will only work for multi type tenants :return: str """ return getattr(self, settings.MULTI_TYPE_DATABASE_FIELD)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def save(self, *args, **kwargs): # Get all other primary domains with the same tenant domain_list = self.__class__.objects.filter(tenant=self.tenant, is_primary=True).exclude(pk=self.pk) # If we have no primary domain yet, set as primary domain by default self.is_primary = self.is_primary or (not domain_list.exists()) if self.is_primary: # Remove primary status of existing domains for tenant domain_list.update(is_primary=False) super().save(*args, **kwargs)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def addOperators(self, num, target): """ Adapted from https://leetcode.com/discuss/58614/java-standard-backtrace-ac-solutoin-short-and-clear Algorithm: 1. DFS 2. Special handling for multiplication 3. Detect invalid number with leading 0's :type num: str :type target: int :rtype: List[str] """ ret = [] self.dfs(num, target, 0, "", 0, 0, ret) return ret
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def dfs(self, num, target, pos, cur_str, cur_val, mul, ret): if pos >= len(num): if cur_val == target: ret.append(cur_str) else: for i in xrange(pos, len(num)): if i != pos and num[pos] == "0": continue nxt_val = int(num[pos:i+1]) if not cur_str: self.dfs(num, target, i+1, "%d"%nxt_val, nxt_val, nxt_val, ret) else: self.dfs(num, target, i+1, cur_str+"+%d"%nxt_val, cur_val+nxt_val, nxt_val, ret) self.dfs(num, target, i+1, cur_str+"-%d"%nxt_val, cur_val-nxt_val, -nxt_val, ret) self.dfs(num, target, i+1, cur_str+"*%d"%nxt_val, cur_val-mul+mul*nxt_val, mul*nxt_val, ret)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def implementor(rpc_code, blocking=False): """ RPC implementation function. """ return partial(_add_implementor, rpc_code, blocking)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def _add_implementor(rpc_code, blocking, fn): # Validate the argument types. if type(rpc_code) is not int: raise TypeError("Expected int, got %r instead" % type(rpc_code)) if type(blocking) is not bool: raise TypeError("Expected bool, got %r instead" % type(blocking)) if not callable(fn): raise TypeError("Expected callable, got %r instead" % type(fn)) # Validate the RPC code. if rpc_code in rpcMap: try: msg = "Duplicated RPC implementors for code %d: %s and %s" msg %= (rpc_code, rpcMap[rpc_code][0].__name__, fn.__name__) except Exception: msg = "Duplicated RPC implementors for code: %d" % rpc_code raise SyntaxError(msg) # TODO: use introspection to validate the function signature # Register the implementor. rpcMap[rpc_code] = (fn, blocking) # Return the implementor. No wrapping is needed! :) return fn
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def rpc_bulk(orchestrator, audit_name, rpc_code, *arguments): # Get the implementor for the RPC code. # Raise NotImplementedError if it's not defined. try: method, blocking = rpcMap[rpc_code] except KeyError: raise NotImplementedError("RPC code not implemented: %r" % rpc_code) # This can't be done with blocking implementors! if blocking: raise NotImplementedError( "Cannot run blocking RPC calls in bulk. Code: %r" % rpc_code) # Prepare a partial function call to the implementor. caller = partial(method, orchestrator, audit_name) # Use the built-in map() function to issue all the calls. # This ensures we support the exact same interface and functionality. return map(caller, *arguments)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def rpc_send_message(orchestrator, audit_name, message): # Enqueue the ACK message. orchestrator.enqueue_msg(message)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self, orchestrator): """ :param orchestrator: Orchestrator instance. :type orchestrator: Orchestrator """ # Keep a reference to the Orchestrator. self.__orchestrator = orchestrator # Keep a reference to the global RPC map (it's faster this way). self.__rpcMap = rpcMap # Check all RPC messages have been mapped at this point. missing = MSG_RPC_CODES.difference(self.__rpcMap.keys()) if missing: msg = "Missing RPC implementors for codes: %s" msg %= ", ".join(str(x) for x in sorted(missing)) raise SyntaxError(msg)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def orchestrator(self): """ :returns: Orchestrator instance. :rtype: Orchestrator """ return self.__orchestrator
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def execute_rpc(self, audit_name, rpc_code, response_queue, args, kwargs): """ Honor a remote procedure call request from a plugin. :param audit_name: Name of the audit requesting the call. :type audit_name: str :param rpc_code: RPC code. :type rpc_code: int :param response_queue: Response queue identity. :type response_queue: str :param args: Positional arguments to the call. :type args: tuple :param kwargs: Keyword arguments to the call. :type kwargs: dict """ try: # Get the implementor for the RPC code. # Raise NotImplementedError if it's not defined. try: target, blocking = self.__rpcMap[rpc_code] except KeyError: raise NotImplementedError( "RPC code not implemented: %r" % rpc_code) # If it's a blocking call... if blocking: # Run the implementor in a new thread. thread = Thread( target = self._execute_rpc_implementor_background, args = ( Config._context, audit_name, target, response_queue, args, kwargs), ) thread.daemon = True thread.start() # If it's a non-blocking call... else: # Call the implementor directly. self.execute_rpc_implementor( audit_name, target, response_queue, args, kwargs) # Catch exceptions and send them back. except Exception: if response_queue: error = self.prepare_exception(*sys.exc_info()) try: self.orchestrator.messageManager.send( response_queue, (False, error)) except IOError: import warnings warnings.warn("RPC caller died!") pass
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def _execute_rpc_implementor_background(self, context, audit_name, target, response_queue, args, kwargs): """ Honor a remote procedure call request from a plugin, from a background thread. Must only be used as the entry point for said background thread! :param context: Plugin execution context. :type context: PluginContext :param audit_name: Name of the audit requesting the call. :type audit_name: str :param target: RPC implementor function. :type target: callable :param response_queue: Response queue identity. :type response_queue: str :param args: Positional arguments to the call. :type args: tuple :param kwargs: Keyword arguments to the call. :type kwargs: dict """ Config._context = context self.execute_rpc_implementor( audit_name, target, response_queue, args, kwargs)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def execute_rpc_implementor(self, audit_name, target, response_queue, args, kwargs): """ Honor a remote procedure call request from a plugin. :param audit_name: Name of the audit requesting the call. :type audit_name: str :param target: RPC implementor function. :type target: callable :param response_queue: Response queue identity. :type response_queue: str :param args: Positional arguments to the call. :type args: tuple :param kwargs: Keyword arguments to the call. :type kwargs: dict """ try: # Call the implementor and get the response. response = target(self.orchestrator, audit_name, *args, **kwargs) success = True # Catch exceptions and prepare them for sending. except Exception: if response_queue: response = self.prepare_exception(*sys.exc_info()) success = False # If the call was synchronous, # send the response/error back to the plugin. if response_queue: self.orchestrator.messageManager.send( response_queue, (success, response))
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost'
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def __init__(self): self.SOURCE_HTML_BASE_FOLDER_PATH = u"cameo_res\\source_html" self.PARSED_RESULT_BASE_FOLDER_PATH = u"cameo_res\\parsed_result" self.strWebsiteDomain = u"http://buzzorange.com/techorange" self.dicSubCommandHandler = { "index":self.downloadIndexPage, "tag":self.downloadTagPag, "news":self.downloadNewsPage } self.utility = Utility() self.db = LocalDbForTECHORANGE() self.driver = None
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def _cost_gp(self,x): """ Predicts the time cost of evaluating the function at x. """ m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m)
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def getUseageMessage(self): return ("- TECHORANGE -\n" "useage:\n" "index - download entry page of TECHORANGE \n" "tag - download not obtained tag page \n" "news [tag] - download not obtained news [of given tag] \n")
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx
def emit(self, level, message): raise NotImplementedError('Please implement an emit method')
def getDriver(self): chromeDriverExeFilePath = "cameo_res\\chromedriver.exe" driver = webdriver.Chrome(chromeDriverExeFilePath) return driver