code
stringlengths
1
18.2k
raise ValueError("Client does not have permission.") return True
def grant_client_permissions(self, client_id, admin=False, write=False, read=False, secret=False): """ Grant the given client_id permissions for managing clients. - clients.admin: super user scope to create, modify, delete - clients.write: scope ot create and modify clients - clients.read: scope to read info about clie...
read or admin: perms.append('clients.read') if secret or admin: perms.append('clients.secret') if perms: self.update_client_grants(client_id, scope=perms, authorities=perms)
def get_clients(self): """ Returns the clients stored in the instance of UAA. """ self.assert_has_permission('clients.read') uri = self.uri + '/oauth/clients' headers = self.get_authorization_headers() response = requests.get(uri, headers=headers) return response.json()['resources']
def get_client(self, client_id): """ Returns details about a specific client by the client_id. """ self.assert_has_permission('clients.read') uri = self.uri + '/oauth/clients/' + client_id headers = self.get_authorization_headers() response = requests.get(uri, headers=headers) if response.status_code == 200: return res...
def update_client_grants(self, client_id, scope=[], authorities=[], grant_types=[], redirect_uri=[], replace=False): """ Will extend the client with additional scopes or authorities. Any existing scopes and authorities will be left as is unless asked to replace entirely. """ self.assert_has_permission('clients.write') ...
{'client_id': client_id} if scope: changes['scope'] = client['scope'] changes['scope'].extend(scope) if authorities: changes['authorities'] = client['authorities'] changes['authorities'].extend(authorities) if grant_types: if 'authorization_code' in grant_types and not redirect_uri: logging.warning("A redirect_uri is r...
"application/json", "Authorization": "Bearer " + self.get_token() } logging.debug("URI=" + str(uri)) logging.debug("HEADERS=" + str(headers)) logging.debug("BODY=" + json.dumps(changes)) response = requests.put(uri, headers=headers, data=json.dumps(changes)) logging.debug("STATUS=" + str(response.status_code)) if respo...
def grant_scim_permissions(self, client_id, read=False, write=False, create=False, userids=False, zones=False, invite=False, openid=False): """ Grant the given client_id permissions for managing users. System for Cross-domain Identity Management (SCIM) are required for accessing /Users and /Groups endpoints of UAA. - s...
account only - scim.userids: scope for id and username+origin conversion - scim.zones: scope for group management of users only - scim.invite: scope to participate in invitations - openid: scope to access /userinfo """ self.assert_has_permission('clients.admin') perms = [] if read: perms.append('scim.read') if write: p...
def create_client(self, client_id, client_secret, manifest=None, client_credentials=True, refresh_token=True, authorization_code=False, redirect_uri=[]): """ Will create a new client for your application use. - client_credentials: allows client to get access token - refresh_token: can be used to get new access token wh...
See: https://www.predix.io/support/article/KB0013026 """ self.assert_has_permission('clients.admin') if authorization_code and not redirect_uri: raise ValueError("Must provide a redirect_uri for clients used with authorization_code") # Check if client already exists client = self.get_client(client_id) if client: return...
authorization_code: grant_types.append('authorization_code') params = { "client_id": client_id, "client_secret": client_secret, "scope": ["uaa.none"], "authorized_grant_types": grant_types, "authorities": ["uaa.none"], "autoapprove": [] } if redirect_uri: params.append(redirect_uri) response = requests.post(uri, header...
def add_client_to_manifest(self, client_id, client_secret, manifest): """ Add the given client / secret to the manifest for use in the application. """ client_id_key = 'PREDIX_APP_CLIENT_ID' manifest.add_env_var(client_id_key, client_id) client_secret_key = 'PREDIX_APP_CLIENT_SECRET' manifest.add_env_var(client_secret_...
def create_user(self, username, password, family_name, given_name, primary_email, details={}): """ Creates a new user account with the required details. :: create_user('j12y', 'my-secret', 'Delancey', 'Jayson', 'volcano@ge.com') """ self.assert_has_permission('scim.write') data = { 'userName': username, 'password': pas...
def delete_user(self, id): """ Delete user with given id. """ self.assert_has_permission('scim.write') uri = self.uri + '/Users/%s' % id headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("HEADERS=" + str(headers)) response = self.session.delete(uri, headers=headers) logging.debug("STATUS=" + ...
def get_users(self, filter=None, sortBy=None, sortOrder=None, startIndex=None, count=None): """ Returns users accounts stored in UAA. See https://docs.cloudfoundry.org/api/uaa/#list63 For filtering help, see: http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources """ self.assert_has_permission('scim.r...
def get_user_by_username(self, username): """ Returns details for user of the given username. If there is more than one match will only return the first. Use get_users() for full result set. """ results = self.get_users(filter='username eq "%s"' % (username)) if results['totalResults'] == 0: logging.warning("Found no m...
def get_user_by_email(self, email): """ Returns details for user with the given email address. If there is more than one match will only return the first. Use get_users() for full result set. """ results = self.get_users(filter='email eq "%s"' % (email)) if results['totalResults'] == 0: logging.warning("Found no matche...
results['resources'][0]
def get_user(self, id): """ Returns details about the user for the given id. Use get_user_by_email() or get_user_by_username() for help identifiying the id. """ self.assert_has_permission('scim.read') return self._get(self.uri + '/Users/%s' % (id))
def create(self): """ Create an instance of the Time Series Service with the typical starting settings. """ self.service.create() predix.config.set_env_value(self.use_class, 'ingest_uri', self.get_ingest_uri()) predix.config.set_env_value(self.use_class, 'ingest_zone_id', self.get_ingest_zone_id()) predix.config.set_en...
def grant_client(self, client_id, read=True, write=True): """ Grant the given client id all the scopes and authorities needed to work with the timeseries service. """ scopes = ['openid'] authorities = ['uaa.resource'] if write: for zone in self.service.settings.data['ingest']['zone-token-scopes']: scopes.append(zone) a...
def get_query_uri(self): """ Return the uri used for queries on time series data. """ # Query URI has extra path we don't want so strip it off here query_uri = self.service.settings.data['query']['uri'] query_uri = urlparse(query_uri) return query_uri.scheme + '://' + query_uri.netloc
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app. """ # Add this service to list of services manifest...
uri = predix.config.get_env_key(self.use_class, 'query_uri') manifest.add_env_var(uri, self.get_query_uri()) zone_id = predix.config.get_env_key(self.use_class, 'query_zone_id') manifest.add_env_var(zone_id, self.get_query_zone_id()) manifest.write_manifest()
def find_requirements(path): """ This method tries to determine the requirements of a particular project by inspecting the possible places that they could be defined. It will attempt, in order: 1) to parse setup.py in the root for an install_requires value 2) to read a requirements.txt file or a requirements.pip in the...
the root 4) to read files matching "*requirements*.txt" and "*reqs*.txt" in the root, excluding any starting or ending with 'test' If one of these succeeds, then a list of pkg_resources.Requirement's will be returned. If none can be found, then a RequirementsNotFound will be raised """ requirements = [] setup_py = os.p...
CouldNotParseRequirements: pass for reqfile_name in ('requirements.txt', 'requirements.pip'): reqfile_path = os.path.join(path, reqfile_name) if os.path.exists(reqfile_path) and os.path.isfile(reqfile_path): try: requirements += from_requirements_txt(reqfile_path) except CouldNotParseRequirements as e: pass requirement...
raise RequirementsNotFound
def get_app_guid(self, app_name): """ Returns the GUID for the app instance with the given name. """ summary = self.space.get_space_summary() for app in summary['apps']: if app['name'] == app_name: return app['guid']
def delete_app(self, app_name): """ Delete the given app. Will fail intentionally if there are any service bindings. You must delete those first. """ if app_name not in self.space.get_apps(): logging.warning("App not found so... succeeded?") return True guid = self.get_app_guid(app_name) self.api.delete("/v2/apps/%s" %...
def _get_service_config(self): """ Reads in config file of UAA credential information or generates one as a side-effect if not yet initialized. """ # Should work for windows, osx, and linux environments if not os.path.exists(self.config_path): try: os.makedirs(os.path.dirname(self.config_path)) except OSError as exc: i...
def _write_service_config(self): """ Will write the config out to disk. """ with open(self.config_path, 'w') as output: output.write(json.dumps(self.data, sort_keys=True, indent=4))
def create(self, **kwargs): """ Create an instance of the Blob Store Service with the typical starting settings. """ self.service.create(**kwargs) predix.config.set_env_value(self.use_class, 'url', self.service.settings.data['url']) predix.config.set_env_value(self.use_class, 'access_key_id', self.service.settings.data...
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app. """ # Add this service to the list of services mani...
self.service.settings.data['access_key_id']) bucket = predix.config.get_env_key(self.use_class, 'bucket_name') manifest.add_env_var(bucket, self.service.settings.data['bucket_name']) host = predix.config.get_env_key(self.use_class, 'host') manifest.add_env_var(host, self.service.settings.data['host']) secret_access_key...
def subscribe(self): """ return a generator for all subscribe messages :return: None """ while self.run_subscribe_generator: if len(self._rx_messages) != 0: yield self._rx_messages.pop(0) return
def send_acks(self, message): """ send acks to the service :param message: EventHub_pb2.Message :return: None """ if isinstance(message, EventHub_pb2.Message): ack = EventHub_pb2.Ack(partition=message.partition, offset=message.offset) self.grpc_manager.send_message(EventHub_pb2.SubscriptionResponse(ack=ack)) elif isins...
def _generate_subscribe_headers(self): """ generate the subscribe stub headers based on the supplied config :return: i """ headers =[] headers.append(('predix-zone-id', self.eventhub_client.zone_id)) token = self.eventhub_client.service._get_bearer_token() headers.append(('subscribername', self._config.subscriber_name)...
self._config.batching_enabled: headers.append(('batch-size', str(self._config.batch_size))) headers.append(('batch-interval', str(self._config.batch_interval_millis) + 'ms')) return headers
def _get_assets(self, bbox, size=None, page=None, asset_type=None, device_type=None, event_type=None, media_type=None): """ Returns the raw results of an asset search for a given bounding box. """ uri = self.uri + '/v1/assets/search' headers = self._get_headers() params = { 'bbox': bbox, } # Query parameters params['q'...
%s" % device) params['q'].append("device-type:%s" % device) if asset_type: if isinstance(asset_type, str): asset_type = [asset_type] for asset in asset_type: if asset not in self.ASSET_TYPES: logging.warning("Invalid asset type: %s" % asset) params['q'].append("assetType:%s" % asset) if media_type: if isinstance(media_...
= [event_type] for event in event_type: if event not in self.EVENT_TYPES: logging.warning("Invalid event type: %s" % event) params['q'].append("eventTypes:%s" % event) # Pagination parameters if size: params['size'] = size if page: params['page'] = page return self.service._get(uri, params=params, headers=headers)
def get_assets(self, bbox, **kwargs): """ Query the assets stored in the intelligent environment for a given bounding box and query. Assets can be filtered by type of asset, event, or media available. - device_type=['DATASIM'] - asset_type=['CAMERA'] - event_type=['PKIN'] - media_type=['IMAGE'] Pagination can be contro...
asset-id - device-type - device-id - media-type - coordinates - event-type Additionally there are some _links for additional information. """ response = self._get_assets(bbox, **kwargs) # Remove broken HATEOAS _links but identify asset uid first assets = [] for asset in response['_embedded']['assets']: asset_url = asse...
def _get_asset(self, asset_uid): """ Returns raw response for an given asset by its unique id. """ uri = self.uri + '/v2/assets/' + asset_uid headers = self._get_headers() return self.service._get(uri, headers=headers)
def label(self, input_grid): """ Label input grid with hysteresis method. Args: input_grid: 2D array of values. Returns: Labeled output grid. """ unset = 0 high_labels, num_labels = label(input_grid > self.high_thresh) region_ranking = np.argsort(maximum(input_grid, high_labels, index=np.arange(1, num_labels + 1)))[::-...
if output_grid[label_i[i], label_j[i]] == unset: stack.append((label_i[i], label_j[i])) while len(stack) > 0: index = stack.pop() output_grid[index] = label_num for i in range(index[0] - 1, index[0] + 2): for j in range(index[1] - 1, index[1] + 2): if 0 <= i < output_grid.shape[0] and 0 <= j < output_grid.shape[1]: if ...
def size_filter(labeled_grid, min_size): """ Remove labeled objects that do not meet size threshold criteria. Args: labeled_grid: 2D output from label method. min_size: minimum size of object in pixels. Returns: labeled grid with smaller objects removed. """ out_grid = np.zeros(labeled_grid.shape, dtype=int) slices = f...
min_size and box.shape[0] > 1 and box.shape[1] > 1: out_grid[np.where(labeled_grid == i + 1)] = j j += 1 return out_grid
def roc_curve(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Probability of False Detection", ylabel="Probability of Detection", title="ROC Curve", ticks=np.arange(0, 1.1, 0.1), dpi=300, legend_params=None, bootstrap_sets=None, ci=(2.5, 97.5), label_fontsize=14, title_fontsize=16, tick_fontsiz...
Rate) on the y-axis and Probability of False Detection (False Alarm Rate) on the x-axis. This plotting function allows one to customize the colors and markers of the ROC curves as well as the parameters of the legend and the title. Args: roc_objs (list): DistributedROC objects being plotted. obj_labels (list): Label de...
colors (names or hex-values) for each curve. markers (list): Matplotlib marker (e.g. *, o, v, etc.) for each curve. filename (str): Name of figure file being saved. figsize (tuple): (Width, height) of the figure in inches. xlabel (str): Label for the x-axis. ylabel (str): Label for the y-axis. title (str): The title of...
axes. dpi (int): Figure resolution in dots per inch. legend_params (None, dict): Keyword arguments for the formatting of the figure legend. bootstrap_sets (list): List of lists of DistributedROC objects that were bootstrap resampled for each model. ci (tuple of 2 floats): Quantiles of the edges of the bootstrap confide...
axis labels. title_fontsize (int): Font size of the title. tick_fontsize (int): Font size of the x and y tick labels. Examples: >>> from hagelslag.evaluation import DistributedROC >>> import numpy as np >>> forecasts = np.random.random(1000) >>> obs = np.random.random_integers(0, 1, 1000) >>> roc = DistributedROC() >>>...
frameon=True) plt.figure(figsize=figsize, dpi=dpi) plt.plot(ticks, ticks, "k--") if bootstrap_sets is not None: for b, b_set in enumerate(bootstrap_sets): broc_curves = np.dstack([b_roc.roc_curve().values for b_roc in b_set]) pod_range = np.percentile(broc_curves[:,0], ci, axis=1) pofd_range = np.percentile(broc_curves...
marker=markers[r], color=colors[r], label=obj_labels[r]) plt.xlabel(xlabel, fontsize=label_fontsize) plt.ylabel(ylabel, fontsize=label_fontsize) plt.xticks(ticks, fontsize=tick_fontsize) plt.yticks(ticks, fontsize=tick_fontsize) plt.title(title, fontsize=title_fontsize) plt.legend(**legend_params) plt.savefig(filename,...
def performance_diagram(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Success Ratio (1-FAR)", ylabel="Probability of Detection", ticks=np.arange(0, 1.1, 0.1), dpi=300, csi_cmap="Blues", csi_label="Critical Success Index", title="Performance Diagram", legend_params=None, bootstrap_sets=None, c...
replaced with the Success Ratio (1-False Alarm Ratio or Precision). The diagram also shows the Critical Success Index (CSI or Threat Score) as a series of curved contours, and the frequency bias as angled diagonal lines. Points along the 1:1 diagonal are unbiased, and better performing models should appear in the upper...
severe weather warnings as it displays all three commonly used statistics (POD, FAR, and CSI) simultaneously on the same chart. Args: roc_objs (list): DistributedROC objects being plotted. obj_labels: list or array of labels describing each DistributedROC object. obj_labels (list): Label describing the forecast associa...
(e.g. *, o, v, etc.) for each curve. filename (str): Name of figure file being saved. figsize (tuple): (Width, height) of the figure in inches. xlabel (str): Label for the x-axis. ylabel (str): Label for the y-axis. title (str): The title of the figure. ticks (numpy.ndarray): Values shown on the x and y axes. dpi (int)...
Matplotlib colormap used to fill CSI contours. csi_label (str): Label for CSI colormap. legend_params (None or dict): Keyword arguments for the formatting of the figure legend. bootstrap_sets (list): A list of arrays of bootstrapped DistributedROC objects. If not None, confidence regions will be plotted. ci (tuple): tu...
(int): Font size of the title. tick_fontsize (int): Font size of the x and y tick labels. Examples: >>> from hagelslag.evaluation import DistributedROC >>> import numpy as np >>> forecasts = np.random.random(1000) >>> obs = np.random.random_integers(0, 1, 1000) >>> roc = DistributedROC() >>> roc.update(forecasts, obs) ...
= np.arange(0, 1.01, 0.01) sr_g, pod_g = np.meshgrid(grid_ticks, grid_ticks) bias = pod_g / sr_g csi = 1.0 / (1.0 / sr_g + 1.0 / pod_g - 1.0) csi_contour = plt.contourf(sr_g, pod_g, csi, np.arange(0.1, 1.1, 0.1), extend="max", cmap=csi_cmap) b_contour = plt.contour(sr_g, pod_g, bias, [0.5, 1, 1.5, 2, 4], colors="k", li...
for b, b_set in enumerate(bootstrap_sets): perf_curves = np.dstack([b_roc.performance_curve().values for b_roc in b_set]) pod_range = np.nanpercentile(perf_curves[:, 0], ci, axis=1) sr_range = np.nanpercentile(1 - perf_curves[:, 1], ci, axis=1) pod_poly = np.concatenate((pod_range[1], pod_range[0, ::-1])) sr_poly = np....
cbar.set_label(csi_label) plt.xlabel(xlabel, fontsize=label_fontsize) plt.ylabel(ylabel, fontsize=label_fontsize) plt.xticks(ticks, fontsize=tick_fontsize) plt.yticks(ticks, fontsize=tick_fontsize) plt.title(title, fontsize=title_fontsize) plt.legend(**legend_params) plt.savefig(filename, dpi=dpi, bbox_inches="tight") ...
def reliability_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability", ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300, inset_size=1.5, title="Reliability Diagram", legend_params=None, bootstrap_sets=None, ci=(2.5, 97.5)): """ Plot reliabili...
colors (list): List of colors for each line markers (list): List of line markers filename (str): Where to save the figure. figsize (tuple): (Width, height) of the figure in inches. xlabel (str): X-axis label ylabel (str): Y-axis label ticks (array): Tick value labels for the x and y axes. dpi (int): resolution of the s...
inset title (str): Title of figure legend_params (dict): Keyword arguments for the plot legend. bootstrap_sets (list): A list of arrays of bootstrapped DistributedROC objects. If not None, confidence regions will be plotted. ci (tuple): tuple of bootstrap confidence interval percentiles """ if legend_params is None: le...
if bootstrap_sets is not None: for b, b_set in enumerate(bootstrap_sets): brel_curves = np.dstack([b_rel.reliability_curve().values for b_rel in b_set]) bin_range = np.percentile(brel_curves[:,0], ci, axis=1) rel_range = np.percentile(brel_curves[:, 3], ci, axis=1) bin_poly = np.concatenate((bin_range[1], bin_range[0, ...
marker=markers[r]) inset_hist.set_xlabel("Forecast Probability") inset_hist.set_ylabel("Forecast Relative Frequency") ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_xticks(ticks) ax.set_yticks(ticks) ax.legend(**legend_params) ax.set_title(title) plt.savefig(filename, dpi=dpi, bbox_inches="tight") plt.close()
def attributes_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability", ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300, title="Attributes Diagram", legend_params=None, inset_params=None, inset_position=(0.12, 0.72, 0.25, 0.25), bootstrap_sets...
a positive Brier Skill Score. Args: rel_objs (list): List of DistributedReliability objects. obj_labels (list): List of labels describing the forecast model associated with each curve. colors (list): List of colors for each line markers (list): List of line markers filename (str): Where to save the figure. figsize (tup...
(array): Tick value labels for the x and y axes. dpi (int): resolution of the saved figure in dots per inch. title (str): Title of figure legend_params (dict): Keyword arguments for the plot legend. inset_params (dict): Keyword arguments for the inset axis. inset_position (tuple): Position of the inset axis in normaliz...
bootstrapped DistributedROC objects. If not None, confidence regions will be plotted. ci (tuple): tuple of bootstrap confidence interval percentiles """ if legend_params is None: legend_params = dict(loc=4, fontsize=10, framealpha=1, frameon=True) if inset_params is None: inset_params = dict(width="25%", height="25%", ...
+ 0.5 * climo skill_x = [climo, climo, 1, 1, climo, climo, 0, 0, climo] skill_y = [climo, 1, 1, no_skill[-1], climo, 0, 0, no_skill[0], climo] f = ax.fill(skill_x, skill_y, "0.8") f[0].set_zorder(1) ax.plot(ticks, np.ones(ticks.shape) * climo, "k--") if bootstrap_sets is not None: for b, b_set in enumerate(bootstrap_se...
alpha=0.5, color=colors[b]) fb.set_zorder(2) for r, rel_obj in enumerate(rel_objs): rel_curve = rel_obj.reliability_curve() ax.plot(rel_curve["Bin_Start"], rel_curve["Positive_Relative_Freq"], color=colors[r], marker=markers[r], label=obj_labels[r]) inset_hist.semilogy(rel_curve["Bin_Start"] * 100, rel_obj.frequencies[...
def get_string(self, prompt, default_str=None) -> str: """Return a string value that the user enters. Raises exception for cancel.""" accept_event = threading.Event() value_ref = [None] def perform(): def accepted(text): value_ref[0] = text accept_event.set() def rejected(): accept_event.set() self.__message_column.rem...
Exception("Cancel") return value_ref[0]
def __accept_reject(self, prompt, accepted_text, rejected_text, display_rejected): """Return a boolean value for accept/reject.""" accept_event = threading.Event() result_ref = [False] def perform(): def accepted(): result_ref[0] = True accept_event.set() def rejected(): result_ref[0] = False accept_event.set() self.__...
def compute_weight(self, r, ytr=None, mask=None): """Returns the weight (w) using OLS of r * w = gp._ytr """ ytr = self._ytr if ytr is None else ytr mask = self._mask if mask is None else mask return compute_weight(r, ytr, mask)
def isfinite(self): "Test whether the predicted values are finite" if self._multiple_outputs: if self.hy_test is not None: r = [(hy.isfinite() and (hyt is None or hyt.isfinite())) for hy, hyt in zip(self.hy, self.hy_test)] else: r = [hy.isfinite() for hy in self.hy] return np.all(r) return self.hy.isfinite() and (self....
def value_of_named_argument_in_function(argument_name, function_name, search_str, resolve_varname=False): """ Parse an arbitrary block of python code to get the value of a named argument from inside a function call """ try: search_str = unicode(search_str) except NameError: pass readline = StringIO(search_str).readline...
' + str(e)) in_function = False is_var = False for i in range(len(tokens)): if ( not in_function and tokens[i].typenum == tokenize.NAME and tokens[i].value == function_name and tokens[i+1].typenum == tokenize.OP and tokens[i+1].value == '(' ): in_function = True continue elif ( in_function and tokens[i].typenum == toke...
variable which we are going to attempt to resolve if resolve_varname and tokens[i+2].typenum == 1: is_var = True argument_name = tokens[i+2].value break # again, for a very specific usecase -- get the whole value and concatenate it # this will match something like _version.__version__ j = 3 while True: if tokens[i+j].v...
for t in tokens[i+2:i+j]]).strip() # this is very dumb logic, and only works if the function argument is set to a variable # which is set to a string value if is_var: for i in range(len(tokens)): if ( tokens[i].typenum == tokenize.NAME and tokens[i].value == argument_name and tokens[i+1].typenum == tokenize.OP and toke...
def regex_in_file(regex, filepath, return_match=False): """ Search for a regex in a file If return_match is True, return the found object instead of a boolean """ file_content = get_file_content(filepath) re_method = funcy.re_find if return_match else funcy.re_test return re_method(regex, file_content)
def regex_in_package_file(regex, filename, package_name, return_match=False): """ Search for a regex in a file contained within the package directory If return_match is True, return the found object instead of a boolean """ filepath = package_file_path(filename, package_name) return regex_in_file(regex, filepath, retur...
def string_is_url(test_str): """ Test to see if a string is a URL or not, defined in this case as a string for which urlparse returns a scheme component >>> string_is_url('somestring') False >>> string_is_url('https://some.domain.org/path') True """ parsed = urlparse.urlparse(test_str) return parsed.scheme is not None ...
def item_transaction(self, item) -> Transaction: """Begin transaction state for item. A transaction state is exists to prevent writing out to disk, mainly for performance reasons. All changes to the object are delayed until the transaction state exits. This method is thread safe. """ items = self.__build_transaction_it...
def insert_data_item(self, before_index, data_item, auto_display: bool = True) -> None: """Insert a new data item into document model. This method is NOT threadsafe. """ assert data_item is not None assert data_item not in self.data_items assert before_index <= len(self.data_items) and before_index >= 0 assert data_ite...
add a display if auto_display: display_item = DisplayItem.DisplayItem(data_item=data_item) self.append_display_item(display_item)
def remove_data_item(self, data_item: DataItem.DataItem, *, safe: bool=False) -> typing.Optional[typing.Sequence]: """Remove data item from document model. This method is NOT threadsafe. """ # remove data item from any computations return self.__cascade_delete(data_item, safe=safe)
def __cascade_delete_inner(self, master_item, safe: bool=False) -> typing.Optional[typing.Sequence]: """Cascade delete an item. Returns an undelete log that can be used to undo the cascade deletion. Builds a cascade of items to be deleted and dependencies to be removed when the passed item is deleted. Then removes comp...
until nothing more gets removed. Next remove dependencies. Next remove individual items (from the most distant from the root item to the root item). """ # print(f"cascade {master_item}") # this horrible little hack ensures that computation changed messages are delayed until the end of the cascade # delete; otherwise th...
method is partially finished. ugh. see test_computation_deletes_when_source_cycle_deletes. if self.__computation_changed_delay_list is None: computation_changed_delay_list = list() self.__computation_changed_delay_list = computation_changed_delay_list else: computation_changed_delay_list = None undelete_log = list() tr...
in computation._outputs computation._inputs -= items_set computation._outputs -= items_set if computation not in items and computation != self.__current_computation: # computations are auto deleted if all inputs are deleted or any output is deleted if output_deleted or all(input in items for input in computation._input...
items for item in reversed(items): for computation in self.computations: new_entries = computation.list_item_removed(item) undelete_log.extend(new_entries) container = item.container if isinstance(item, DataItem.DataItem): name = "data_items" elif isinstance(item, DisplayItem.DisplayItem): name = "display_items" elif i...
"Unable to cascade delete type " + str(type(item)) assert name # print(container, name, item) if container is self and name == "data_items": # call the version of __remove_data_item that doesn't cascade again index = getattr(container, name).index(item) item_dict = item.write_to_dict() # NOTE: __remove_data_item will n...