text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _docspec_comments(obj) -> Dict[str, str]: """ Inspect the docstring and get the comments for each parameter. """
# Sometimes our docstring is on the class, and sometimes it's on the initializer, # so we've got to check both. class_docstring = getattr(obj, '__doc__', None) init_docstring = getattr(obj.__init__, '__doc__', None) if hasattr(obj, '__init__') else None docstring = class_docstring or init_docstrin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_config(config: Config, indent: str = "") -> str: """ Pretty-print a config in sort-of-JSON+comments. """
# Add four spaces to the indent. new_indent = indent + " " return "".join([ # opening brace + newline "{\n", # "type": "...", (if present) f'{new_indent}"type": "{config.typ3}",\n' if config.typ3 else '', # render each item "".join...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render(item: ConfigItem, indent: str = "") -> str: """ Render a single config item, with the provided indent """
optional = item.default_value != _NO_DEFAULT if is_configurable(item.annotation): rendered_annotation = f"{item.annotation} (configurable)" else: rendered_annotation = str(item.annotation) rendered_item = "".join([ # rendered_comment, indent, "// " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_to_filename(url: str, etag: str = None) -> str: """ Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to t...
url_bytes = url.encode('utf-8') url_hash = sha256(url_bytes) filename = url_hash.hexdigest() if etag: etag_bytes = etag.encode('utf-8') etag_hash = sha256(etag_bytes) filename += '.' + etag_hash.hexdigest() return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_s3_path(url: str) -> Tuple[str, str]: """Split a full s3 path into the bucket name and path."""
parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError("bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path # Remove '/' at beginning of path. if s3_path.startswith("/"): s3_path = s3_path[1:] return bucket_name, s3_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def s3_request(func: Callable): """ Wrapper function for s3 requests in order to create more helpful error messages. """
@wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if int(exc.response["Error"]["Code"]) == 404: raise FileNotFoundError("file {} not found".format(url)) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def s3_etag(url: str) -> Optional[str]: """Check ETag on S3 object."""
s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def s3_get(url: str, temp_file: IO) -> None: """Pull a file directly from S3."""
s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_from_cache(url: str, cache_dir: str = None) -> str: """ Given a URL, look for the corresponding dataset in the local cache. If it's not there, download it...
if cache_dir is None: cache_dir = CACHE_DIRECTORY os.makedirs(cache_dir, exist_ok=True) # Get eTag to add to filename, if it exists. if url.startswith("s3://"): etag = s3_etag(url) else: response = requests.head(url, allow_redirects=True) if response.status_code !=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_split_sentences(self, texts: List[str]) -> List[List[str]]: """ This method lets you take advantage of spacy's batch processing. Default implementation ...
return [self.split_sentences(text) for text in texts]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_iterator(self, file_path: str) -> Iterator[OntonotesSentence]: """ An iterator over the entire dataset, yielding all sentences processed. """
for conll_file in self.dataset_path_iterator(file_path): yield from self.sentence_iterator(conll_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_path_iterator(file_path: str) -> Iterator[str]: """ An iterator returning file_paths in a directory containing CONLL-formatted files. """
logger.info("Reading CONLL sentences from dataset files at: %s", file_path) for root, _, files in list(os.walk(file_path)): for data_file in files: # These are a relic of the dataset pre-processing. Every # file will be duplicated - one file called filename.g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]: """ An iterator over CONLL formatted files which yields documents, regar...
with codecs.open(file_path, 'r', encoding='utf8') as open_file: conll_rows = [] document: List[OntonotesSentence] = [] for line in open_file: line = line.strip() if line != '' and not line.startswith('#'): # Non-empty line....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]: """ An iterator over the sentences in an individual CONLL formatted file. """
for document in self.dataset_document_iterator(file_path): for sentence in document: yield sentence
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_span_annotations_for_word(annotations: List[str], span_labels: List[List[str]], current_span_labels: List[Optional[str]]) -> None: """ Given a sequen...
for annotation_index, annotation in enumerate(annotations): # strip all bracketing information to # get the actual propbank label. label = annotation.strip("()*") if "(" in annotation: # Entering into a span for a particular semantic role label. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_results_from_args(args: argparse.Namespace): """ Prints results from an ``argparse.Namespace`` object. """
path = args.path metrics_name = args.metrics_filename keys = args.keys results_dict = {} for root, _, files in os.walk(path): if metrics_name in files: full_name = os.path.join(root, metrics_name) metrics = json.load(open(full_name)) results_dict[full_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward(self, input_tensor): # pylint: disable=arguments-differ """ Apply dropout to input tensor. Parameters input_tensor: ``torch.FloatTensor`` A tensor of...
ones = input_tensor.data.new_ones(input_tensor.shape[0], input_tensor.shape[-1]) dropout_mask = torch.nn.functional.dropout(ones, self.p, self.training, inplace=False) if self.inplace: input_tensor *= dropout_mask.unsqueeze(1) return None else: return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unwrap_to_tensors(*tensors: torch.Tensor): """ If you actually passed gradient-tracking Tensors to a Metric, there will be a huge memory leak, because it wil...
return (x.detach().cpu() if isinstance(x, torch.Tensor) else x for x in tensors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_variables(sentence: List[str], sentence_variables: Dict[str, str]) -> Tuple[List[str], List[str]]: """ Replaces abstract variables in text with their ...
tokens = [] tags = [] for token in sentence: if token not in sentence_variables: tokens.append(token) tags.append("O") else: for word in sentence_variables[token].split(): tokens.append(word) tags.append(token) return t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_and_split_sql(sql: str) -> List[str]: """ Cleans up and unifies a SQL query. This involves unifying quoted strings and splitting brackets which aren't f...
sql_tokens: List[str] = [] for token in sql.strip().split(): token = token.replace('"', "'").replace("%", "") if token.endswith("(") and len(token) > 1: sql_tokens.extend(split_table_and_column_names(token[:-1])) sql_tokens.extend(split_table_and_column_names(token[-1]))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_primary_keys_in_schema(sql_tokens: List[str], schema: Dict[str, List[TableColumn]]) -> List[str]: """ Some examples in the text2sql datasets use ID as...
primary_keys_for_tables = {name: max(columns, key=lambda x: x.is_primary_key).name for name, columns in schema.items()} resolved_tokens = [] for i, token in enumerate(sql_tokens): if i > 2: table_name = sql_tokens[i - 2] if token == "ID" and ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_and_run_forward(self, module: Callable[[PackedSequence, Optional[RnnState]], Tuple[Union[PackedSequence, torch.Tensor], RnnState]], inputs: torch.Tensor,...
# In some circumstances you may have sequences of zero length. ``pack_padded_sequence`` # requires all sequence lengths to be > 0, so remove sequences of zero length before # calling self._module, then fill with zeros. # First count how many sequences are empty. batch_size = ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_initial_states(self, batch_size: int, num_valid: int, sorting_indices: torch.LongTensor) -> Optional[RnnState]: """ Returns an initial state for use in a...
# We don't know the state sizes the first time calling forward, # so we let the module define what it's initial hidden state looks like. if self._states is None: return None # Otherwise, we have some previous states. if batch_size > self._states[0].size(1): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_states(self, final_states: RnnStateStorage, restoration_indices: torch.LongTensor) -> None: """ After the RNN has run forward, the states need to be u...
# TODO(Mark): seems weird to sort here, but append zeros in the subclasses. # which way around is best? new_unsorted_states = [state.index_select(1, restoration_indices) for state in final_states] if self._states is None: # We don't already ha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_value(original_string, corenlp_value=None): """Convert the string to Value object. Args: original_string (basestring): Original string corenlp_value (bas...
if isinstance(original_string, Value): # Already a Value return original_string if not corenlp_value: corenlp_value = original_string # Number? amount = NumberValue.parse(corenlp_value) if amount is not None: return NumberValue(amount, original_string) # Date? ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_value_list(original_strings, corenlp_values=None): """Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_valu...
assert isinstance(original_strings, (list, tuple, set)) if corenlp_values is not None: assert isinstance(corenlp_values, (list, tuple, set)) assert len(original_strings) == len(corenlp_values) return list(set(to_value(x, y) for (x, y) in zip(original_strings, cor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_denotation(target_values, predicted_values): """Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values ...
# Check size if len(target_values) != len(predicted_values): return False # Check items for target in target_values: if not any(target.match(pred) for pred in predicted_values): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(text): """Try to parse into a number. Return: the number (int or float) if successful; otherwise None. """
try: return int(text) except ValueError: try: amount = float(text) assert not isnan(amount) and not isinf(amount) return amount except (ValueError, AssertionError): return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(text): """Try to parse into a date. Return: tuple (year, month, date) if successful; otherwise None. """
try: ymd = text.lower().split('-') assert len(ymd) == 3 year = -1 if ymd[0] in ('xx', 'xxxx') else int(ymd[0]) month = -1 if ymd[1] == 'xx' else int(ymd[1]) day = -1 if ymd[2] == 'xx' else int(ymd[2]) assert not year == month == day == -1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward(self, # pylint: disable=arguments-differ sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, s...
raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, initial_state: State, transition_function: TransitionFunction, supervision: SupervisionType) -> Dict[str, torch.Tensor]: """ Takes an initial sta...
raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def state_dict(self) -> Dict[str, Any]: """ Returns the state of the scheduler as a ``dict``. """
return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_state_dict(self, state_dict: Dict[str, Any]) -> None: """ Load the schedulers state. Parameters state_dict : ``Dict[str, Any]`` Scheduler state. Should b...
self.__dict__.update(state_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensemble(subresults: List[Dict[str, torch.Tensor]]) -> torch.Tensor: """ Identifies the best prediction given the results from the submodels. Parameters subre...
# Choose the highest average confidence span. span_start_probs = sum(subresult['span_start_probs'] for subresult in subresults) / len(subresults) span_end_probs = sum(subresult['span_end_probs'] for subresult in subresults) / len(subresults) return get_best_span(span_start_probs.log(), span_end_probs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_weights(self, weight_file: str) -> None: """ Load the pre-trained weights from the file. """
requires_grad = self.requires_grad with h5py.File(cached_path(weight_file), 'r') as fin: for i_layer, lstms in enumerate( zip(self.forward_layers, self.backward_layers) ): for j_direction, lstm in enumerate(lstms): # lstm ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def return_type(self) -> Type: """ Gives the final return type for this function. If the function takes a single argument, this is just ``self.second``. If the fu...
return_type = self.second while isinstance(return_type, ComplexType): return_type = return_type.second return return_type
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def argument_types(self) -> List[Type]: """ Gives the types of all arguments to this function. For functions returning a basic type, we grab all ``.first`` types ...
arguments = [self.first] remaining_type = self.second while isinstance(remaining_type, ComplexType): arguments.append(remaining_type.first) remaining_type = remaining_type.second return arguments
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def substitute_any_type(self, basic_types: Set[BasicType]) -> List[Type]: """ Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this...
substitutions = [] for first_type in substitute_any_type(self.first, basic_types): for second_type in substitute_any_type(self.second, basic_types): substitutions.append(self.__class__(first_type, second_type)) return substitutions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name model: Model, batch_grad_norm: float) -> None: """ Send the mean and std of all par...
if self._should_log_parameter_statistics: # Log parameter values to Tensorboard for name, param in model.named_parameters(): self.add_train_scalar("parameter_mean/" + name, param.data.mean()) self.add_train_scalar("parameter_std/" + name, param.data.std()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_learning_rates(self, model: Model, optimizer: torch.optim.Optimizer): """ Send current parameter specific learning rates to tensorboard """
if self._should_log_learning_rate: # optimizer stores lr info keyed by parameter tensor # we want to log with parameter name names = {param: name for name, param in model.named_parameters()} for group in optimizer.param_groups: if 'lr' not in grou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None: """ Send histograms of parameters to tensorboard. """
for name, param in model.named_parameters(): if name in histogram_parameters: self.add_train_histogram("parameter_histogram/" + name, param)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def align_entities(extracted: List[str], literals: JsonDict, stemmer: NltkPorterStemmer) -> List[str]: """ Use stemming to attempt alignment between extracted wor...
literal_keys = list(literals.keys()) literal_values = list(literals.values()) overlaps = [get_stem_overlaps(extract, literal_values, stemmer) for extract in extracted] worlds = [] for overlap in overlaps: if overlap[0] > overlap[1]: worlds.append(literal_keys[0]) elif ov...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_perspective_match(vector1: torch.Tensor, vector2: torch.Tensor, weight: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Calculate multi-perspect...
assert vector1.size(0) == vector2.size(0) assert weight.size(1) == vector1.size(2) == vector1.size(2) # (batch, seq_len, 1) similarity_single = F.cosine_similarity(vector1, vector2, 2).unsqueeze(2) # (1, 1, num_perspectives, hidden_size) weight = weight.unsqueeze(0).unsqueeze(0) # (batch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_perspective_match_pairwise(vector1: torch.Tensor, vector2: torch.Tensor, weight: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: """ Calculate multi-p...
num_perspectives = weight.size(0) # (1, num_perspectives, 1, hidden_size) weight = weight.unsqueeze(0).unsqueeze(2) # (batch, num_perspectives, seq_len*, hidden_size) vector1 = weight * vector1.unsqueeze(1).expand(-1, num_perspectives, -1, -1) vector2 = weight * vector2.unsqueeze(1).expand(-1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_date_from_utterance(tokenized_utterance: List[Token], year: int = 1993) -> List[datetime]: """ When the year is not explicitly mentioned in the utterance,...
dates = [] utterance = ' '.join([token.text for token in tokenized_utterance]) year_result = re.findall(r'199[0-4]', utterance) if year_result: year = int(year_result[0]) trigrams = ngrams([token.text for token in tokenized_utterance], 3) for month, tens, digit in trigrams: # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_numbers_from_utterance(utterance: str, tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Given an utterance, this function finds all the numb...
# When we use a regex to find numbers or strings, we need a mapping from # the character to which token triggered it. char_offset_to_token_index = {token.idx : token_index for token_index, token in enumerate(tokenized_utterance)} # We want to look up later for each ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def digit_to_query_time(digit: str) -> List[int]: """ Given a digit in the utterance, return a list of the times that it corresponds to. """
if len(digit) > 2: return [int(digit), int(digit) + TWELVE_TO_TWENTY_FOUR] elif int(digit) % 12 == 0: return [0, 1200, 2400] return [int(digit) * HOUR_TO_TWENTY_FOUR, (int(digit) * HOUR_TO_TWENTY_FOUR + TWELVE_TO_TWENTY_FOUR) % HOURS_IN_DAY]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_approximate_times(times: List[int]) -> List[int]: """ Given a list of times that follow a word such as ``about``, we return a list of times that could app...
approximate_times = [] for time in times: hour = int(time/HOUR_TO_TWENTY_FOUR) % 24 minute = time % HOUR_TO_TWENTY_FOUR approximate_time = datetime.now() approximate_time = approximate_time.replace(hour=hour, minute=minute) start_time_range = approximate_time - timedelt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _time_regex_match(regex: str, utterance: str, char_offset_to_token_index: Dict[int, int], map_match_to_query_value: Callable[[str], List[int]], indices_of_app...
linking_scores_dict: Dict[str, List[int]] = defaultdict(list) number_regex = re.compile(regex) for match in number_regex.finditer(utterance): query_values = map_match_to_query_value(match.group()) # If the time appears after a word like ``about`` then we also add # the times that ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _evaluate_sql_query_subprocess(self, predicted_query: str, sql_query_labels: List[str]) -> int: """ We evaluate here whether the predicted query and the query...
postprocessed_predicted_query = self.postprocess_query_sqlite(predicted_query) try: self._cursor.execute(postprocessed_predicted_query) predicted_rows = self._cursor.fetchall() except sqlite3.Error as error: logger.warning(f'Error executing predicted: {erro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_grammar_string(grammar_dictionary: Dict[str, List[str]]) -> str: """ Formats a dictionary of production rules into the string format expected by the Pa...
grammar_string = '\n'.join([f"{nonterminal} = {' / '.join(right_hand_side)}" for nonterminal, right_hand_side in grammar_dictionary.items()]) return grammar_string.replace("\\", "\\\\")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_valid_actions(grammar: Grammar, keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]: """ We initialize the valid actions with the glob...
valid_actions: Dict[str, Set[str]] = defaultdict(set) for key in grammar: rhs = grammar[key] # Sequence represents a series of expressions that match pieces of the text in order. # Eg. A -> B C if isinstance(rhs, Sequence): valid_actions[key].add(format_action(key,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_action(nonterminal: str, right_hand_side: str, is_string: bool = False, is_number: bool = False, keywords_to_uppercase: List[str] = None) -> str: """ T...
keywords_to_uppercase = keywords_to_uppercase or [] if right_hand_side.upper() in keywords_to_uppercase: right_hand_side = right_hand_side.upper() if is_string: return f'{nonterminal} -> ["\'{right_hand_side}\'"]' elif is_number: return f'{nonterminal} -> ["{right_hand_side}"]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_action(self, node: Node) -> None: """ For each node, we accumulate the rules that generated its children in a list. """
if node.expr.name and node.expr.name not in ['ws', 'wsp']: nonterminal = f'{node.expr.name} -> ' if isinstance(node.expr, Literal): right_hand_side = f'["{node.text}"]' else: child_strings = [] for child in node.__iter__(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit(self, node): """ See the ``NodeVisitor`` visit method. This just changes the order in which we visit nonterminals from right to left to left to right. ...
method = getattr(self, 'visit_' + node.expr_name, self.generic_visit) # Call that method, and show where in the tree it failed if it blows # up. try: # Changing this to reverse here! return method(node, [self.visit(child) for child in reversed(list(node))]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]): """ SQL is a predominately variable free language in terms of simple usage, in ...
# Tables in variable free grammars cannot be aliased, so we # remove this functionality from the grammar. grammar_dictionary["select_result"] = ['"*"', '(table_name ws ".*")', 'expr'] # Similarly, collapse the definition of a source table # to not contain aliases and modify references to subqueri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None: """ Variables can be treated as numbers or strings if their type can b...
grammar_dictionary["string_set_vals"] = ['(value ws "," ws string_set_vals)', 'value'] grammar_dictionary["value"].remove('string') grammar_dictionary["value"].remove('number') grammar_dictionary["limit"] = ['("LIMIT" ws "1")', '("LIMIT" ws value)'] grammar_dictionary["expr"][1] = '(value wsp "LIKE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Ensembles don't have vocabularies or weigh...
model_params = config.get('model') # The experiment config tells us how to _train_ a model, including where to get pre-trained # embeddings from. We're now _loading_ the model, so those embeddings will already be # stored in our weights. We don't need any pretrained weight file anymo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infer(self, setup: QuaRelType, answer_0: QuaRelType, answer_1: QuaRelType) -> int: """ Take the question and check if it is compatible with either of the answ...
if self._check_quarels_compatible(setup, answer_0): if self._check_quarels_compatible(setup, answer_1): # Found two answers return -2 else: return 0 elif self._check_quarels_compatible(setup, answer_1): return 1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_app(predictor: Predictor, field_names: List[str] = None, static_dir: str = None, sanitizer: Callable[[JsonDict], JsonDict] = None, title: str = "AllenNLP...
if static_dir is not None: static_dir = os.path.abspath(static_dir) if not os.path.exists(static_dir): logger.error("app directory %s does not exist, aborting", static_dir) sys.exit(-1) elif static_dir is None and field_names is None: print("Neither build_dir nor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _html(title: str, field_names: List[str]) -> str: """ Returns bare bones HTML for serving up an input form with the specified fields that can render predictio...
inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for field_name in field_names) quoted_field_names = [f"'{field_name}'" for field_name in field_names] quoted_field_list = f"[{','.join(quoted_field_names)}]" return _PAGE_TEMPLATE.substitute(title=title, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_valid_actions(self) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]: """ Returns the valid actions in the current grammar state. See the class ...
actions = self._valid_actions[self._nonterminal_stack[-1]] context_actions = [] for type_, variable in self._lambda_stacks: if self._nonterminal_stack[-1] == type_: production_string = f"{type_} -> {variable}" context_actions.append(self._context_acti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign_average_value(self) -> None: """ Replace all the parameter values with the averages. Save the current parameter values to restore later. """
for name, parameter in self._parameters: self._backups[name].copy_(parameter.data) parameter.data.copy_(self._shadows[name])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prune_beam(states: List[State], beam_size: int, sort_states: bool = False) -> List[State]: """ This method can be used to prune the set of unfinished states ...
states_by_batch_index: Dict[int, List[State]] = defaultdict(list) for state in states: assert len(state.batch_indices) == 1 batch_index = state.batch_indices[0] states_by_batch_index[batch_index].append(state) pruned_states = [] for _, instance_states...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]: """ Returns the best finished states for each batch instance bas...
batch_states: Dict[int, List[StateType]] = defaultdict(list) for state in finished_states: batch_states[state.batch_indices[0]].append(state) best_states: Dict[int, List[StateType]] = {} for batch_index, states in batch_states.items(): # The time this sort takes ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_pretrained_embeddings_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Returns and embedd...
file_ext = get_file_extension(file_uri) if file_ext in ['.h5', '.hdf5']: return _read_embeddings_from_hdf5(file_uri, embedding_dim, vocab, namespace) return _read_embeddings_from_text_file(file_uri, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_num_tokens_from_first_line(line: str) -> Optional[int]: """ This function takes in input a string and if it contains 1 or 2 integers, it assumes the larg...
fields = line.split(' ') if 1 <= len(fields) <= 2: try: int_fields = [int(x) for x in fields] except ValueError: return None else: num_tokens = max(int_fields) logger.info('Recognized a header line in th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_predicted_embedding_addition(self, checklist_state: ChecklistStatelet, action_ids: List[int], action_embeddings: torch.Tensor) -> torch.Tensor: """ Gets ...
# Our basic approach here will be to figure out which actions we want to bias, by doing # some fancy indexing work, then multiply the action embeddings by a mask for those # actions, and return the sum of the result. # Shape: (num_terminal_actions, 1). This is 1 if we still want to pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_tensor_dicts(input_queue: Queue, output_queue: Queue, iterator: DataIterator, shuffle: bool, index: int) -> None: """ Pulls at most ``max_instances_in...
def instances() -> Iterator[Instance]: instance = input_queue.get() while instance is not None: yield instance instance = input_queue.get() for tensor_dict in iterator(instances(), num_epochs=1, shuffle=shuffle): output_queue.put(tensor_dict) output_queue.p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _queuer(instances: Iterable[Instance], input_queue: Queue, num_workers: int, num_epochs: Optional[int]) -> None: """ Reads Instances from the iterable and put...
epoch = 0 while num_epochs is None or epoch < num_epochs: epoch += 1 for instance in instances: input_queue.put(instance) # Now put a None for each worker, since each needs to receive one # to know that it's done. for _ in range(num_workers): input_queue.put(No...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]: """ Returns a list of valid actions for each element of the group. "...
return [state.get_valid_actions() for state in self.grammar_state]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _worker(reader: DatasetReader, input_queue: Queue, output_queue: Queue, index: int) -> None: """ A worker that pulls filenames off the input queue, uses the d...
# Keep going until you get a file_path that's None. while True: file_path = input_queue.get() if file_path is None: # Put my index on the queue to signify that I'm finished output_queue.put(index) break logger.info(f"reading instances from {file_path...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]: """ Given labels and a constraint type, returns the allowed transi...
num_labels = len(labels) start_tag = num_labels end_tag = num_labels + 1 labels_with_boundaries = list(labels.items()) + [(start_tag, "START"), (end_tag, "END")] allowed = [] for from_label_index, from_label in labels_with_boundaries: if from_label in ("START", "END"): from...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_transition_allowed(constraint_type: str, from_tag: str, from_entity: str, to_tag: str, to_entity: str): """ Given a constraint type and strings ``from_tag...
# pylint: disable=too-many-return-statements if to_tag == "START" or from_tag == "END": # Cannot transition into START or from END return False if constraint_type == "BIOUL": if from_tag == "START": return to_tag in ('O', 'B', 'U') if to_tag == "END": ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def viterbi_tags(self, logits: torch.Tensor, mask: torch.Tensor) -> List[Tuple[List[int], float]]: """ Uses viterbi algorithm to find most likely tags for the giv...
_, max_seq_length, num_tags = logits.size() # Get the tensors out of the variables logits, mask = logits.data, mask.data # Augment transitions matrix with start and end transitions start_tag = num_tags end_tag = num_tags + 1 transitions = torch.Tensor(num_tags ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def takes_arg(obj, arg: str) -> bool: """ Checks whether the provided obj takes a certain arg. If it's a class, we're really checking whether its constructor does...
if inspect.isclass(obj): signature = inspect.signature(obj.__init__) elif inspect.ismethod(obj) or inspect.isfunction(obj): signature = inspect.signature(obj) else: raise ConfigurationError(f"object {obj} is not callable") return arg in signature.parameters
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_kwargs(cls: Type[T], params: Params, **extras) -> Dict[str, Any]: """ Given some class, a `Params` object, and potentially other keyword arguments, cre...
# Get the signature of the constructor. signature = inspect.signature(cls.__init__) kwargs: Dict[str, Any] = {} # Iterate over all the constructor parameters and their annotations. for name, param in signature.parameters.items(): # Skip "self". You're not *required* to call the first param...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def take_step(self, state: StateType, max_actions: int = None, allowed_actions: List[Set] = None) -> List[StateType]: """ The main method in the ``TransitionFunct...
raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_sentence(sentence_blob: str) -> Tuple[List[Dict[str, str]], List[Tuple[int, int]], List[str]]: """ Parses a chunk of text in the SemEval SDP format. Eac...
annotated_sentence = [] arc_indices = [] arc_tags = [] predicates = [] lines = [line.split("\t") for line in sentence_blob.split("\n") if line and not line.strip().startswith("#")] for line_idx, line in enumerate(lines): annotated_token = {k:v for k, v in zip(FIELDS, line)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]: """ Disambiguates single GPU and multiple GPU settings for cuda_device pa...
def from_list(strings): if len(strings) > 1: return [int(d) for d in strings] elif len(strings) == 1: return int(strings[0]) else: return -1 if isinstance(cuda_device, str): return from_list(re.split(r',\s*', cuda_device)) elif isinstance...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_epoch_number(batch: Batch, epoch: int) -> Batch: """ Add the epoch number to the batch instances as a MetadataField. """
for instance in batch.instances: instance.fields['epoch_num'] = MetadataField(epoch) return batch
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _take_instances(self, instances: Iterable[Instance], max_instances: Optional[int] = None) -> Iterator[Instance]: """ Take the next `max_instances` instances f...
# If max_instances isn't specified, just iterate once over the whole dataset if max_instances is None: yield from iter(instances) else: # If we don't have a cursor for this dataset, create one. We use ``id()`` # for the key because ``instances`` could be a li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _memory_sized_lists(self, instances: Iterable[Instance]) -> Iterable[List[Instance]]: """ Breaks the dataset into "memory-sized" lists of instances, which it ...
lazy = is_lazy(instances) # Get an iterator over the next epoch worth of instances. iterator = self._take_instances(instances, self._instances_per_epoch) # We have four different cases to deal with: # With lazy instances and no guidance about how many to load into memory, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_batch_is_sufficiently_small( self, batch_instances: Iterable[Instance], excess: Deque[Instance]) -> List[List[Instance]]: """ If self._maximum_samples...
if self._maximum_samples_per_batch is None: assert not excess return [list(batch_instances)] key, limit = self._maximum_samples_per_batch batches: List[List[Instance]] = [] batch: List[Instance] = [] padding_length = -1 excess.extend(batch_inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]: """ This method should return one epoch worth of batches. """
raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = None, dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tenso...
d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: scores = scores.masked_fill(mask == 0, -1e9) p_attn = F.softmax(scores, dim=-1) if dropout is not None: p_attn = dropout(p_attn) return torch.matmul(p_attn, value), p_a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor: """Mask out subsequent positions."""
mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0) return mask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor: """Apply residual connection to any sublayer with the same s...
return x + self.dropout(sublayer(self.norm(x)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block_orthogonal(tensor: torch.Tensor, split_sizes: List[int], gain: float = 1.0) -> None: """ An initializer which allows initializing model parameters in "b...
data = tensor.data sizes = list(tensor.size()) if any([a % b != 0 for a, b in zip(sizes, split_sizes)]): raise ConfigurationError("tensor dimensions must be divisible by their respective " "split_sizes. Found size: {} and split_sizes: {}".format(sizes, split_sizes))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lstm_hidden_bias(tensor: torch.Tensor) -> None: """ Initialize the biases of the forget gate to 1, and all other gates to 0, following Jozefowicz et al., An E...
# gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size) tensor.data.zero_() hidden_size = tensor.shape[0] // 4 tensor.data[hidden_size:(2 * hidden_size)] = 1.0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _should_split_column_cells(cls, column_cells: List[str]) -> bool: """ Returns true if there is any cell in this column that can be split. """
return any(cls._should_split_cell(cell_text) for cell_text in column_cells)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _should_split_cell(cls, cell_text: str) -> bool: """ Checks whether the cell should be split. We're just doing the same thing that SEMPRE did here. """
if ', ' in cell_text or '\n' in cell_text or '/' in cell_text: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_linked_agenda_items(self) -> List[str]: """ Returns entities that can be linked to spans in the question, that should be in the agenda, for training a cov...
agenda_items: List[str] = [] for entity in self._get_longest_span_matching_entities(): agenda_items.append(entity) # If the entity is a cell, we need to add the column to the agenda as well, # because the answer most likely involves getting the row with the cell. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_predicate(ex: Extraction) -> Extraction: """ Ensure single word predicate by adding "before-predicate" and "after-predicate" arguments. """
rel_toks = ex.toks[char_to_word_index(ex.rel.span[0], ex.sent) \ : char_to_word_index(ex.rel.span[1], ex.sent) + 1] if not rel_toks: return ex verb_inds = [tok_ind for (tok_ind, tok) in enumerate(rel_toks) if tok.tag_.startswith('VB')] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extraction_to_conll(ex: Extraction) -> List[str]: """ Return a conll representation of a given input Extraction. """
ex = split_predicate(ex) toks = ex.sent.split(' ') ret = ['*'] * len(toks) args = [ex.arg1] + ex.args2 rels_and_args = [("ARG{}".format(arg_ind), arg) for arg_ind, arg in enumerate(args)] + \ [(rel_part.elem_type, rel_part) for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpret_element(element_type: str, text: str, span: str) -> Element: """ Construct an Element instance from regexp groups. """
return Element(element_type, interpret_span(span), text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_sent_to_conll(sent_ls: List[Extraction]): """ Given a list of extractions for a single sentence - convert it to conll representation. """
# Sanity check - make sure all extractions are on the same sentence assert(len(set([ex.sent for ex in sent_ls])) == 1) toks = sent_ls[0].sent.split(' ') return safe_zip(*[range(len(toks)), toks] + \ [extraction_to_conll(ex) for ex in sent_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad_line_to_ontonotes(line, domain) -> List[str]: """ Pad line to conform to ontonotes representation. """
word_ind, word = line[ : 2] pos = 'XX' oie_tags = line[2 : ] line_num = 0 parse = "-" lemma = "-" return [domain, line_num, word_ind, word, pos, parse, lemma, '-',\ '-', '-', '*'] + list(oie_tags) + ['-', ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_sent_dict_to_conll(sent_dic, domain) -> str: """ Given a dictionary from sentence -> extractions, return a corresponding CoNLL representation. """
return '\n\n'.join(['\n'.join(['\t'.join(map(str, pad_line_to_ontonotes(line, domain))) for line in convert_sent_to_conll(sent_ls)]) for sent_ls in sent_dic.iteritems()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_s3_uri(uri): """Parses a S3 Uri into a dictionary of the Bucket, Key, and VersionId :return: a BodyS3Location dict or None if not an S3 Uri :rtype: dic...
if not isinstance(uri, string_types): return None url = urlparse(uri) query = parse_qs(url.query) if url.scheme == 's3' and url.netloc and url.path: s3_pointer = { 'Bucket': url.netloc, 'Key': url.path.lstrip('/') } if 'versionId' in query and l...