Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_hours_for_week(self, week_start=None): week_start = week_start if week_start else self.week_start week_end = week_start + relativedelta(days=7) return ProjectHours.objects.filter( week_start__gte=week_start, week_start__l...
[ "\n Gets all ProjectHours entries in the 7-day period beginning on\n week_start.\n " ]
Please provide a description of the function:def get_users_from_project_hours(self, project_hours): name = ('user__first_name', 'user__last_name') users = project_hours.values_list('user__id', *name).distinct()\ .order_by(*name) return users
[ "\n Gets a list of the distinct users included in the project hours\n entries, ordered by name.\n " ]
Please provide a description of the function:def check_all(self, all_entries, *args, **kwargs): all_overlaps = 0 while True: try: user_entries = all_entries.next() except StopIteration: return all_overlaps else: ...
[ "\n Go through lists of entries, find overlaps among each, return the total\n " ]
Please provide a description of the function:def check_entry(self, entries, *args, **kwargs): verbosity = kwargs.get('verbosity', 1) user_total_overlaps = 0 user = '' for index_a, entry_a in enumerate(entries): # Show the name the first time through if in...
[ "\n With a list of entries, check each entry against every other\n " ]
Please provide a description of the function:def find_start(self, **kwargs): week = kwargs.get('week', False) month = kwargs.get('month', False) year = kwargs.get('year', False) days = kwargs.get('days', 0) # If no flags are True, set to the beginning of last billing win...
[ "\n Determine the starting point of the query using CLI keyword arguments\n " ]
Please provide a description of the function:def find_users(self, *args): if args: names = reduce(lambda query, arg: query | (Q(first_name__icontains=arg) | Q(last_name__icontains=arg)), args, Q()) # noqa users = User.objects.filter(names) ...
[ "\n Returns the users to search given names as args.\n Return all users if there are no args provided.\n " ]
Please provide a description of the function:def find_entries(self, users, start, *args, **kwargs): forever = kwargs.get('all', False) for user in users: if forever: entries = Entry.objects.filter(user=user).order_by('start_time') else: en...
[ "\n Find all entries for all users, from a given starting point.\n If no starting point is provided, all entries are returned.\n " ]
Please provide a description of the function:def cbv_decorator(function_decorator): def class_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View return class_decorator
[ "Allows a function-based decorator to be used on a CBV." ]
Please provide a description of the function:def date_totals(entries, by): date_dict = {} for date, date_entries in groupby(entries, lambda x: x['date']): if isinstance(date, datetime.datetime): date = date.date() d_entries = list(date_entries) if by == 'user': ...
[ "Yield a user's name and a dictionary of their hours" ]
Please provide a description of the function:def get_project_totals(entries, date_headers, hour_type=None, overtime=False, total_column=False, by='user'): totals = [0 for date in date_headers] rows = [] for thing, thing_entries in groupby(entries, lambda x: x[by]): name, ...
[ "\n Yield hour totals grouped by user and date. Optionally including overtime.\n " ]
Please provide a description of the function:def get_payroll_totals(month_work_entries, month_leave_entries): def _get_user_info(entries): fname = entries[0].get('user__first_name', '') if entries else '' lname = entries[0].get('user__last_name', '') if entries else '' name = '...
[ "Summarizes monthly work and leave totals, grouped by user.\n\n Returns (labels, rows).\n labels -> {'billable': [proj_labels], 'nonbillable': [proj_labels]}\n rows -> [{\n name: name of user,\n billable, nonbillable, leave: [\n {'hours': hours for label, 'perce...
Please provide a description of the function:def validate(self, validation_instances, metrics, iteration=None): ''' Evaluate this model on `validation_instances` during training and output a report. :param validation_instances: The data to use to validate the model. :type valida...
[]
Please provide a description of the function:def score(self, eval_instances, verbosity=0): ''' Return scores (negative log likelihoods) assigned to each testing instance in `eval_instances`. :param eval_instances: The data to use to evaluate the model. Instances should have ...
[]
Please provide a description of the function:def predict_and_score(self, eval_instances, random=False, verbosity=0): ''' Return most likely outputs and scores for the particular set of outputs given in `eval_instances`, as a tuple. Return value should be equivalent to the default impleme...
[]
Please provide a description of the function:def load(self, infile): ''' Deserialize a model from a stored file. By default, unpickle an entire object. If `dump` is overridden to use a different storage format, `load` should be as well. :param file outfile: A file-like object f...
[]
Please provide a description of the function:def iter_batches(iterable, batch_size): ''' Given a sequence or iterable, yield batches from that iterable until it runs out. Note that this function returns a generator, and also each batch will be a generator. :param iterable: The sequence or iterable ...
[]
Please provide a description of the function:def gen_batches(iterable, batch_size): ''' Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns ...
[]
Please provide a description of the function:def sized_imap(func, iterable, strict=False): ''' Return an iterable whose elements are the result of applying the callable `func` to each element of `iterable`. If `iterable` has a `len()`, then the iterable returned by this function will have the same `len(...
[]
Please provide a description of the function:def stripped(self, include_annotated=True): ''' Return a version of this instance with all information removed that could be used to "cheat" at test time: the true output and its annotated version, and the reference to the full source. ...
[]
Please provide a description of the function:def inverted(self): ''' Return a version of this instance with inputs replaced by outputs and vice versa. ''' return Instance(input=self.output, output=self.input, annotated_input=self.annotated_output, ...
[]
Please provide a description of the function:def get_data_or_download(dir_name, file_name, url='', size='unknown'): dname = os.path.join(stanza.DATA_DIR, dir_name) fname = os.path.join(dname, file_name) if not os.path.isdir(dname): assert url, 'Could not locate data {}, and url was not specifie...
[ "Returns the data. if the data hasn't been downloaded, then first download the data.\n\n :param dir_name: directory to look in\n :param file_name: file name to retrieve\n :param url: if the file is not found, then download it from this url\n :param size: the expected size\n :return: path to the reque...
Please provide a description of the function:def add(self, word, count=1): if word not in self: super(Vocab, self).__setitem__(word, len(self)) self._counts[word] += count return self[word]
[ "Add a word to the vocabulary and return its index.\n\n :param word: word to add to the dictionary.\n\n :param count: how many times to add the word.\n\n :return: index of the added word.\n\n WARNING: this function assumes that if the Vocab currently has N words, then\n there is a...
Please provide a description of the function:def subset(self, words): v = self.__class__(unk=self._unk) unique = lambda seq: len(set(seq)) == len(seq) assert unique(words) for w in words: if w in self: v.add(w, count=self.count(w)) return v
[ "Get a new Vocab containing only the specified subset of words.\n\n If w is in words, but not in the original vocab, it will NOT be in the subset vocab.\n Indices will be in the order of `words`. Counts from the original vocab are preserved.\n\n :return (Vocab): a new Vocab object\n " ]
Please provide a description of the function:def _index2word(self): # TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable compute_index2word = lambda: self.keys() # this works because self is an OrderedDict # create if it doesn't e...
[ "Mapping from indices to words.\n\n WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab.\n\n :return: a list of strings\n " ]
Please provide a description of the function:def prune_rares(self, cutoff=2): keep = lambda w: self.count(w) >= cutoff or w == self._unk return self.subset([w for w in self if keep(w)])
[ "\n returns a **new** `Vocab` object that is similar to this one but with rare words removed.\n Note that the indices in the new `Vocab` will be remapped (because rare words will have been removed).\n\n :param cutoff: words occuring less than this number of times are removed from the vocabulary...
Please provide a description of the function:def sort_by_decreasing_count(self): words = [w for w, ct in self._counts.most_common()] v = self.subset(words) return v
[ "Return a **new** `Vocab` object that is ordered by decreasing count.\n\n The word at index 1 will be most common, the word at index 2 will be\n next most common, and so on.\n\n :return: A new vocabulary sorted by decreasing count.\n\n NOTE: UNK will remain at index 0, regardless of its ...
Please provide a description of the function:def from_dict(cls, word2index, unk, counts=None): try: if word2index[unk] != 0: raise ValueError('unk must be assigned index 0') except KeyError: raise ValueError('word2index must have an entry for unk.') ...
[ "Create Vocab from an existing string to integer dictionary.\n\n All counts are set to 0.\n\n :param word2index: a dictionary representing a bijection from N words to the integers 0 through N-1.\n UNK must be assigned the 0 index.\n\n :param unk: the string representing unk in wo...
Please provide a description of the function:def to_file(self, f): for word in self._index2word: count = self._counts[word] f.write(u'{}\t{}\n'.format(word, count).encode('utf-8'))
[ "Write vocab to a file.\n\n :param (file) f: a file object, e.g. as returned by calling `open`\n\n File format:\n word0<TAB>count0\n word1<TAB>count1\n ...\n\n word with index 0 is on the 0th line and so on...\n " ]
Please provide a description of the function:def from_file(cls, f): word2index = {} counts = Counter() for i, line in enumerate(f): word, count_str = line.split('\t') word = word.decode('utf-8') word2index[word] = i counts[word] = float(co...
[ "Load vocab from a file.\n\n :param (file) f: a file object, e.g. as returned by calling `open`\n :return: a vocab object. The 0th line of the file is assigned to index 0, and so on...\n " ]
Please provide a description of the function:def backfill_unk_emb(self, E, filled_words): unk_emb = E[self[self._unk]] for i, word in enumerate(self): if word not in filled_words: E[i] = unk_emb
[ " Backfills an embedding matrix with the embedding for the unknown token.\n\n :param E: original embedding matrix of dimensions `(vocab_size, emb_dim)`.\n :param filled_words: these words will not be backfilled with unk.\n\n NOTE: this function is for internal use.\n " ]
Please provide a description of the function:def get_embeddings(self, rand=None, dtype='float32'): rand = rand if rand else lambda shape: np.random.uniform(-0.1, 0.1, size=shape) embeddings = get_data_or_download('senna', 'embeddings.txt', self.embeddings_url) words = get_data_or_downlo...
[ "\n Retrieves the embeddings for the vocabulary.\n\n :param rand: Random initialization function for out-of-vocabulary words. Defaults to `np.random.uniform(-0.1, 0.1, size=shape)`.\n :param dtype: Type of the matrix.\n :return: embeddings corresponding to the vocab instance.\n\n ...
Please provide a description of the function:def get_embeddings(self, rand=None, dtype='float32', corpus='common_crawl_48', n_dim=300): assert corpus in self.settings, '{} not in supported corpus {}'.format(corpus, self.settings.keys()) self.n_dim, self.corpus, self.setting = n_dim, corpus, sel...
[ "\n Retrieves the embeddings for the vocabulary.\n\n :param rand: Random initialization function for out-of-vocabulary words. Defaults to `np.random.uniform(-0.1, 0.1, size=shape)`.\n :param dtype: Type of the matrix.\n :param corpus: Corpus to use. Please see `GloveVocab.settings` for a...
Please provide a description of the function:def to_unicode(s): if not isinstance(s, six.string_types): raise ValueError("{} must be str or unicode.".format(s)) if not isinstance(s, six.text_type): s = six.text_type(s, 'utf-8') return s
[ "Return the object as unicode (only matters for Python 2.x).\n\n If s is already Unicode, return s as is.\n Otherwise, assume that s is UTF-8 encoded, and convert to Unicode.\n\n :param (basestring) s: a str, unicode or other basestring object\n :return (unicode): the object as unicode\n " ]
Please provide a description of the function:def best_gpu(max_usage=USAGE_THRESHOLD, verbose=False): ''' Return the name of a device to use, either 'cpu' or 'gpu0', 'gpu1',... The least-used GPU with usage under the constant threshold will be chosen; ties are broken randomly. ''' try: pr...
[]
Please provide a description of the function:def parse_bytes(field): ''' >>> parse_bytes('24B') 24.0 >>> parse_bytes('4MiB') 4194304.0 ''' if field[-1] in 'bB': field = field[:-1] try: for i, prefix in enumerate('KMGTPEZ'): if field.endswith(prefix + 'i'): ...
[]
Please provide a description of the function:def bind_theano(device=None, max_usage=USAGE_THRESHOLD, verbose=True): ''' Initialize Theano to use a certain device. If `device` is None (the default), use the device returned by calling `best_gpu` with the same parameters. This needs to be called *befo...
[]
Please provide a description of the function:def evaluate(learner, eval_data, metrics, metric_names=None, split_id=None, write_data=False): ''' Evaluate `learner` on the instances in `eval_data` according to each metric in `metric`, and return a dictionary summarizing the values of the metr...
[]
Please provide a description of the function:def json2pb(pb, js, useFieldNumber=False): ''' convert JSON string to google.protobuf.descriptor instance ''' for field in pb.DESCRIPTOR.fields: if useFieldNumber: key = field.number else: key = field.name if key not in...
[]
Please provide a description of the function:def pb2json(pb, useFieldNumber=False): ''' convert google.protobuf.descriptor instance to JSON string ''' js = {} # fields = pb.DESCRIPTOR.fields #all fields fields = pb.ListFields() #only filled (including extensions) for field,value in fields: ...
[]
Please provide a description of the function:def modified_ngram_precision(references, pred, n): ''' Borrowed from the ntlk BLEU implementation: http://www.nltk.org/_modules/nltk/translate/bleu_score.html >>> modified_ngram_precision([['the', 'fat', 'cat', 'the', 'rat']], ... ...
[]
Please provide a description of the function:def closest_length(refs, pred): ''' >>> closest_length(['1234', '12345', '1'], '123') 4 >>> closest_length(['123', '12345', '1'], '12') 1 ''' smallest_diff = float('inf') closest_length = float('inf') for ref in refs: diff = abs(le...
[]
Please provide a description of the function:def _request(self, text, properties, retries=0): text = to_unicode(text) # ensures unicode try: r = requests.post(self.server, params={'properties': str(properties)}, data=text.encode('utf-8')) r.raise_for_status() ...
[ "Send a request to the CoreNLP server.\n\n :param (str | unicode) text: raw text for the CoreNLPServer to parse\n :param (dict) properties: properties that the server expects\n :return: request result\n " ]
Please provide a description of the function:def annotate_json(self, text, annotators=None): # WARN(chaganty): I'd like to deprecate this function -- we # should just use annotate().json #properties = { # 'annotators': ','.join(annotators or self.default_annotators), ...
[ "Return a JSON dict from the CoreNLP server, containing annotations of the text.\n\n :param (str) text: Text to annotate.\n :param (list[str]) annotators: a list of annotator names\n\n :return (dict): a dict of annotations\n " ]
Please provide a description of the function:def annotate_proto(self, text, annotators=None): properties = { 'annotators': ','.join(annotators or self.default_annotators), 'outputFormat': 'serialized', 'serializer': 'edu.stanford.nlp.pipeline.ProtobufAnnotationSerial...
[ "Return a Document protocol buffer from the CoreNLP server, containing annotations of the text.\n\n :param (str) text: text to be annotated\n :param (list[str]) annotators: a list of annotator names\n\n :return (CoreNLP_pb2.Document): a Document protocol buffer\n " ]
Please provide a description of the function:def annotate(self, text, annotators=None): doc_pb = self.annotate_proto(text, annotators) return AnnotatedDocument.from_pb(doc_pb)
[ "Return an AnnotatedDocument from the CoreNLP server.\n\n :param (str) text: text to be annotated\n :param (list[str]) annotators: a list of annotator names\n\n See a list of valid annotator names here:\n http://stanfordnlp.github.io/CoreNLP/annotators.html\n\n :return (Annotate...
Please provide a description of the function:def from_pb(cls, pb): obj = cls._from_pb(pb) obj._pb = pb return obj
[ "Instantiate the object from a protocol buffer.\n\n Args:\n pb (protobuf)\n\n Save a reference to the protocol buffer on the object.\n " ]
Please provide a description of the function:def from_tokens(cls, text, toks): sentence_pb = CoreNLP_pb2.Sentence() sentence_pb.characterOffsetBegin = 0 sentence_pb.characterOffsetEnd = len(text) sentence_pb.sentenceIndex = 0 sentence_pb.tokenOffsetBegin = 0 sent...
[ "\n A helper method that allows you to construct an AnnotatedSentence with just token information:\n :param (str) text -- full text of the sentence.\n :param (list[str]) toks -- tokens\n " ]
Please provide a description of the function:def depparse(self, mode="enhancedPlusPlus"): assert mode in [ "basic", "alternative", "collapsedCCProcessed", "collapsed", "enhanced", "enhancedPlusPlus", ], "Invalid mode" dep_p...
[ "\n Retrieves the appropriate dependency parse.\n Must be one of:\n - basic\n - alternative\n - collapsedCCProcessed\n - collapsed\n - enhanced\n - enhancedPlusPlus\n " ]
Please provide a description of the function:def to_json(self): edges = [] for root in self.roots: edges.append({ 'governer': 0, 'dep': "root", 'dependent': root+1, 'governergloss': "root", 'dependentglo...
[ "\n Represented as a list of edges:\n dependent: index of child\n dep: dependency label\n governer: index of parent\n dependentgloss: gloss of parent\n governergloss: gloss of parent\n " ]
Please provide a description of the function:def character_span(self): begin, end = self.token_span return (self.sentence[begin].character_span[0], self.sentence[end-1].character_span[-1])
[ "\n Returns the character span of the token\n " ]
Please provide a description of the function:def log_proto(self, proto, step_num): self.summ_writer.add_summary(proto, step_num) return proto
[ "Log a Summary protobuf to the event file.\n\n :param proto: a Summary protobuf\n :param step_num: the iteration number at which this value was logged\n " ]
Please provide a description of the function:def log(self, key, val, step_num): try: ph, summ = self.summaries[key] except KeyError: # if we haven't defined a variable for this key, define one with self.g.as_default(): ph = tf.placeholder(tf.f...
[ "Directly log a scalar value to the event file.\n\n :param string key: a name for the value\n :param val: a float\n :param step_num: the iteration number at which this value was logged\n " ]
Please provide a description of the function:def unescape_sql(inp): if inp.startswith('"') and inp.endswith('"'): inp = inp[1:-1] return inp.replace('""','"').replace('\\\\','\\')
[ "\n :param inp: an input string to be unescaped\n :return: return the unescaped version of the string.\n " ]
Please provide a description of the function:def parse_psql_array(inp): inp = unescape_sql(inp) # Strip '{' and '}' if inp.startswith("{") and inp.endswith("}"): inp = inp[1:-1] lst = [] elem = "" in_quotes, escaped = False, False for ch in inp: if escaped: ...
[ "\n :param inp: a string encoding an array\n :return: the array of elements as represented by the input\n " ]
Please provide a description of the function:def save(self, fname): with open(fname, 'wb') as f: json.dump(self, f)
[ " Saves the dictionary in json format\n :param fname: file to save to\n " ]
Please provide a description of the function:def load(cls, fname): with open(fname) as f: return Config(**json.load(f))
[ " Loads the dictionary from json file\n :param fname: file to load from\n :return: loaded dictionary\n " ]
Please provide a description of the function:def read_events(stream): ''' Read and return as a generator a sequence of Event protos from file-like object `stream`. ''' header_size = struct.calcsize('<QI') len_size = struct.calcsize('<Q') footer_size = struct.calcsize('<I') while True: ...
[]
Please provide a description of the function:def write_events(stream, events): ''' Write a sequence of Event protos to file-like object `stream`. ''' for event in events: data = event.SerializeToString() len_field = struct.pack('<Q', len(data)) len_crc = struct.pack('<I', masked_...
[]
Please provide a description of the function:def log_image(self, step, tag, val): ''' Write an image event. :param int step: Time step (x-axis in TensorBoard graphs) :param str tag: Label for this value :param numpy.ndarray val: Image in RGB format with values from 0...
[]
Please provide a description of the function:def log_scalar(self, step, tag, val): ''' Write a scalar event. :param int step: Time step (x-axis in TensorBoard graphs) :param str tag: Label for this value :param float val: Scalar to graph at this time step (y-axis) ''' ...
[]
Please provide a description of the function:def log_histogram(self, step, tag, val): ''' Write a histogram event. :param int step: Time step (x-axis in TensorBoard graphs) :param str tag: Label for this value :param numpy.ndarray val: Arbitrary-dimensional array containing ...
[]
Please provide a description of the function:def flush(self): ''' Force all queued events to be written to the events file. The queue will automatically be flushed at regular time intervals, when it grows too large, and at program exit (with the usual caveats of `atexit`: this wo...
[]
Please provide a description of the function:def options(allow_partial=False, read=False): ''' Get the object containing the values of the parsed command line options. :param bool allow_partial: If `True`, ignore unrecognized arguments and allow the options to be re-parsed next time `options` is ca...
[]
Please provide a description of the function:def mkdirp(dirname, overwrite=True): ''' Create a directory at the path given by `dirname`, if it doesn't already exist. If `overwrite` is False, raise an error when trying to create a directory that already has a config.json file in it. Otherwise do noth...
[]
Please provide a description of the function:def inner_products(self, vec): products = self.array.dot(vec) return self._word_to_score(np.arange(len(products)), products)
[ "Get the inner product of a vector with every embedding.\n\n :param (np.array) vector: the query vector\n\n :return (list[tuple[str, float]]): a map of embeddings to inner products\n " ]
Please provide a description of the function:def _word_to_score(self, ids, scores): # should be 1-D vectors assert len(ids.shape) == 1 assert ids.shape == scores.shape w2s = {} for i in range(len(ids)): w2s[self.vocab.index2word(ids[i])] = scores[i] ...
[ "Return a map from each word to its score.\n\n :param (np.array) ids: a vector of word ids\n :param (np.array) scores: a vector of scores\n\n :return (dict[unicode, float]): a map from each word (unicode) to its score (float)\n " ]
Please provide a description of the function:def k_nearest(self, vec, k): nbr_score_pairs = self.inner_products(vec) return sorted(nbr_score_pairs.items(), key=lambda x: x[1], reverse=True)[:k]
[ "Get the k nearest neighbors of a vector (in terms of highest inner products).\n\n :param (np.array) vec: query vector\n :param (int) k: number of top neighbors to return\n\n :return (list[tuple[str, float]]): a list of (word, score) pairs, in descending order\n " ]
Please provide a description of the function:def _init_lsh_forest(self): import sklearn.neighbors lshf = sklearn.neighbors.LSHForest() lshf.fit(self.array) return lshf
[ "Construct an LSH forest for nearest neighbor search." ]
Please provide a description of the function:def k_nearest_approx(self, vec, k): if not hasattr(self, 'lshf'): self.lshf = self._init_lsh_forest() # TODO(kelvin): make this inner product score, to be consistent with k_nearest distances, neighbors = self.lshf.kneighbors([vec...
[ "Get the k nearest neighbors of a vector (in terms of cosine similarity).\n\n :param (np.array) vec: query vector\n :param (int) k: number of top neighbors to return\n\n :return (list[tuple[str, float]]): a list of (word, cosine similarity) pairs, in descending order\n " ]
Please provide a description of the function:def to_dict(self): d = {} for word, idx in self.vocab.iteritems(): d[word] = self.array[idx].tolist() return d
[ "Convert to dictionary.\n\n :return (dict): A dict mapping from strings to vectors.\n " ]
Please provide a description of the function:def to_files(self, array_file, vocab_file): logging.info('Writing array...') np.save(array_file, self.array) logging.info('Writing vocab...') self.vocab.to_file(vocab_file)
[ "Write the embedding matrix and the vocab to files.\n\n :param (file) array_file: file to write array to\n :param (file) vocab_file: file to write vocab to\n " ]
Please provide a description of the function:def from_files(cls, array_file, vocab_file): logging.info('Loading array...') array = np.load(array_file) logging.info('Loading vocab...') vocab = Vocab.from_file(vocab_file) return cls(array, vocab)
[ "Load the embedding matrix and the vocab from files.\n\n :param (file) array_file: file to read array from\n :param (file) vocab_file: file to read vocab from\n\n :return (Embeddings): an Embeddings object\n " ]
Please provide a description of the function:def to_file_path(self, path_prefix): with self._path_prefix_to_files(path_prefix, 'w') as (array_file, vocab_file): self.to_files(array_file, vocab_file)
[ "Write the embedding matrix and the vocab to <path_prefix>.npy and <path_prefix>.vocab.\n\n :param (str) path_prefix: path prefix of the saved files\n " ]
Please provide a description of the function:def from_file_path(cls, path_prefix): with cls._path_prefix_to_files(path_prefix, 'r') as (array_file, vocab_file): return cls.from_files(array_file, vocab_file)
[ "Load the embedding matrix and the vocab from <path_prefix>.npy and <path_prefix>.vocab.\n\n :param (str) path_prefix: path prefix of the saved files\n " ]
Please provide a description of the function:def get_uuids(): result = shell('cl ls -w {} -u'.format(worksheet)) uuids = result.split('\n') uuids = uuids[1:-1] # trim non uuids return uuids
[ "List all bundle UUIDs in the worksheet." ]
Please provide a description of the function:def open_file(uuid, path): # create temporary file just so we can get an unused file path f = tempfile.NamedTemporaryFile() f.close() # close and delete right away fname = f.name # download file to temporary path cmd ='cl down -o {} -w {...
[ "Get the raw file content within a particular bundle at a particular path.\n\n Path have no leading slash.\n " ]
Please provide a description of the function:def launch_job(job_name, cmd=None, code_dir=None, excludes='*.ipynb .git .ipynb_checkpoints', dependencies=tuple(), queue='john', image='codalab/python', memory='18g', debug=False, tail=False): print 'Remember to set up S...
[ "Launch a job on CodaLab (optionally upload code that the job depends on).\n\n Args:\n job_name: name of the job\n cmd: command to execute\n code_dir: path to code folder. If None, no code is uploaded.\n excludes: file types to exclude from the upload\n dependencies: list of ot...
Please provide a description of the function:def load_img(self, img_path): with open_file(self.uuid, img_path) as f: return mpimg.imread(f)
[ "\n Return an image object that can be immediately plotted with matplotlib\n " ]
Please provide a description of the function:def slope(self): x = range(self.window_size) y = self.vals slope, bias = np.polyfit(x, y, 1) return slope
[ "\n :return: the esitmated slope for points in the current window\n " ]
Please provide a description of the function:def output_results(results, split_id='results', output_stream=None): ''' Log `results` readably to `output_stream`, with a header containing `split_id`. :param results: a dictionary of summary statistics from an evaluation :type results: dict(str -> obje...
[]
Please provide a description of the function:def labels_to_onehots(labels, num_classes): batch_size = labels.get_shape().as_list()[0] with tf.name_scope("one_hot"): labels = tf.expand_dims(labels, 1) indices = tf.expand_dims(tf.range(0, batch_size, 1), 1) sparse_ptrs = tf.concat(1,...
[ "Convert a vector of integer class labels to a matrix of one-hot target vectors.\n\n :param labels: a vector of integer labels, 0 to num_classes. Has shape (batch_size,).\n :param num_classes: the total number of classes\n :return: has shape (batch_size, num_classes)\n " ]
Please provide a description of the function:def start_task(self, name, size): ''' Add a task to the stack. If, for example, `name` is `'Iteration'` and `size` is 10, progress on that task will be shown as ..., Iteration <p> of 10, ... :param str name: A descriptive name fo...
[]
Please provide a description of the function:def progress(self, p): ''' Update the current progress on the task at the top of the stack. :param int p: The current subtask number, between 0 and `size` (passed to `start_task`), inclusive. ''' self.task_stack[-1] = self...
[]
Please provide a description of the function:def end_task(self): ''' Remove the current task from the stack. ''' self.progress(self.task_stack[-1].size) self.task_stack.pop()
[]
Please provide a description of the function:def progress_report(self, force=False): ''' Print the current progress. :param bool force: If `True`, print the report regardless of the elapsed time since the last progress report. ''' now = datetime.datetime.now() ...
[]
Please provide a description of the function:def fraction_done(self, start=0.0, finish=1.0, stack=None): ''' :return float: The estimated fraction of the overall task hierarchy that has been finished. A number in the range [0.0, 1.0]. ''' if stack is None: stack =...
[]
Please provide a description of the function:def load_conll(cls, fname): def process_cache(cache, fields): cache = [l.split() for l in cache if l] if not cache: return None fields['label'].append(cache[0][0]) instance = {k: [] for k in fie...
[ "\n The CONLL file must have a tab delimited header, for example::\n\n # description tags\n Alice\n Hello t1\n my t2\n name t3\n is t4\n alice t5\n\n Bob\n I'm t1\n bob t2\...
Please provide a description of the function:def write_conll(self, fname): if 'label' not in self.fields: raise InvalidFieldsException("dataset is not in CONLL format: missing label field") def instance_to_conll(inst): tab = [v for k, v in inst.items() if k != 'label'] ...
[ "\n Serializes the dataset in CONLL format to fname\n " ]
Please provide a description of the function:def convert(self, converters, in_place=False): dataset = self if in_place else self.__class__(OrderedDict([(name, data[:]) for name, data in self.fields.items()])) for name, convert in converters.items(): if name not in self.fields.keys()...
[ "\n Applies transformations to the dataset.\n\n :param converters: A dictionary specifying the function to apply to each field. If a field is missing from the dictionary, then it will not be transformed.\n\n :param in_place: Whether to perform the transformation in place or create a new dataset...
Please provide a description of the function:def shuffle(self): order = range(len(self)) random.shuffle(order) for name, data in self.fields.items(): reindexed = [] for _, i in enumerate(order): reindexed.append(data[i]) self.fields[na...
[ "\n Re-indexes the dataset in random order\n\n :return: the shuffled dataset instance\n " ]
Please provide a description of the function:def copy(self, keep_fields=None): keep_fields = self.fields.keys() or keep_fields return self.__class__(OrderedDict([(name, data[:]) for name, data in self.fields.items() if name in keep_fields]))
[ "\n :param keep_fields: if specified, then only the given fields will be kept\n :return: A deep copy of the dataset (each instance is copied).\n " ]
Please provide a description of the function:def pad(cls, sequences, padding, pad_len=None): max_len = max([len(s) for s in sequences]) pad_len = pad_len or max_len assert pad_len >= max_len, 'pad_len {} must be greater or equal to the longest sequence {}'.format(pad_len, max_len) ...
[ "\n Pads a list of sequences such that they form a matrix.\n\n :param sequences: a list of sequences of varying lengths.\n :param padding: the value of padded cells.\n :param pad_len: the length of the maximum padded sequence.\n " ]
Please provide a description of the function:def log_likelihood_bits(eval_data, predictions, scores, learner='ignored'): ''' Return the log likelihood of each correct output in base 2 (bits), computed from the scores in `scores` (which should be in base e, nats). >>> bits = log_likelihood_bits(None, No...
[]
Please provide a description of the function:def accuracy(eval_data, predictions, scores='ignored', learner='ignored'): ''' Return the accuracy of each prediction in `predictions`: 1 if it is equal to the correct output in `eval_data`, 0 otherwise. >>> data = [Instance('input', 'correct'), ... ...
[]
Please provide a description of the function:def prec1(eval_data, predictions, scores='ignored', learner='ignored'): ''' Return the precision@1 of each prediction in `predictions`: 1 if it is equal to any of the correct outputs for the corresponding instance in `eval_data`, 0 otherwise. >>> data = ...
[]
Please provide a description of the function:def bleu(eval_data, predictions, scores='ignored', learner='ignored'): ''' Return corpus-level BLEU score of `predictions` using the `output` field of the instances in `eval_data` as references. This is returned as a length-1 list of floats. This uses th...
[]
Please provide a description of the function:def _has_4gram_match(ref, pred): ''' >>> _has_4gram_match(['four', 'lovely', 'tokens', 'here'], ... ['four', 'lovely', 'tokens', 'here']) True >>> _has_4gram_match(['four', 'lovely', 'tokens', 'here'], ... ['four', 'l...
[]
Please provide a description of the function:def squared_error(eval_data, predictions, scores='ignored', learner='ignored'): ''' Return the squared error of each prediction in `predictions` with respect to the correct output in `eval_data`. >>> data = [Instance('input', (0., 0., 1.)), ... I...
[]
Please provide a description of the function:def perplexity(eval_data, predictions, scores, learner='ignored'): ''' Return the perplexity `exp(-score)` computed from each score in `scores`. The log scores in `scores` should be base e (`exp`, `log`). The correct average to use for this metric is the geo...
[]
Please provide a description of the function:def token_perplexity_macro(eval_data, predictions, scores, learner='ignored'): ''' Return the per-token perplexity `exp(-score / num_tokens)` computed from each score in `scores.` The correct macro-average is given by the geometric mean. >>> refs = [Ins...
[]