text
stringlengths
81
112k
Disable an existing User Group Args: usergroup (str): The encoded ID of the User Group to disable. e.g. 'S0604QSJC' def usergroups_disable(self, *, usergroup: str, **kwargs) -> SlackResponse: """Disable an existing User Group Args: usergroup (str): The ...
List all User Groups for a team def usergroups_list(self, **kwargs) -> SlackResponse: """List all User Groups for a team""" self._validate_xoxp_token() return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
List all users in a User Group Args: usergroup (str): The encoded ID of the User Group to update. e.g. 'S0604QSJC' def usergroups_users_list(self, *, usergroup: str, **kwargs) -> SlackResponse: """List all users in a User Group Args: usergroup (str): Th...
Update the list of users for a User Group Args: usergroup (str): The encoded ID of the User Group to update. e.g. 'S0604QSJC' users (list): A list user IDs that represent the entire list of users for the User Group. e.g. ['U060R4BJ4', 'U060RNRCZ'] def us...
Delete the user profile photo def users_deletePhoto(self, **kwargs) -> SlackResponse: """Delete the user profile photo""" self._validate_xoxp_token() return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
Gets user presence information. Args: user (str): User to get presence info on. Defaults to the authed user. e.g. 'W1234567890' def users_getPresence(self, *, user: str, **kwargs) -> SlackResponse: """Gets user presence information. Args: user (str): Us...
Get a user's identity. def users_identity(self, **kwargs) -> SlackResponse: """Get a user's identity.""" self._validate_xoxp_token() return self.api_call("users.identity", http_verb="GET", params=kwargs)
Find a user with an email address. Args: email (str): An email address belonging to a user in the workspace. e.g. 'spengler@ghostbusters.example.com' def users_lookupByEmail(self, *, email: str, **kwargs) -> SlackResponse: """Find a user with an email address. Args...
Set the user profile photo Args: image (str): Supply the path of the image you'd like to upload. e.g. 'myimage.png' def users_setPhoto(self, *, image: Union[str, IOBase], **kwargs) -> SlackResponse: """Set the user profile photo Args: image (str): Suppl...
Manually sets user presence. Args: presence (str): Either 'auto' or 'away'. def users_setPresence(self, *, presence: str, **kwargs) -> SlackResponse: """Manually sets user presence. Args: presence (str): Either 'auto' or 'away'. """ kwargs.update({"pres...
Retrieves a user's profile information. def users_profile_get(self, **kwargs) -> SlackResponse: """Retrieves a user's profile information.""" self._validate_xoxp_token() return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
Set the profile information for a user. def users_profile_set(self, **kwargs) -> SlackResponse: """Set the profile information for a user.""" self._validate_xoxp_token() return self.api_call("users.profile.set", json=kwargs)
Create a request and execute the API call to Slack. Args: api_method (str): The target Slack API method. e.g. 'chat.postMessage' http_verb (str): HTTP Verb. e.g. 'POST' files (dict): Files to multipart upload. e.g. {imageORfile: file_objectORf...
Ensures that an xoxp token is used when the specified method is called. Raises: BotUserAccessError: If the API method is called with a Bot User OAuth Access Token. def _validate_xoxp_token(self): """Ensures that an xoxp token is used when the specified method is called. Raises: ...
Sends the request out for transmission. Args: http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'. api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage' req_args (dict): The request arguments to be attached to the request. e.g. ...
Submit the HTTP request with the running session or a new session. Returns: A dictionary of the response data. async def _request(self, *, http_verb, api_url, req_args): """Submit the HTTP request with the running session or a new session. Returns: A dictionary of the re...
Construct the user-agent header with the package info, Python version and OS version. Returns: The user agent string. e.g. 'Python/3.6.7 slack/2.0.0 Darwin/17.7.0' def _get_user_agent(): """Construct the user-agent header with the package info, Python version an...
Check if the response from Slack was successful. Returns: (SlackResponse) This method returns it's own object. e.g. 'self' Raises: SlackApiError: The request to the Slack API failed. def validate(self): """Check if the response from Slack was successful...
Create and send an onboarding welcome message to new users. Save the time stamp of this message so we can update this message in the future. def onboarding_message(**payload): """Create and send an onboarding welcome message to new users. Save the time stamp of this message so we can update this message in...
Log the time it takes to run a function. It's sort of like timeit, but prettier. def log_time(func: Callable[..., Any]) -> Callable[..., Any]: """Log the time it takes to run a function. It's sort of like timeit, but prettier. """ def wrapper(*args, **kwargs): start_time = time.time() ...
We double-fork here to detach the daemon process from the parent. If we were to just fork the child as a daemon, we'd have to worry about the parent process exiting zombifying the daemon. def daemonize(self) -> None: """We double-fork here to detach the daemon process from the parent. ...
Populates this graph from the given one based on affected_files def populate_from_trace_graph(self, graph: TraceGraph) -> None: """Populates this graph from the given one based on affected_files """ # Track which trace frames have been visited as we populate the full # traces of the gra...
Populates the trimmed graph with issues whose locations are in affected_files based on data in the input graph. Since these issues exist in the affected files, all traces are copied as well. def _populate_affected_issues(self, graph: TraceGraph) -> None: """Populates the trimmed graph with issu...
TraceFrames found in affected_files should be reachable via some issue instance. Follow traces of graph to find them and populate this TrimmedGraph with it. def _populate_issues_from_affected_trace_frames(self, graph: TraceGraph) -> None: """TraceFrames found in affected_files should be reachab...
Helper for populating reachable issue instances from the initial pre/postconditions. Also populates conditions/traces reachable from these instances. Traces are populated only in the direction this is called from: i.e. if initial_conditions are preconditions, only the backward trace is p...
Copies an issue over from the given trace graph, including all its traces and assocs. def _populate_issue_and_traces(self, graph: TraceGraph, instance_id: int) -> None: """ Copies an issue over from the given trace graph, including all its traces and assocs. """ self._populate_i...
Adds an issue to the trace graph along with relevant information pertaining to the issue (e.g. instance, fix_info, sources/sinks) The issue is identified by its corresponding instance's ID in the input trace graph. def _populate_issue(self, graph: TraceGraph, instance_id: int) -> None: ...
Populates (from the given trace graph) the forward and backward traces reachable from the given traces (including input trace frames). Make sure to respect trace kind in successors def _populate_trace(self, graph: TraceGraph, trace_frame_ids: List[int]) -> None: """ Populates (from the given tr...
Copies the trace frame from 'graph' to this (self) graph. Also copies all the trace_frame-leaf assocs since we don't know which ones are needed until we know the issue that reaches it def _add_trace_frame(self, graph: TraceGraph, trace_frame: TraceFrame) -> None: """ Copies the trace frame from...
Given a shared analysis directory, produce a mapping from actual source files to files contained within this directory. Only includes files which have one of the provided extensions. Watchman watches actual source files, so when a change is detected to a file, this mapping can be used t...
Raises an OSError if the lock can't be acquired def acquire_lock(path: str, blocking: bool) -> Generator[Optional[int], None, None]: """Raises an OSError if the lock can't be acquired""" try: with open(path, "w+") as lockfile: if not blocking: lock_command = fcntl.LOCK_EX | ...
Process a list of paths which were added/removed/updated, making any necessary changes to the directory: - For an AnalysisDirectory, nothing needs to be changed, since the mapping from source file to analysis file is 1:1. - For a SharedAnalysisDirectory, the...
Return the paths in the analysis directory (symbolic links) corresponding to the given paths. Result also includes any files which are within a tracked directory. This method will remove/add symbolic links for deleted/new files. def process_updated_files(self, paths: List[str]) -> ...
Return the list of files that match any of the patterns within root. If exclude is provided, files that match an exclude pattern are omitted. Note: The `find` command does not understand globs properly. e.g. 'a/*.py' will match 'a/b/c.py' For this reason, avoid calli...
Iterate over all issues and count the number of times each callable is seen. def _compute_callables_count(self, iters: Dict[str, Any]): """Iterate over all issues and count the number of times each callable is seen.""" count = dict.fromkeys([issue["callable"] for issue in iters["issues"...
setting boilerplate when creating a Run object def _create_empty_run( self, status=RunStatus.FINISHED, status_description=None ) -> Run: """setting boilerplate when creating a Run object""" run = Run( job_id=self.summary["job_id"], issue_instances=[], dat...
Insert the issue instance into a run. This includes creating (for new issues) or finding (for existing issues) Issue objects to associate with the instances. Also create sink entries and associate related issues def _generate_issue(self, run, entry, callablesCount): """Insert the issue ...
Remove all lines in execution history added by iPython calls. def get_history_without_ipython_calls(self): """ Remove all lines in execution history added by iPython calls. """ line_count = 0 filtered_history = [] for line in self.history: if "get_ipython()."...
Prepares the bulk saver to load the trace graph info into the database. def _prep_save(self): """ Prepares the bulk saver to load the trace graph info into the database. """ log.info("Preparing bulk save.") self.graph.update_bulk_saver(self.bulk_saver) log.info(...
Saves bulk saver's info into the databases in bulk. def _save(self) -> RunSummary: """ Saves bulk saver's info into the databases in bulk. """ assert self.summary["run"] is not None, "Must have called process before" trace_frames = self.bulk_saver.get_items_to_add(TraceFrame) l...
Returns a list of pairs (leaf_name, distance) def _parse_leaves(self, leaves) -> List[Tuple[str, int]]: """Returns a list of pairs (leaf_name, distance)""" return [(self._leaf_name(leaf), 0) for leaf in leaves]
Generates all file handles represented by the analysis. Callee owns file handle and closes it when the next is yielded or the generator ends. def file_handles(self) -> Iterable[IO[str]]: """Generates all file handles represented by the analysis. Callee owns file handle and closes it whe...
Generates all file names that are used to generate file_handles. def file_names(self) -> Iterable[str]: """Generates all file names that are used to generate file_handles. """ if self.is_sharded(): yield from ShardedFile(self.filename_spec).get_filenames() elif self.filename...
This is called immediately before the items are written to the database. pkgen is passed in to allow last-minute resolving of ids. def prepare(cls, session, pkgen, items): """This is called immediately before the items are written to the database. pkgen is passed in to allow last-minute resolvi...
An object can have multiple attributes as its key. This merges the items to be added with existing items in the database based on their key(s). session: Session object for querying the DB. items: Iterator of items to be added to the DB. hash_item: Function that takes as in put t...
SQLAlchemy uses this to convert a string into a SourceLocation object. We separate the fields by a | def process_result_value(self, value, dialect): """ SQLAlchemy uses this to convert a string into a SourceLocation object. We separate the fields by a | """ if value is N...
session - Session for DB operations. saving_classes - class objects that need to be saved e.g. Issue, Run item_counts - map from class name to the number of items, for preallocating id ranges def reserve( self, session: Session, saving_classes: List[Type], item_c...
Here we take input generators and return a dict with issues, preconditions, and postconditions separated. If there is only a single generator file, it's simple. If we also pass in a generator from a previous inputfile then there are a couple extra steps: 1. If an issue was seen in the p...
Uses the absolute line and ignores the callable/character offsets. Used only in determining whether new issues are old issues. def compute_diff_handle(filename, old_line, code): """Uses the absolute line and ignores the callable/character offsets. Used only in determining whether new issues are...
Determine whether we are connected to a capable terminal. def is_capable_terminal(file=sys.stderr) -> bool: """ Determine whether we are connected to a capable terminal. """ if not os.isatty(file.fileno()): return False terminal = os.getenv("TERM", "dumb") # Hardcoded list of non-capabl...
Walk directories upwards from base, until the root directory is reached. At each step, check if the target directory exist, and return it if found. Return None if the search is unsuccessful. def _find_directory_upwards(base: str, target: str) -> Optional[str]: """ Walk directories upwards from base, un...
Compute the set of targets to build for the given targets using a breadth-first traversal. def compute_targets_to_build(self, targets: Iterable[str]) -> Iterable[BuildTarget]: """ Compute the set of targets to build for the given targets using a breadth-first traversal. ...
Compute the set of targets which depend on each target. def compute_reverse_dependencies( self, targets: Iterable[BuildTarget] ) -> Mapping[str, Iterable[BuildTarget]]: """ Compute the set of targets which depend on each target. """ result = defaultdict(list) for...
Consume a key from the configuration. When a key is consumed, it is removed from the configuration. If not found, the default is returned. If the current value is not None, it will be returned instead, but the key will still be considered consumed. def consume(self, key, default=None, ...
Sets the location of the output from the static analysis tool. Parameters: location: str Filesystem location for the results. def analysis_output(self, location: Optional[str] = None) -> None: """Sets the location of the output from the static analysis tool. Parameters: ...
Select an issue. Parameters: issue_instance_id: int id of the issue instance to select Note: We are selecting issue instances, even though the command is called issue. def issue(self, issue_instance_id): """Select an issue. Parameters: issue_instanc...
More details about the selected issue or trace frame. def show(self): """ More details about the selected issue or trace frame. """ self._verify_entrypoint_selected() if self.current_issue_instance_id != -1: self._show_current_issue_instance() return se...
Lists issues for the selected run. Parameters (all optional): use_pager: bool use a unix style pager for output codes: int or list[int] issue codes to filter on callables: str or list[str] callables to filter on (supports wildcards) filen...
Display trace frames independent of the current issue. Parameters (all optional): callers: str or list[str] filter traces by this caller name callees: str or list[str] filter traces by this callee name kind: precondition|postcondition the type of tra...
Move cursor to the next trace frame. def next_cursor_location(self): """Move cursor to the next trace frame. """ self._verify_entrypoint_selected() self.current_trace_frame_index = min( self.current_trace_frame_index + 1, len(self.trace_tuples) - 1 ) self.tra...
Move cursor to the previous trace frame. def prev_cursor_location(self): """Move cursor to the previous trace frame. """ self._verify_entrypoint_selected() self.current_trace_frame_index = max(self.current_trace_frame_index - 1, 0) self.trace()
Jump to a specific trace frame in a trace. Parameters: selected_number: int the trace frame number from trace output def jump(self, selected_number: int) -> None: """Jump to a specific trace frame in a trace. Parameters: selected_number: int the trace frame numbe...
Show and select branches for a branched trace. - [*] signifies the current branch that is selected - will prompt for branch selection if called with no argument - will automatically select a branch if called with an argument Parameters (optional): selected_number: int bra...
Show source code around the current trace frame location. Parameters: context: int number of lines to show above and below trace location (default: 5) def list_source_code(self, context: int = 5) -> None: """Show source code around the current trace frame loc...
Show additional info about the current trace frame. Parameters (all optional): limit: int number of related post/pre conditions to show (pass limit=None to show all) def details( self, *, limit: Optional[int] = 5, kind: Optional[TraceKind] = None ) -> None:...
Buckets together trace frames that have the same caller:caller_port. def _group_trace_frames( self, trace_frames: Iterable[TraceFrameQueryResult], limit: int ) -> Dict[Tuple[str, str], List[TraceFrameQueryResult]]: """Buckets together trace frames that have the same caller:caller_port. """ ...
Finds all trace frames that the given trace_frame flows to. When backwards=True, the result will include the parameter trace_frame, since we are filtering on the parameter's callee. def _next_trace_frames( self, session: Session, trace_frame: TraceFrameQueryResult, visi...
Show the name of the current callable in the trace def callable(self) -> Optional[str]: """Show the name of the current callable in the trace""" if self.current_trace_frame_index != -1: return self._get_callable_from_trace_tuple( self.trace_tuples[self.current_trace_frame_in...
Returns either (caller, caller_port) or (callee, callee_port). def _get_callable_from_trace_tuple( self, trace_tuple: TraceTuple ) -> Tuple[str, str]: """Returns either (caller, caller_port) or (callee, callee_port). """ trace_frame = trace_tuple.trace_frame if trace_tuple.p...
Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand def require_option(current_ctx: click.Context, param_name: str) -> None: """Throw an exception if an option wasn't required. This is useful when its optional in some contexts but...
Try to guess a reasonable database name by looking at the repository path def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]): """Try to guess a reasonable database name by looking at the repository path""" if value: return value if ctx.params["repository"]: r...
Output DB models in a lint-friendly format def lint(click_ctx: click.Context, run_id: int, filenames: List[str]) -> None: """Output DB models in a lint-friendly format""" ctx = click_ctx.obj require_option(click_ctx, "repository") paths = [Path(p).resolve() for p in filenames] root = Path(ctx.repo...
Returns a mapping from absolute source path to absolute output path as specified by the sources object. Files are not guaranteed to exist. def resolve_source_mapping( source_directory: str, output_directory: str, sources: Sources ) -> Mapping[str, str]: """ Returns a mapping from absolute sourc...
Query buck to obtain a mapping from each absolute path to the relative location in the analysis directory. def resolve_relative_paths(paths: List[str]) -> Dict[str, str]: """ Query buck to obtain a mapping from each absolute path to the relative location in the analysis directory. """ ...
Shell out to buck to build the targets, then yield the paths to the link trees. def build(self, targets: Iterable[str]) -> Iterable[str]: """ Shell out to buck to build the targets, then yield the paths to the link trees. """ return generate_source_directorie...
Depending on if an argument has a type, the style for default values changes. E.g. def fun(x=5) def fun(x : int = 5) def _get_parameter_string(self) -> str: """ Depending on if an argument has a type, the style for default values changes. E.g. def fun(x=5) ...
Determines if a stub completely types a function def is_complete(self) -> bool: """ Determines if a stub completely types a function """ if not self.actual: return False for parameter in self.parameters: if parameter["name"] != "self" and not parameter["type"]: ...
We currently ignore nested classes, i.e.: class X: class Y: [ALL OF THIS IS IGNORED] def to_string(self) -> str: """We currently ignore nested classes, i.e.: class X: class Y: [ALL OF THIS IS IGNORED] """ classe...
Download a trained weights, config and preprocessor. Args: url (str): target url. def download(url): """Download a trained weights, config and preprocessor. Args: url (str): target url. """ filepath = get_file(fname='tmp.zip', origin=url, extract=True) base_dir = os.path.dirna...
Loads data and label from a file. Args: filename (str): path to the file. encoding (str): file encoding format. The file format is tab-separated values. A blank line is required at the end of a sentence. For example: ``` EU B-ORG rejects O G...
Loads word vectors in numpy array. Args: embeddings (dict): a dictionary of numpy array. vocab (dict): word_index lookup table. Returns: numpy array: an array of word embeddings. def filter_embeddings(embeddings, vocab, dim): """Loads word vectors in numpy array. Args: ...
Loads GloVe vectors in numpy array. Args: file (str): a path to a glove file. Return: dict: a dict of numpy arrays. def load_glove(file): """Loads GloVe vectors in numpy array. Args: file (str): a path to a glove file. Return: dict: a dict of numpy arrays. ""...
Add token to vocabulary. Args: token (str): token to add. def add_token(self, token): """Add token to vocabulary. Args: token (str): token to add. """ token = self.process_token(token) self._token_count.update([token])
Update dictionary from a collection of documents. Each document is a list of tokens. Args: docs (list): documents to add. def add_documents(self, docs): """Update dictionary from a collection of documents. Each document is a list of tokens. Args: docs (...
Get the list of token_id given doc. Args: doc (list): document. Returns: list: int id of doc. def doc2id(self, doc): """Get the list of token_id given doc. Args: doc (list): document. Returns: list: int id of doc. """ ...
Build vocabulary. def build(self): """ Build vocabulary. """ token_freq = self._token_count.most_common(self._max_size) idx = len(self.vocab) for token, _ in token_freq: self._token2id[token] = idx self._id2token.append(token) idx += 1...
Get the token_id of given token. Args: token (str): token from vocabulary. Returns: int: int id of token. def token_to_id(self, token): """Get the token_id of given token. Args: token (str): token from vocabulary. Returns: int:...
Probability estimates. The returned estimates for all classes are ordered by the label of classes. Args: text : string, the input text. Returns: y : array-like, shape = [num_words, num_classes] Returns the probability of the word for each class in t...
Analyze text and return pretty format. Args: text: string, the input text. Returns: res: dict. Examples: >>> text = 'President Obama is speaking at the White House.' >>> model.analyze(text) { "words": [ ...
Predict using the model. Args: text: string, the input text. Returns: tags: list, shape = (num_words,) Returns predicted values. def predict(self, text): """Predict using the model. Args: text: string, the input text. Returns: ...
Pads nested sequences to the same length. This function transforms a list of list sequences into a 3D Numpy array of shape `(num_samples, max_sent_len, max_word_len)`. Args: sequences: List of lists of lists. dtype: Type of the output sequences. # Returns x: Numpy array. def ...
Learn vocabulary from training set. Args: X : iterable. An iterable which yields either str, unicode or file objects. Returns: self : IndexTransformer. def fit(self, X, y): """Learn vocabulary from training set. Args: X : iterable. An iterable whic...
Transform documents to document ids. Uses the vocabulary learned by fit. Args: X : iterable an iterable which yields either str, unicode or file objects. y : iterabl, label strings. Returns: features: document id matrix. y: label id ...
Learn vocabulary and return document id matrix. This is equivalent to fit followed by transform. Args: X : iterable an iterable which yields either str, unicode or file objects. Returns: list : document id matrix. list: label id matrix. def fit...
Return label strings. Args: y: label id matrix. lengths: sentences length. Returns: list: list of list of strings. def inverse_transform(self, y, lengths=None): """Return label strings. Args: y: label id matrix. lengths: sen...
Transform documents to document ids. Uses the vocabulary learned by fit. Args: X : iterable an iterable which yields either str, unicode or file objects. y : iterabl, label strings. Returns: features: document id matrix. y: label id ...
Trains the model for a fixed number of epochs (iterations on a dataset). Args: x_train: list of training data. y_train: list of training target (label) data. x_valid: list of validation data. y_valid: list of validation target (label) data. batch_size...
Fit the model for a fixed number of epochs. Args: x_train: list of training data. y_train: list of training target (label) data. x_valid: list of validation data. y_valid: list of validation target (label) data. batch_size: Integer. Nu...
Returns the prediction of the model on the given test data. Args: x_test : array-like, shape = (n_samples, sent_length) Test samples. Returns: y_pred : array-like, shape = (n_smaples, sent_length) Prediction labels for x. def predict(self, x_test): ...
Analyze text and return pretty format. Args: text: string, the input text. tokenizer: Tokenize input sentence. Default tokenizer is `str.split`. Returns: res: dict. def analyze(self, text, tokenizer=str.split): """Analyze text and return pretty format. ...