code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# 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 = su...
def _calibrate(self, data, labels)
\ Calibrate the network using `self._bmus`.
4.345876
3.708333
1.171922
bmus, seconds, mdst = self._som._bmus_and_seconds(data) quant_error = np.sqrt(mdst, out=mdst).mean() topog_error = self._som._topographic_error(bmus, seconds, data.shape[0]) return self._som._to_bmus(bmus), quant_error, topog_error
def bmus_with_errors(self, data)
\ Compute common error metrics (Quantization err. and Topographic err.) for this data. :param data: sparse input matrix (ideal dtype is `numpy.float32`) :type data: :class:`scipy.sparse.csr_matrix` :returns: the BMUs, the QE and the TE :rtype: tuple
7.941861
6.988527
1.136414
assert self.classifier is not None, 'not calibrated' bmus = self._som.bmus(data) return self._predict_from_bmus(bmus, unkown)
def predict(self, data, unkown=None)
\ Classify data according to previous calibration. :param data: sparse input matrix (ideal dtype is `numpy.float32`) :type data: :class:`scipy.sparse.csr_matrix` :param unkown: the label to attribute if no label is known :returns: the labels guessed for data :rtype: `num...
7.940831
7.464903
1.063755
self.fit(data, labels) return self._predict_from_bmus(self._bmus, unkown)
def fit_predict(self, data, labels, unkown=None)
\ Fit and classify data efficiently. :param data: sparse input matrix (ideal dtype is `numpy.float32`) :type data: :class:`scipy.sparse.csr_matrix` :param labels: the labels associated with data :type labels: iterable :param unkown: the label to attribute if no label is ...
6.947582
8.955491
0.77579
assert self.classifier is not None, 'not calibrated' arr = np.zeros((self._som.nrows, self._som.ncols)) for ij, (lbl, p) in self.classifier.items(): arr[ij] = p return arr
def get_precision(self)
\ :returns: the ratio part of the dominant label for each unit. :rtype: 2D :class:`numpy.ndarray`
6.768216
6.321347
1.070692
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
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.ndarray` :returns: the computed 2D histogram of bmus. :rtype: :class:`numpy.ndarray`
3.645503
3.742651
0.974043
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_PR...
def get_protocol_version(protocol=None, target=None)
Return a suitable pickle protocol version for a given target. Arguments: target: The internals description of the targeted python version. If this is ``None`` the specification of the currently running python version will be used. protocol(None or int): The requested protoco...
3.513503
2.982565
1.178014
protocol = get_protocol_version(protocol, target) return cPickle.dumps(PickleInvoke(func, *args), protocol)
def pickle_invoke(func, target=None, protocol=None, *args)
pickle_invoke(func, *args, target=None, protocol=None) Create a byte sequence which when unpickled calls a callable with given arguments. Note: The function has to be importable using the same name on the system that unpickles this invocation. Arguments: func(callable): The fu...
6.500215
11.950438
0.543931
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 i...
def translate_opcodes(code_obj, target)
Very crude inter-python version opcode translator. Raises SyntaxError when the opcode doesn't exist in the destination opmap. Used to transcribe python code objects between python versions. Arguments: code_obj(pwnypack.bytecode.CodeObject): The code object representation to translate. ...
1.74242
1.619833
1.075678
"finds extra attributes in *value* if they are there" extra = None value_is_from_database = True if hasattr(value, 'standin_value_is_from_database'): value_is_from_database = value.standin_value_is_from_database if value.stored_value != value.msg: extra = value.msg ...
def find_extra_attrs(value)
finds extra attributes in *value* if they are there
5.222413
4.403689
1.185918
ret = set() for k,v in kw.items(): for entity in entities: if getattr(entity, k)() == v: ret.add(entity) return ret
def filtany(entities, **kw)
Filter a set of entities based on method return. Use keyword arguments. Example: filtmeth(entities, id='123') filtmeth(entities, name='bart') Multiple filters are 'OR'.
3.344825
2.896981
1.15459
ret = sorted(filtany(entities, **kw), key=lambda x:x.id()) if not ret: raise ValueError('No result') return ret[0]
def filtfirst(entities, **kw)
Return the first matching entity, sorted by id().
5.789226
4.000512
1.447121
frames = inspect.stack()[2:] if depth: frames = frames[:depth] result = StringIO() result.write("----------------------------------------------------\n") for (frame, file, line, context, code, status) in frames: result.write("In %s from %s\n%s %s" % (context, file, line...
def stack_trace(depth=None)
returns a print friendly stack trace at the current frame, without aborting the application. :param depth: The depth of the stack trace. if omitted, the entire stack will be printed. usage:: print stack_trace(10)
4.080118
4.880162
0.836062
serves = set() for trip in self.trips(): for stop_time in trip.stop_times(): serves |= stop_time.stops() return serves
def stops(self)
Return stops served by this route.
5.659173
4.773935
1.185431
endian, target = kwargs.get('endian'), kwargs.get('target') endian = endian if endian is not None else target.endian if target is not None else pwnypack.target.target.endian if fmt and fmt[0] not in '@=<>!': if endian is pwnypack.target.Target.Endian.little: fmt = '<' + fmt ...
def pack(fmt, *args, **kwargs)
pack(fmt, v1, v2, ..., endian=None, target=None) Return a string containing the values v1, v2, ... packed according to the given format. The actual packing is performed by ``struct.pack`` but the byte order will be set according to the given `endian`, `target` or byte order of the global target. A...
3.273011
2.332481
1.403231
endian = endian if endian is not None else target.endian if target is not None else pwnypack.target.target.endian if fmt and fmt[0] not in '@=<>!': if endian is pwnypack.target.Target.Endian.little: fmt = '<' + fmt elif endian is pwnypack.target.Target.Endian.big: f...
def unpack(fmt, data, endian=None, target=None)
Unpack the string (presumably packed by pack(fmt, ...)) according to the given format. The actual unpacking is performed by ``struct.unpack`` but the byte order will be set according to the given `endian`, `target` or byte order of the global target. Args: fmt(str): The format string. d...
2.96582
2.448273
1.211393
if bits is not None: bits = int(bits) if bits in (8, 16, 32, 64): return bits else: raise ValueError('bits needs to be 8, 16, 32 or 64') else: return int((target if target is not None else pwnypack.target.target).bits)
def _get_bits(bits=None, target=None)
Determine the number of bits to pack/unpack.
3.160047
2.945967
1.072669
return globals()['P%d' % _get_bits(bits, target)](value, endian=endian, target=target)
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.target.Target.Bits`): Override the default word size. If ``None`` it will look at the word size of ``target``. endian(:class:`~pwnypack.target.Target.Endian`): Ov...
6.824875
9.572587
0.71296
return globals()['p%d' % _get_bits(bits, target)](value, endian=endian, target=target)
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.target.Target.Bits`): Override the default word size. If ``None`` it will look at the word size of ``target``. endian(:class:`~pwnypack.target.Target.Endian`): Overri...
6.728895
9.796175
0.68689
return globals()['U%d' % _get_bits(bits, target)](data, endian=endian, target=target)
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:`pwnypack.target.Target.Bits`): Override the default word size. If ``None`` it will look at the word size of ``target``. endian(:class:`~pwnypack.target.Target.Endian`):...
6.301642
10.904798
0.577878
return globals()['u%d' % _get_bits(bits, target)](data, endian=endian, target=target)
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.target.Target.Bits`): Override the default word size. If ``None`` it will look at the word size of ``target``. endian(:class:`~pwnypack.target.Target.Endian`): Ov...
6.519496
11.065815
0.589156
trips = set() for route in self.routes(): trips |= route.trips() return trips
def trips(self)
Return all trips for this agency.
4.49541
3.547509
1.267202
stops = set() for stop_time in self.stop_times(): stops |= stop_time.stops() return stops
def stops(self)
Return all stops visited by trips for this agency.
5.867431
4.724298
1.241969
stop_times = set() for trip in self.trips(): stop_times |= trip.stop_times() return stop_times
def stop_times(self)
Return all stop_times for this agency.
3.58512
2.763488
1.297317
if self.__boxes is not None: return self.__boxes # Check first if there is an OCR file available boxfile = self.__get_box_path() if self.fs.exists(boxfile): box_builder = pyocr.builders.LineBoxBuilder() try: with self.fs.open...
def __get_boxes(self)
Get all the word boxes of this page.
3.918432
3.789558
1.034008
# 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 ...
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 the original field, instead replace it with a DefaultFieldDescriptor, which always returns the field in the current language.
3.723472
3.589858
1.03722
logger.info("Destroying doc: %s" % self.path) self.fs.rm_rf(self.path) logger.info("Done")
def destroy(self)
Delete the document. The *whole* document. There will be no survivors.
5.683749
4.807587
1.182246
if to_remove not in self.labels: return labels = self.labels labels.remove(to_remove) 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....
def remove_label(self, to_remove)
Remove a label from the document. (-> rewrite the label file)
3.252848
3.189586
1.019834
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(",", ...
def __get_labels(self)
Read the label file of the documents and extract all the labels Returns: An array of labels.Label objects
2.929177
3.061311
0.956838
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()))
def __set_labels(self, labels)
Add a label on the document.
4.1341
3.843632
1.075571
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 l...
def update_label(self, old_label, new_label)
Update a label Replace 'old_label' by 'new_label'
2.746978
2.822598
0.973209
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
def __doc_cmp(self, other)
Comparison function. Can be used to sort docs alphabetically.
2.339808
2.273853
1.029006
if self.is_new: return _("New document") try: split = self.__docid.split("_") short_docid = "_".join(split[:3]) datetime_obj = datetime.datetime.strptime( short_docid, self.DOCNAME_FORMAT) final = datetime_obj.strftime(...
def __get_name(self)
Returns the localized name of the document (see l10n)
4.273599
3.872796
1.103492
'''atomic writing''' tmp_file, tmp_fname = tempfile.mkstemp() os.close(tmp_file) shutil.copystat(self.file_name, tmp_fname) self.config.write(open(tmp_fname, 'w')) shutil.move(tmp_fname, self.file_name)
def write(self)
atomic writing
3.806165
3.391861
1.122146
po_text = po_obj.__str__() if type(po_text) != types.UnicodeType: po_text = po_text.decode('utf-8') return po_text
def po_to_unicode(po_obj)
Turns a polib :class:`polib.PoFile` or a :class:`polib.PoEntry` into a :class:`unicode` string. :param po_obj: Either a :class:`polib.PoFile` or :class:`polib.PoEntry`. :rtype: :class:`unicode` string.
2.889443
4.094229
0.705736
''' 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=True) as f: f.write(arff...
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
3.33867
1.871206
1.784234
languages = get_language_codes() if hasattr(settings, 'MSGID_LANGUAGE'): if not settings.MSGID_LANGUAGE in languages: languages.insert(0, settings.MSGID_LANGUAGE) return languages
def get_all_language_codes()
Returns all language codes defined in settings.LANGUAGES and also the settings.MSGID_LANGUAGE if defined. >>> from django.conf import settings >>> settings.MSGID_LANGUAGE = 'en-us' >>> settings.LANGUAGES = (('en','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),) ...
4.002347
2.874187
1.392514
stripped_url = strip_language_code(url) if not getattr(settings, 'MASTER_SITE', False) and len(settings.LANGUAGES) == 1: # no MASTER_SITE and only one language, do not add language code to url return stripped_url # add the language code to the url return u"/%s%s" % (get...
def fix_language_code(url, current_language)
Fixes the language code as follows: If there is only one language used in the site, it strips the language code. If there are more languages used, it will make sure that the url has the current language as a prefix. >>> # multiple languages defined >>> settings.LANGUAGES = (('en-us','Engli...
4.538339
4.734218
0.958625
result = [] lang = get_language() for field in fields: if field in internationalized_fields: result.append(get_real_fieldname(field, lang)) else: result.append(field) return result
def localize_fieldnames(fields, internationalized_fields)
Given a list of fields and a list of field names that are internationalized, will return a list with all internationalized fields properly localized. >>> from django.utils.translation import activate >>> activate('en-us') >>> localize_fieldnames(['name', 'title', 'url'], ['title']) ['name',...
2.897105
2.990678
0.968712
try: return force_unicode(self.__get__(obj)) except TypeError: return str(self.__get__(obj))
def value_to_string(self, obj)
This descriptor acts as a Field, as far as the serializer is concerned.
3.989892
3.818596
1.044858
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): occurre...
def poify(self, model)
turn a django model into a po file.
5.826902
5.395248
1.080006
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) ...
def xgettext(self, template)
Extracts to be translated strings from template and turns it into po format.
5.770134
5.875256
0.982108
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...
def msgmerge(self, locale_file, po_string)
Runs msgmerge on a locale_file and po_string
4.424881
4.571253
0.96798
# 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.commun...
def msguniq(self, locale_file)
run msgunique on the locale_file
7.259382
6.932825
1.047103
if isinstance(value, _UTF8_TYPES): return value if not isinstance(value, unicode_type): raise TypeError( "Expected bytes, unicode, or None; got %r" % type(value) ) return value.encode("utf-8")
def _utf8(value)
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
3.00379
2.852867
1.052902
if isinstance(value, _TO_UNICODE_TYPES): return value if not isinstance(value, bytes_type): raise TypeError( "Expected bytes, unicode, or None; got %r" % type(value) ) return value.decode("utf-8")
def _unicode(value)
Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8.
3.126514
2.890495
1.081653
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...
def to_utf8(obj)
Walks a simple data structure, converting unicode to byte string. Supports lists, tuples, and dictionaries.
1.725845
1.748969
0.986779
dsearch = get_docsearch() doc = dsearch.get(docid) if doc is None: raise Exception( "Document {} not found. Cannot add label on it".format( docid ) ) label = None for clabel in dsearch.label_list: if clabel.name == label_name: ...
def cmd_add_label(docid, label_name, color=None)
Arguments: <document_id> <label_name> [<label_color>] Add a label on a document. Color must be specified if the label doesn't exist yet. Color will be ignored if the label already exists. Color format must be given in hexadecimal format. Ex: #abcdef Possible JSON replies: -- { "st...
2.780917
2.767967
1.004678
dsearch = get_docsearch() doc = dsearch.get(docid) if doc is None: raise Exception( "Document {} not found. Cannot delete it".format( docid ) ) index_updater = dsearch.get_index_updater(optimize=False) index_updater.del_doc(doc) index_...
def cmd_delete_doc(docid)
Arguments: <document_id> Delete a document. Possible JSON replies: -- { "status": "ok", "docid": "xxxx" } -- { "status": "error", "exception": "yyy", "reason": "xxxx", "args": "(xxxx, )" }
4.310612
4.445317
0.969697
dsearch = get_docsearch() doc = dsearch.get(docid) pages = doc.pages pages = [page for page in pages] if page_nb: page_nb = int(page_nb) pages = pages[page_nb - 1:page_nb] for page in pages: verbose("=== Page {} ===".format(page.page_nb + 1)) _dump_page(page)
def cmd_dump(docid, page_nb=None)
Arguments: <document id> [<page number>] Dump the content of the specified document. Beware, page numbers start from 1. See 'search' for the document ids. Replies with page content. Beware: This is the only command not replying in JSON format.
3.090388
3.324247
0.92965
(output_dir, quality, page_format) = _get_export_params(args) dsearch = get_docsearch() try: os.mkdir(output_dir) except FileExistsError: # NOQA (Python 3.x only) pass out = [] docs = [d for d in dsearch.docs] docs.sort(key=lambda doc: doc.docid) output_dir = FS...
def cmd_export_all(*args)
Arguments: <output folder> [-- [--quality <0-100>] [--page_format <page_format>]] Export all documents as PDF files. Default quality is 50. Default page format is A4. Possible JSON replies: -- { "status": "error", "exception": "yyy", "reason": "xxxx", "...
3.793922
3.360945
1.128826
(docid, output_pdf, quality, page_format) = _get_export_params(args) dsearch = get_docsearch() doc = dsearch.get(docid) exporter = doc.build_exporter(file_format="pdf") if exporter.can_change_quality: exporter.set_quality(quality) if exporter.can_select_format: exporter.se...
def cmd_export_doc(*args)
Arguments: <document id> <output PDF file path> [-- [--quality <0-100>] [--page_format <page_format>]] Export one document as a PDF file. Default quality is 50. Default page format is A4. Possible JSON replies: -- { "status": "error", "exception": "yyy", ...
3.779603
3.306041
1.143241
args = list(args) apply_labels = False if "--apply" in args: apply_labels = True args.remove("--apply") docid = args[0] dsearch = get_docsearch() doc = dsearch.get(docid) if doc is None: raise Exception( "Document {} not found. Cannot guess labels"....
def cmd_guess_labels(*args)
Arguments: <document id> [-- [--apply]] Guess the labels that should be set on the document. Example: paperwork-shell guess_labels -- 20161207_1144_00_8 --apply Possible JSON replies: -- { "status": "error", "exception": "yyy", "reason": "xxxx", "args": "(xxxx, )" ...
2.41734
2.104253
1.148788
guess_labels = True ocr = pyocr.get_available_tools() docid = None doc = None args = list(args) if len(ocr) <= 0: raise Exception("No OCR tool found") ocr = ocr[0] if "--no_label_guessing" in args: guess_labels = False args.remove("--no_label_guessing") ...
def cmd_import(*args)
Arguments: <file_or_folder> [<file_or_folder> [...]] [-- [--no_ocr] [--no_label_guessing] [--append <document_id>]] Import a file or a PDF folder. OCR is run by default on images and on PDF pages without text (PDF containing only images) Please keep in mind that documents that are alre...
2.9708
2.599612
1.142786
ocr_lang = None empty_only = False args = list(args) ocr = pyocr.get_available_tools() if len(ocr) <= 0: raise Exception("No OCR tool found") ocr = ocr[0] if "--lang" in args: idx = args.index("--lang") ocr_lang = args[idx + 1] args.pop(idx) ar...
def cmd_ocr(*args)
Arguments: <document id or page id> [<document id or page id> [...]] [-- [--lang <ocr_lang>] [--empty_only]] Re-run the OCR on the specified elements. Elements can be whole documents or specific pages. --lang: specifies the language to use for OCR. The default language used is the one ...
3.096298
2.781816
1.113049
dsearch = get_docsearch() doc = dsearch.get(docid) if doc is None: raise Exception( "Document {} not found. Cannot remove label from it".format( docid ) ) for clabel in dsearch.label_list: if clabel.name == label_name: lab...
def cmd_remove_label(docid, label_name)
Arguments: <document_id> <label_name> Remove a label from a document. Note that if the document was the last one to use the label, the label may disappear entirely from Paperwork. Possible JSON replies: -- { "status": "error", "exception": "yyy", "reason": "xxx...
3.087708
3.047058
1.013341
dsearch = get_docsearch() doc = dsearch.get(old_docid) if doc is None: raise Exception( "Document {} not found. Cannot remove label from it".format( old_docid ) ) index_updater = dsearch.get_index_updater(optimize=False) # just clone the...
def cmd_rename(old_docid, new_docid)
Arguments: <current document_id> <new document_id> Change the ID of a document. Note that the document id are also their date. Using an ID that is not a date may have side effects (the main one being the document won't be sorted correctly). Possible JSON replies: -- { ...
4.047153
4.166285
0.971406
dsearch = get_docsearch() doc = dsearch.get(docid) r = { 'type': str(type(doc)), 'nb_pages': doc.nb_pages, 'labels': [l.name for l in doc.labels], 'first_line': _get_first_line(doc), 'pages': [] } for page in doc.pages: nb_lines = 0 nb_wor...
def cmd_show(docid)
Arguments: <doc_id> Show document information (but not its content, see 'dump'). See 'search' for the document id. Possible JSON replies: -- { "status": "error", "exception": "yyy", "reason": "xxxx", "args": "(xxxx, )" } -- { "sta...
3.262036
2.432269
1.341149
dsearch = get_docsearch() verbose("Search: {}".format(" ".join(args))) r = {'results': []} docs = dsearch.find_documents(" ".join(args)) docs.sort(key=lambda doc: doc.docid) for doc in docs: r['results'].append({ 'docid': doc.docid, 'nb_pages': doc.nb_page...
def cmd_search(*args)
Arguments: <keyword1> [<keyword2> [<keyword3> [...]]] List the documents containing the keywords. Syntax is the same than with the search field in Paperwork-gui. Search "" (empty string) to get all the documents. Example: 'label:contrat AND paperwork' Possible JSON replies: -- { ...
3.869388
3.253016
1.189477
new_workdir = FS.safe(new_workdir) if not FS.exists(new_workdir) or not FS.isdir(new_workdir): sys.stderr.write("New work directory {} doesn't exists".format( new_workdir )) return pconfig = config.PaperworkConfig() pconfig.read() r = { 'old_workdir':...
def cmd_switch_workdir(new_workdir)
Arguments: <new work directory path> Change current Paperwork's work directory. Does *not* update the index. You should run 'paperwork-shell rescan' after this command. Possible JSON replies: -- { "status": "error", "exception": "yyy", "reason": "xxxx", "args":...
3.624986
3.536865
1.024915
self.postGoal = goal self.postScript = script
def setPostScript(self, goal, script)
After learning call the given script using 'goal'. :param goal: goal name :param script: prolog script to call
7.640553
13.020434
0.586812
# 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: dumpF...
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 experiment. :param mode: In which mode to induce rules/features. :param pos: String of positive examples. :param neg: String of negative examples. :param b: String of background kno...
4.701597
4.480213
1.049414
posFile = open('%s/%s.f' % (self.tmpdir, filestem), 'w') negFile = open('%s/%s.n' % (self.tmpdir, filestem), 'w') bFile = open('%s/%s.b' % (self.tmpdir, filestem), 'w') posFile.write(pos) negFile.write(neg) bFile.write(b) posFile.close() negFile...
def __prepare(self, filestem, pos, neg, b)
Prepares the needed files.
1.71853
1.653469
1.039349
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(...
def __script(self, mode, filestem)
Makes the script file to be run by yap.
5.253628
5.23798
1.002987
foos = foobar_models.Foo.objects.all() return HttpResponse(tree.xml(foos), mimetype='text/xml')
def raw(request)
shows untransformed hierarchical xml output
7.48411
6.858895
1.091154
bars = foobar_models.Bar.objects.all() bazs = foobar_models.Baz.objects.all() qsc = XmlQuerySetChain(bars, bazs) return HttpResponse(tree.xml(qsc), mimetype='text/xml')
def chain(request)
shows how the XmlQuerySetChain can be used instead of @toxml decorator
5.662105
3.836385
1.475896
foos = foobar_models.Foo.objects.all() return render_xslt_to_response('xslt/model-to-xml.xsl', foos, mimetype='text/xml')
def xslt(request)
Shows xml output transformed with standard xslt
5.765434
6.124094
0.941435
#Step 1: get the right pitch values assert isinstance(self.pitch_obj.pitch, np.ndarray) valid_pitch = self.pitch_obj.pitch valid_pitch = [i for i in valid_pitch if i > -10000] if folded: valid_pitch = map(lambda x: int(x % 1200), valid_pitch) #Step 2...
def compute_hist(self, bins=None, density=True, folded=False, weight="duration")
Computes histogram from the pitch data in Pitch object (pitch), and creates a Data object (pypeaks). :param bins: Refers to number of bins in the histogram, determines the granularity. If it is not set, the number of bins which gives the highest granularity is chosen automatically. ...
2.548244
2.381506
1.070014
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(n...
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. This function labels pitch contours with intervals by guessing from the characteristics of the contour and its melodic context. :param window: the size of window over which the context is gauged,...
3.310178
3.314786
0.99861
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) t...
def plot_contour_labels(self, new_fig=True)
Plots the labelled contours!
3.491723
3.356554
1.04027
newn = int(1.0 * len(l) / n + 0.5) for i in range(0, n - 1): yield l[i * newn:i * newn + newn] yield l[n * newn - newn:]
def chunks(l, n)
Yield n successive chunks from l.
2.268718
2.081706
1.089836
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:", l...
def wordify_example(name_to_table, connecting_tables, context, cached_sentences, index_by_value, target_table_name, word_att_length, data_name, ex, searched_connections)
Recursively constructs the 'wordification' document for the given example. :param data: The given examples ExampleTable :param ex: Example for which the document is constructed
2.848497
2.894963
0.983949
# 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_t...
def run(self, num_of_processes=multiprocessing.cpu_count())
Applies the wordification methodology on the target table :param num_of_processes: number of processes
8.024189
7.426548
1.080474
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[d...
def calculate_weights(self, measure='tfidf')
Counts word frequency and calculates tf-idf values for words in every document. :param measure: example weights approach (can be one of ``tfidf, binary, tf``).
3.950516
3.812067
1.036319
''' 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.add(word) ...
def to_arff(self)
Returns the "wordified" representation in ARFF. :rtype: str
2.534667
2.241584
1.130748
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...
def prune(self, minimum_word_frequency_percentage=1)
Filter out words that occur less than minimum_word_frequency times. :param minimum_word_frequency_percentage: minimum frequency of words to keep
2.459007
2.631401
0.934486
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)
def wordify(self)
Constructs string of all documents. :return: document representation of the dataset, one line per document :rtype: str
6.504812
5.621246
1.157183
if env.target.bits == 32: get_pc = [ '\tcall __getpc0', '__getpc0:', '\tpop %s' % env.OFFSET_REG, '\tadd %s, __data - __getpc0' % env.OFFSET_REG, '__realstart:', ] else: get_pc = ['\tlea %s, [rel __data]' % env.OFFSET_REG]...
def nasm_mutable_data_finalizer(env, code, data)
Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code.
7.157845
7.128019
1.004184
if data or env.buffers: # Determine length of nullify + shellcode and adjust data pointer xor_offsets = [] masked_data = OrderedDict() for datum, (offset, orig_datum) in six.iteritems(data): xor_offsets.extend([ offset + i ...
def nasm_null_safe_mutable_data_finalizer(env, code, data)
Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code.
4.754165
4.769989
0.996682
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
def binary_value_or_stdin(value)
Return fsencoded value or read raw data from stdin if value is None.
2.928028
2.633711
1.11175
parser.add_argument( 'apps', nargs=argparse.REMAINDER, help='Which apps to create symlinks for.' ) args = parser.parse_args(args) base_dir, pwny_main = os.path.split(sys.argv[0]) for app_name, config in MAIN_FUNCTIONS.items(): if not config['symlink'] or (args...
def symlink(parser, cmd, args)
Set up symlinks for (a subset of) the pwny apps.
2.898839
2.472613
1.172379
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 ...
def __label_cmp(self, other)
Comparaison function. Can be used to sort labels alphabetically.
2.006663
1.904673
1.053547
color = self.color return ("#%02x%02x%02x" % ( int(color.red), int(color.green), int(color.blue) ))
def get_html_color(self)
get a string representing the color, using HTML notation
2.942679
2.691852
1.09318
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)
def forget(self, label_name)
Forget training for label 'label_name'
5.419486
5.049233
1.073328
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_...
def rename(self, old_label_name, new_label_name)
Take into account that a label has been renamed
2.423609
2.469229
0.981524
filename = ("%s%d.%s" % (self.FILE_PREFIX, self.page_nb + 1, ext)) return self.fs.join(self.doc.path, filename)
def _get_filepath(self, ext)
Returns a file path relative to this page
6.248083
5.155851
1.211843
(w, h) = self.size factor = max( (float(w) / width), (float(h) / height) ) w /= factor h /= factor return self.get_image((round(w), round(h)))
def __make_thumbnail(self, width, height)
Create the page's thumbnail
4.308695
4.205698
1.02449
# 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...
def get_thumbnail(self, width, height)
thumbnail with a memory cache
3.171395
3.101019
1.022695
txt = self.text for line in txt: for word in split_words(line): yield(word)
def __get_keywords(self)
Get all the keywords related of this page Returns: An array of strings
8.213944
9.416975
0.872249
return u''.join( (character for character in unicodedata.normalize('NFD', string) if unicodedata.category(character) != 'Mn'))
def strip_accents(string)
Strip all the accents from the string
3.079774
2.894578
1.06398
if (sentence == "*"): yield sentence return # TODO: i18n if modify: sentence = sentence.lower() sentence = strip_accents(sentence) words = FORCED_SPLIT_KEYWORDS_REGEX.split(sentence) if keep_shorts: word_iter = words else: word_iter = __clea...
def split_words(sentence, modify=True, keep_shorts=False)
Extract and yield the keywords from the sentence: - Drop keywords that are too short (keep_shorts=False) - Drop the accents (modify=True) - Make everything lower case (modify=True) - Try to separate the words as much as possible (using 2 list of separators, one being more complete than the others)
2.758763
2.695242
1.023568
if os.name == "nt": assert(not "check_spelling() not available on Windows") return with _ENCHANT_LOCK: # Maximum distance from the first suggestion from python-enchant words_dict = enchant.request_dict(spelling_lang) try: tknzr = enchant.tokenize.get_tok...
def check_spelling(spelling_lang, txt)
Check the spelling in the text, and compute a score. The score is the number of words correctly (or almost correctly) spelled, minus the number of mispelled words. Words "almost" correct remains neutral (-> are not included in the score) Returns: A tuple : (fixed text, score)
4.920527
4.879382
1.008432
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....
def rm_rf(path)
Act as 'rm -rf' in the shell
1.477418
1.504851
0.98177
# 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, # ...
def surface2image(surface)
Convert a cairo surface into a PIL image
2.543437
2.482524
1.024537
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')...
def image2surface(img)
Convert a PIL image into a Cairo surface
4.324814
4.134784
1.045959
''' Check for illegal predicates (like reading/writing, opening sockets, etc). ''' if prolog_file == None: return for pred in illegal_predicates: if type(pred) == tuple: print_name = pred[1] pred = pred[0] else: print_name = pred if...
def check_input(prolog_file)
Check for illegal predicates (like reading/writing, opening sockets, etc).
7.32917
5.120636
1.431301
''' Use the features returned by a propositionalization method to map unseen test examples into the new feature space. :param features: string of features as returned by rsd, aleph or treeliker :param feature_format: 'rsd', 'aleph', 'treeliker' :param train_context: DBContext with trainin...
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: string of features as returned by rsd, aleph or treeliker :param feature_format: 'rsd', 'aleph', 'treeliker' :param train_context: DBContext with training examples ...
4.095954
2.68572
1.525086
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
def _get_text(self)
Get the text corresponding to this page
4.560773
4.065526
1.121816
boxfile = self.__box_path try: box_builder = pyocr.builders.LineBoxBuilder() with self.fs.open(boxfile, 'r') as file_desc: boxes = box_builder.read_file(file_desc) if boxes != []: return boxes # fallback: old forma...
def __get_boxes(self)
Get all the word boxes of this page.
4.043071
3.871784
1.04424
with self.fs.open(self.__img_path, 'rb') as fd: img = PIL.Image.open(fd) img.load() return img
def __get_img(self)
Returns an image object corresponding to the page
3.62923
3.345841
1.084699