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 fit(self, data, labels, **kwargs): """\ Training the SOM on the the data and calibrate itself. After the training, `self.quant_error` and `self.topog_error` ...
# train the network self._som.train(data, **kwargs) # retrieve first and second bmus and distances bmus, q_error, t_error = self.bmus_with_errors(data) # set errors measures of training data self.quant_error = q_error self.topog_error = t_error # store tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calibrate(self, data, labels): """\ Calibrate the network using `self._bmus`. """
# network calibration classifier = defaultdict(Counter) for (i,j), label in zip(self._bmus, labels): classifier[i,j][label] += 1 self.classifier = {} for ij, cnt in classifier.items(): maxi = max(cnt.items(), key=itemgetter(1)) nb = sum(cnt.va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, data, unkown=None): """\ Classify data according to previous calibration. :param data: sparse input matrix (ideal dtype is `numpy.float32`) :ty...
assert self.classifier is not None, 'not calibrated' bmus = self._som.bmus(data) return self._predict_from_bmus(bmus, unkown)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit_predict(self, data, labels, unkown=None): """\ Fit and classify data efficiently. :param data: sparse input matrix (ideal dtype is `numpy.float32`) :type...
self.fit(data, labels) return self._predict_from_bmus(self._bmus, unkown)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def histogram(self, bmus=None): """\ Return a 2D histogram of bmus. :param bmus: the best-match units indexes for underlying data. :type bmus: :class:`numpy.ndar...
if bmus is None: assert self._bmus is not None, 'not trained' bmus = self._bmus arr = np.zeros((self._som.nrows, self._som.ncols)) for i,j in bmus: arr[i,j] += 1 return arr
<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_protocol_version(protocol=None, target=None): """ Return a suitable pickle protocol version for a given target. Arguments: target: The internals descript...
target = get_py_internals(target) if protocol is None: protocol = target['pickle_default_protocol'] if protocol > cPickle.HIGHEST_PROTOCOL: warnings.warn('Downgrading pickle protocol, running python supports up to %d.' % cPickle.HIGHEST_PROTOCOL) protocol = cPickle.HIGHEST_PROTOC...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_opcodes(code_obj, target): """ Very crude inter-python version opcode translator. Raises SyntaxError when the opcode doesn't exist in the destinati...
target = get_py_internals(target) src_ops = code_obj.disassemble() dst_opmap = target['opmap'] dst_ops = [] op_iter = enumerate(src_ops) for i, op in op_iter: if isinstance(op, pwnypack.bytecode.Label): dst_ops.append(op) continue if op.name not in ds...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stops(self): """Return stops served by this route."""
serves = set() for trip in self.trips(): for stop_time in trip.stop_times(): serves |= stop_time.stops() return serves
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def P(value, bits=None, endian=None, target=None): """ Pack an unsigned pointer for a given target. Args: value(int): The value to pack. bits(:class:`~pwnypack....
return globals()['P%d' % _get_bits(bits, target)](value, endian=endian, target=target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def p(value, bits=None, endian=None, target=None): """ Pack a signed pointer for a given target. Args: value(int): The value to pack. bits(:class:`pwnypack.targ...
return globals()['p%d' % _get_bits(bits, target)](value, endian=endian, target=target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def U(data, bits=None, endian=None, target=None): """ Unpack an unsigned pointer for a given target. Args: data(bytes): The data to unpack. bits(:class:`pwnypac...
return globals()['U%d' % _get_bits(bits, target)](data, endian=endian, target=target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def u(data, bits=None, endian=None, target=None): """ Unpack a signed pointer for a given target. Args: data(bytes): The data to unpack. bits(:class:`pwnypack.t...
return globals()['u%d' % _get_bits(bits, target)](data, endian=endian, target=target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trips(self): """Return all trips for this agency."""
trips = set() for route in self.routes(): trips |= route.trips() return trips
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stops(self): """Return all stops visited by trips for this agency."""
stops = set() for stop_time in self.stop_times(): stops |= stop_time.stops() return stops
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_times(self): """Return all stop_times for this agency."""
stop_times = set() for trip in self.trips(): stop_times |= trip.stop_times() return stop_times
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def localize_fields(cls, localized_fields): """ For each field name in localized_fields, for each language in settings.LANGUAGES, add fields to cls, and remove t...
# never do this twice if hasattr(cls, 'localized_fields'): return cls # MSGID_LANGUAGE is the language that is used for the gettext message id's. # If it is not available, because the site isn't using subsites, the # LANGUAGE_CODE is good too. MSGID_LANGUAGE gives the opportunity to #...
<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_labels(self): """ Read the label file of the documents and extract all the labels Returns: An array of labels.Label objects """
labels = [] try: with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), 'r') as file_desc: for line in file_desc.readlines(): line = line.strip() (label_name, label_color) = line.split(",", 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 __set_labels(self, labels): """ Add a label on the document. """
with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), 'w') \ as file_desc: for label in labels: file_desc.write("%s,%s\n" % (label.name, label.get_color_str()))
<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_label(self, old_label, new_label): """ Update a label Replace 'old_label' by 'new_label' """
logger.info("%s : Updating label ([%s] -> [%s])" % (str(self), old_label.name, new_label.name)) labels = self.labels try: labels.remove(old_label) except ValueError: # this document doesn't have this label return logger.in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __doc_cmp(self, other): """ Comparison function. Can be used to sort docs alphabetically. """
if other is None: return -1 if self.is_new and other.is_new: return 0 if self.__docid < other.__docid: return -1 elif self.__docid == other.__docid: return 0 else: 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 arff_to_orange_table(arff): ''' Convert a string in arff format to an Orange table. :param arff: string in arff format :return: Orange data table object constructed from the arff string :rtype: orange.ExampleTable ''' with tempfile.NamedTemporaryFile(suffix='.arff', delete=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_to_string(self, obj): """This descriptor acts as a Field, as far as the serializer is concerned."""
try: return force_unicode(self.__get__(obj)) except TypeError: return str(self.__get__(obj))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poify(self, model): """turn a django model into a po file."""
if not hasattr(model, 'localized_fields'): return None # create po stream with header po_stream = polibext.PoStream(StringIO.StringIO(self.po_header)).parse() for (name, field) in easymode.tree.introspection.get_default_field_descriptors(model): occurrence = u"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xgettext(self, template): """Extracts to be translated strings from template and turns it into po format."""
cmd = 'xgettext -d django -L Python --keyword=gettext_noop \ --keyword=gettext_lazy --keyword=ngettext_lazy:1,2 --from-code=UTF-8 \ --output=- -' p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def msgmerge(self, locale_file, po_string): """ Runs msgmerge on a locale_file and po_string """
cmd = "msgmerge -q %s -" % locale_file p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (msg, err) = p.communicate(input=po_string) if err: # dont raise exception, some stuff in stderr are just warming...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def msguniq(self, locale_file): """ run msgunique on the locale_file """
# group related language strings together. # except if no real entries where written or the header will be removed. p = subprocess.Popen('msguniq --to-code=utf-8 %s' % (locale_file,), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) (msg, err) = p.communicate() ...
<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_utf8(obj): """Walks a simple data structure, converting unicode to byte string. Supports lists, tuples, and dictionaries. """
if isinstance(obj, unicode_type): return _utf8(obj) elif isinstance(obj, dict): return dict((to_utf8(k), to_utf8(v)) for (k, v) in obj.items()) elif isinstance(obj, list): return list(to_utf8(i) for i in obj) elif isinstance(obj, tuple): return tuple(to_utf8(i) for i in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setPostScript(self, goal, script): """ After learning call the given script using 'goal'. :param goal: goal name :param script: prolog script to call """
self.postGoal = goal self.postScript = script
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def induce(self, mode, pos, neg, b, filestem='default', printOutput=False): """ Induce a theory or features in 'mode'. :param filestem: The base name of this exp...
# Write the inputs to appropriate files. self.__prepare(filestem, pos, neg, b) # Make a script to run aleph (with appropriate settings). self.__script(mode, filestem) logger.info("Running aleph...") dumpFile = None if not printOutput: dumpFile = te...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __script(self, mode, filestem): """ Makes the script file to be run by yap. """
scriptPath = '%s/%s' % (self.tmpdir, Aleph.SCRIPT) script = open(scriptPath, 'w') # Permit the owner to execute and read this script os.chmod(scriptPath, S_IREAD | S_IEXEC) cat = lambda x: script.write(x + '\n') cat(":- initialization(run_aleph).") cat("run_ale...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw(request): """shows untransformed hierarchical xml output"""
foos = foobar_models.Foo.objects.all() return HttpResponse(tree.xml(foos), mimetype='text/xml')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chain(request): """shows how the XmlQuerySetChain can be used instead of @toxml decorator"""
bars = foobar_models.Bar.objects.all() bazs = foobar_models.Baz.objects.all() qsc = XmlQuerySetChain(bars, bazs) return HttpResponse(tree.xml(qsc), mimetype='text/xml')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xslt(request): """Shows xml output transformed with standard xslt"""
foos = foobar_models.Foo.objects.all() return render_xslt_to_response('xslt/model-to-xml.xsl', foos, mimetype='text/xml')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def label_contours(self, intervals, window=150, hop=30): """ In a very flowy contour, it is not trivial to say which pitch value corresponds to what interval. Th...
window /= 1000.0 hop /= 1000.0 exposure = int(window / hop) boundary = window - hop final_index = utils.find_nearest_index(self.pitch_obj.timestamps, self.pitch_obj.timestamps[-1] - boundary) interval = np.median(np.diff(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_contour_labels(self, new_fig=True): """ Plots the labelled contours! """
timestamps = [] pitch = [] if new_fig: p.figure() for interval, contours in self.contour_labels.items(): for contour in contours: x = self.pitch_obj.timestamps[contour[0]:contour[1]] y = [interval]*len(x) timestamp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wordify_example(name_to_table, connecting_tables, context, cached_sentences, index_by_value, target_table_name, word_att_length, data_name, ex, searched_conne...
debug = False data_name = str(data_name) if debug: print("======================================") print("example:", ex) print("table name:", data_name) print("searched_connections:", len(searched_connections), searched_connections) print("connecting_tables:", len(c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, num_of_processes=multiprocessing.cpu_count()): """ Applies the wordification methodology on the target table :param num_of_processes: number of pro...
# class + wordification on every example of the main table p = multiprocessing.Pool(num_of_processes) indices = chunks(list(range(len(self.target_table))), num_of_processes) # ) for ex_idxs in indices: self.resulting_documents.extend(wordify_examples(self.name_to_table,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_weights(self, measure='tfidf'): """ Counts word frequency and calculates tf-idf values for words in every document. :param measure: example weights...
from math import log # TODO replace with spipy matrices (and calculate with scikit) if measure == 'tfidf': self.calculate_idf() for doc_idx, document in enumerate(self.resulting_documents): train_word_count = defaultdict(int) self.tf_idfs[doc_idx] ...
<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_arff(self): ''' Returns the "wordified" representation in ARFF. :rtype: str ''' arff_string = "@RELATION " + self.target_table.name + "\n\n" words = set() for document in self.resulting_documents: for word in document: words...
<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(self, minimum_word_frequency_percentage=1): """ Filter out words that occur less than minimum_word_frequency times. :param minimum_word_frequency_perce...
pruned_resulting_documents = [] for document in self.resulting_documents: new_document = [] for word in document: if self.word_in_how_many_documents[word] >= minimum_word_frequency_percentage / 100. * len( self.resulting_documents): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wordify(self): """ Constructs string of all documents. :return: document representation of the dataset, one line per document :rtype: str """
string_documents = [] for klass, document in zip(self.resulting_classes, self.resulting_documents): string_documents.append("!" + str(klass) + " " + '' .join(document)) return '\n'.join(string_documents)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def binary_value_or_stdin(value): """ Return fsencoded value or read raw data from stdin if value is None. """
if value is None: reader = io.open(sys.stdin.fileno(), mode='rb', closefd=False) return reader.read() elif six.PY3: return os.fsencode(value) else: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __label_cmp(self, other): """ Comparaison function. Can be used to sort labels alphabetically. """
if other is None: return -1 label_name = strip_accents(self.name).lower() other_name = strip_accents(other.name).lower() if label_name < other_name: return -1 elif label_name == other_name: return 0 else: 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 get_html_color(self): """ get a string representing the color, using HTML notation """
color = self.color return ("#%02x%02x%02x" % ( int(color.red), int(color.green), int(color.blue) ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forget(self, label_name): """ Forget training for label 'label_name' """
self._bayes.pop(label_name) baye_dir = self._get_baye_dir(label_name) logger.info("Deleting label training {} : {}".format( label_name, baye_dir )) rm_rf(baye_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename(self, old_label_name, new_label_name): """ Take into account that a label has been renamed """
assert(old_label_name != new_label_name) self._bayes.pop(old_label_name) old_baye_dir = self._get_baye_dir(old_label_name) new_baye_dir = self._get_baye_dir(new_label_name) logger.info("Renaming label training {} -> {} : {} -> {}".format( old_label_name, new_label_na...
<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_filepath(self, ext): """ Returns a file path relative to this page """
filename = ("%s%d.%s" % (self.FILE_PREFIX, self.page_nb + 1, ext)) return self.fs.join(self.doc.path, 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 __make_thumbnail(self, width, height): """ Create the page's thumbnail """
(w, h) = self.size factor = max( (float(w) / width), (float(h) / height) ) w /= factor h /= factor return self.get_image((round(w), round(h)))
<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_thumbnail(self, width, height): """ thumbnail with a memory cache """
# get from the file thumb_path = self._get_thumb_path() try: doc_file_path = self.get_doc_file_path() if (self.fs.exists(thumb_path) and self.fs.getmtime(doc_file_path) < self.fs.getmtime(thumb_path)): with self.fs...
<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_keywords(self): """ Get all the keywords related of this page Returns: An array of strings """
txt = self.text for line in txt: for word in split_words(line): yield(word)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_accents(string): """ Strip all the accents from the string """
return u''.join( (character for character in unicodedata.normalize('NFD', string) if unicodedata.category(character) != 'Mn'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rm_rf(path): """ Act as 'rm -rf' in the shell """
if os.path.isfile(path): os.unlink(path) elif os.path.isdir(path): for root, dirs, files in os.walk(path, topdown=False): for filename in files: filepath = os.path.join(root, filename) logger.info("Deleting file %s" % filepath) os.unli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def surface2image(surface): """ Convert a cairo surface into a PIL image """
# TODO(Jflesch): Python 3 problem # cairo.ImageSurface.get_data() raises NotImplementedYet ... # import PIL.ImageDraw # # if surface is None: # return None # dimension = (surface.get_width(), surface.get_height()) # img = PIL.Image.frombuffer("RGBA", dimension, # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image2surface(img): """ Convert a PIL image into a Cairo surface """
if not CAIRO_AVAILABLE: raise Exception("Cairo not available(). image2surface() cannot work.") # TODO(Jflesch): Python 3 problem # cairo.ImageSurface.create_for_data() raises NotImplementedYet ... # img.putalpha(256) # (width, height) = img.size # imgd = img.tobytes('raw', 'BGRA') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def domain_map(features, feature_format, train_context, test_context, intervals={}, format='arff', positive_class=None): ''' Use the features returned by a propositionalization method to map unseen test examples into the new feature space. :param features:...
<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_text(self): """ Get the text corresponding to this page """
boxes = self.boxes txt = [] for line in boxes: txt_line = u"" for box in line.word_boxes: txt_line += u" " + box.content txt.append(txt_line) return txt
<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_img(self): """ Returns an image object corresponding to the page """
with self.fs.open(self.__img_path, 'rb') as fd: img = PIL.Image.open(fd) img.load() return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_index(self, offset=0): """ Move the page number by a given offset. Beware to not let any hole in the page numbers when doing this. Make sure also that...
src = {} src["box"] = self.__get_box_path() src["img"] = self.__get_img_path() src["thumb"] = self._get_thumb_path() page_nb = self.page_nb page_nb += offset logger.info("--> Moving page %d (+%d) to index %d" % (self.page_nb, offset, page_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 destroy(self): """ Delete the page. May delete the whole document if it's actually the last page. """
logger.info("Destroying page: %s" % self) if self.doc.nb_pages <= 1: self.doc.destroy() return doc_pages = self.doc.pages[:] current_doc_nb_pages = self.doc.nb_pages paths = [ self.__get_box_path(), self.__get_img_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 pclink(self, parent, child): """Create a parent-child relationship."""
if parent._children is None: parent._children = set() if child._parents is None: child._parents = set() parent._children.add(child) child._parents.add(parent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discretize(self, intervals, slope_thresh=1500, cents_thresh=50): """ This function takes the pitch data and returns it quantized to given set of intervals. A...
#eps = np.finfo(float).eps #pitch = median_filter(pitch, 7)+eps self.pitch = median_filter(self.pitch, 7) pitch_quantized = np.zeros(len(self.pitch)) pitch_quantized[0] = utils.find_nearest_index(intervals, self.pitch[0]) pitch_quantized[-1] = utils.find_nearest_index(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assume(self, other): """ Assume the identity of another target. This can be useful to make the global target assume the identity of an ELF executable. Argume...
self._arch = other._arch self._bits = other._bits self._endian = other._endian self._mode = other._mode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_read_permission(self, request, path): """ Just return True if the user is an authenticated staff member. Extensions could base the permissions on the pat...
user = request.user if not user.is_authenticated(): return False elif user.is_superuser: return True elif user.is_staff: return True else: 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 rows(self, table, cols): ''' Fetches rows from the local cache or from the db if there's no cache. :param table: table name to select :cols: list of columns to select :return: list of rows :rtype: list ''' if self.orng_tables: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def select_where(self, table, cols, pk_att, pk): ''' SELECT with WHERE clause. :param table: target table :param cols: list of columns to select :param pk_att: attribute for the where clause :param pk: the id that the pk_att should match :retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode(string): """ Encode the given string as an OID. '5.104.101.108.108.111' """
result=".".join([ str(ord(s)) for s in string ]) return "%s." % (len(string)) + result
<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(self,oid): """Return snmp value for the given OID."""
try: self.lock.acquire() if oid not in self.data: return "NONE" else: return self.base_oid + oid + '\n' + self.data[oid]['type'] + '\n' + str(self.data[oid]['value']) finally: self.lock.release()
<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_next(self,oid): """Return snmp value for the next OID."""
try: # Nested try..except because of Python 2.4 self.lock.acquire() try: # remove trailing zeroes from the oid while len(oid) > 0 and oid[-2:] == ".0" and oid not in self.data: oid = oid[:-2]; return self.get(self.data_idx[self.data_idx.index(oid)+1]) except ValueError: # Not found: try...
<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_first(self): """Return snmp value for the first OID."""
try: # Nested try..except because of Python 2.4 self.lock.acquire() try: return self.get(self.data_idx[0]) except (IndexError, ValueError): return "NONE" finally: self.lock.release()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cut_oid(self,full_oid): """ Remove the base OID from the given string. '28.12' """
if not full_oid.startswith(self.base_oid.rstrip('.')): return None else: return full_oid[len(self.base_oid):]
<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_oid_entry(self, oid, type, value, label=None): """General function to add an oid entry to the MIB subtree."""
if self.debug: print('DEBUG: %s %s %s %s'%(oid,type,value,label)) item={'type': str(type), 'value': str(value)} if label is not None: item['label']=str(label) self.pending[oid]=item
<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_oid(self,oid,value,label=None): """Short helper to add an object ID value to the MIB subtree."""
self.add_oid_entry(oid,'OBJECTID',value,label=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 add_int(self,oid,value,label=None): """Short helper to add an integer value to the MIB subtree."""
self.add_oid_entry(oid,'INTEGER',value,label=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 add_oct(self,oid,value,label=None): """Short helper to add an octet value to the MIB subtree."""
self.add_oid_entry(oid,'OCTET',value,label=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 add_str(self,oid,value,label=None): """Short helper to add a string value to the MIB subtree."""
self.add_oid_entry(oid,'STRING',value,label=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 add_ip(self,oid,value,label=None): """Short helper to add an IP address value to the MIB subtree."""
self.add_oid_entry(oid,'IPADDRESS',value,label=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 add_cnt_32bit(self,oid,value,label=None): """Short helper to add a 32 bit counter value to the MIB subtree."""
# Truncate integer to 32bits ma,x self.add_oid_entry(oid,'Counter32',int(value)%4294967296,label=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 add_cnt_64bit(self,oid,value,label=None): """Short helper to add a 64 bit counter value to the MIB subtree."""
# Truncate integer to 64bits ma,x self.add_oid_entry(oid,'Counter64',int(value)%18446744073709551615,label=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 add_gau(self,oid,value,label=None): """Short helper to add a gauge value to the MIB subtree."""
self.add_oid_entry(oid,'GAUGE',value,label=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 add_tt(self,oid,value,label=None): """Short helper to add a timeticks value to the MIB subtree."""
self.add_oid_entry(oid,'TIMETICKS',value,label=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 main_passpersist(self): """ Main function that handle SNMP's pass_persist protocol, called by the start method. Direct call is unnecessary. """
line = sys.stdin.readline().strip() if not line: raise EOFError() if 'PING' in line: print("PONG") elif 'getnext' in line: oid = self.cut_oid(sys.stdin.readline().strip()) if oid is None: print("NONE") elif oid == "": # Fallback to the first entry print(self.get_first()) 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 main_update(self): """ Main function called by the updater thread. Direct call is unnecessary. """
# Renice updater thread to limit overload try: os.nice(1) except AttributeError as er: pass # os.nice is not available on windows time.sleep(self.refresh) try: while True: # We pick a timestamp to take in account the time used by update() timestamp=time.time() # Update data with user's...
<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_setter(self, oid): """ Retrieve the nearest parent setter function for an OID """
if hasattr(self.setter, oid): return self.setter[oid] parents = [ poid for poid in list(self.setter.keys()) if oid.startswith(poid) ] if parents: return self.setter[max(parents)] return self.default_setter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, oid, typevalue): """ Call the default or user setter function if available """
success = False type_ = typevalue.split()[0] value = typevalue.lstrip(type_).strip().strip('"') ret_value = self.get_setter(oid)(oid, type_, value) if ret_value: if ret_value in ErrorValues or ret_value == 'DONE': print(ret_value) elif ret_value == True: print('DONE') elif ret_value == 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 start(self, user_func, refresh): """ Start the SNMP's protocol handler and the updater thread user_func is a reference to an update function, ran every...
self.update=user_func self.refresh=refresh self.error=None # First load self.update() self.commit() # Start updater thread up = threading.Thread(None,self.main_update,"Updater") up.daemon = True up.start() # Main loop while up.isAlive(): # Do not serve data if the Updater thread has died ...
<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_members_of_type(obj, member_type): """ Finds members of a certain type in obj. :param obj: A model instance or class. :param member_type: The type of th...
if not issubclass(type(obj), ModelBase): obj = obj.__class__ key_hash = [] for key in dir(obj): try: attr = getattr(obj, key) except AttributeError as e: try: attr = obj.__dict__[key] except KeyError: raise Attrib...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """ Provide the next element of the list. """
if self.idx >= len(self.page_list): raise StopIteration() page = self.page_list[self.idx] self.idx += 1 return page
<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_nb_pages(self): """ Compute the number of pages in the document. It basically counts how many JPG files there are in the document. """
try: filelist = self.fs.listdir(self.path) count = 0 for filepath in filelist: filename = self.fs.basename(filepath) if (filename[-4:].lower() != "." + ImgPage.EXT_IMG or (filename[-10:].lower() == "." + ImgPage.EXT_THUMB) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def steal_page(self, page): """ Steal a page from another document """
if page.doc == self: return self.fs.mkdir_p(self.path) new_page = ImgPage(self, self.nb_pages) logger.info("%s --> %s" % (str(page), str(new_page))) new_page._steal_content(page)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recursion_depth(key): """ A context manager used to guard recursion depth for some function. Multiple functions can be kept separately because it will be cou...
try: if not getattr(RECURSION_LEVEL_DICT, 'key', False): RECURSION_LEVEL_DICT.key = 0 RECURSION_LEVEL_DICT.key += 1 yield RECURSION_LEVEL_DICT.key RECURSION_LEVEL_DICT.key -= 1 except Exception as e: RECURSION_LEVEL_DICT.key = 0 raise e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def first_match(predicate, lst): """ returns the first value of predicate applied to list, which does not return None 4 :param predicate: a function that returns...
for item in lst: val = predicate(item) if val is not None: return val 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 bases_walker(cls): """ Loop through all bases of cls True True :param cls: The class in which we want to loop through the base classes. """
for base in cls.__bases__: yield base for more in bases_walker(base): yield more
<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_add_params(url, **kwargs): """ Add parameters to an url 'http://example.com/?a=1&b=3' 'http://example.com/?c=8&a=1&b=3' 'http://example.com/?a=1&b=3#/iro...
parsed_url = urlparse.urlsplit(url) params = urlparse.parse_qsl(parsed_url.query) parsed_url = list(parsed_url) for pair in kwargs.iteritems(): params.append(pair) parsed_url[3] = urllib.urlencode(params) return urlparse.urlunsplit(parsed_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self, cleanup=True, printOutput=False): ''' Runs TreeLiker with the given settings. :param cleanup: deletes temporary files after completion :param printOutput: print algorithm output to the terminal ''' self._copy_data() self._batch() du...
<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(self): ''' Creates the batch file to run the experiment. ''' self.batch = '%s/%s.treeliker' % (self.tmpdir, self.basename) commands = [] if not self.test_dataset: commands.append('set(output_type, single)') commands.append("set(examples...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterread(self, table): """Iteratively read data from a GTFS table. Returns namedtuples."""
self.log('Reading: %s'%table) # Entity class cls = self.FACTORIES[table] f = self._open(table) # csv reader if unicodecsv: data = unicodecsv.reader(f, encoding='utf-8-sig') else: data = csv.reader(f) header = data.next() headerlen = len(header) ent = collections.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 write(self, filename, entities, sortkey=None, columns=None): """Write entities out to filename in csv format. Note: this doesn't write directly into a Zip ar...
if os.path.exists(filename): raise IOError('File exists: %s'%filename) # Make sure we have all the entities loaded. if sortkey: entities = sorted(entities, key=lambda x:x[sortkey]) if not columns: columns = set() for entity in entities: columns |= set(entity.keys()) ...
<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_zip(self, filename, files=None, path=None, clone=None, compress=True): """Create a Zip archive. Provide any of the following: files - A list of files pa...
if filename and os.path.exists(filename): raise IOError('File exists: %s'%filename) files = files or [] arcnames = [] if path and os.path.isdir(path): files += glob.glob(os.path.join(path, '*.txt')) if compress: compress_level = zipfile.ZIP_DEFLATED else: compress_level ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shapes(self): """Return the route shapes as a dictionary."""
# Todo: Cache? if self._shapes: return self._shapes # Group together by shape_id self.log("Generating shapes...") ret = collections.defaultdict(entities.ShapeLine) for point in self.read('shapes'): ret[point['shape_id']].add_child(point) self._shapes = ret return self._shape...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, validator=None, skip_relations=False): """Validate a GTFS :param validator: a ValidationReport :param (bool) skip_relations: skip validation o...
validator = validation.make_validator(validator) self.log('Loading...') self.preload() # required required = [ 'agency', 'stops', 'routes', 'trips', 'stop_times', 'calendar' ] for f in required: self.log("Validating required file: %s"%f) data ...