Esempio n. 1
0
	def copy(self, **kwargs):
		k, v = itertools.tee(itertools.chain(
			('break_long_words', 'break_on_hyphens', 'drop_whitespace',
				'expand_tabs', 'fix_sentence_endings', 'initial_indent',
				'replace_whitespace', 'subsequent_indent', 'width', 'file'),
			filter(fpartial(hasattr, self),
				('max_lines', 'placeholder', 'tabsize'))))
		foreach(kwargs.setdefault, k, map(fpartial(getattr, self), v))
		return self.__class__(**kwargs)
Esempio n. 2
0
    def load(cls):
        """Load a version object from environment information.

        Tries to load or construct version information based on the environment in
        the following order:

         1. using the attributes of the ._data module (relative to this module),
         2. the first line of the 'VERSION' file located two directory levels above
            the module search path root for this module or package for the 'version'
            attribute only,
         3. from 'from_repo(version)'.
        """

        try:
            from . import _data
        except ImportError:
            pass
        else:
            return cls(
                *map(fpartial(getattr, _data), cls.__slots__))

        version_file = os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(
                __import__(strings.prefix(__package__ or __name__, '.')).__file__))),
            'VERSION')
        try:
            version_file = open(version_file)
        except FileNotFoundError:
            version = None
        else:
            with version_file:
                version = version_file.readline(1024).strip()

        return cls.from_repo(version)
Esempio n. 3
0
def main(*args):
	opts = parse_args(args or None)

	records = sys.stdin
	if opts.skip > 0:
		records = itertools.islice(records, opts.skip, None)
	if opts.input_field_separator is None:
		records = map(str.split, records)
	else:
		records = map(methodcaller('rstrip', '\n'), records)
		if isinstance(opts.input_field_separator, RegexType):
			records = map(opts.input_field_separator.split, records)
		elif opts.input_field_separator is not False:
			records = map(
				fpartial(str.split, sep=opts.input_field_separator), records)
	records = filter(None, records)

	if not opts.groups:
		records = ((), records)
	else:
		group_key_func = itemgetter(*opts.groups)
		if not opts.sorted:
			records = sorted(records, key=group_key_func)
		records = itertools.groupby(records, group_key_func)

	return process_records(records, opts)
	def load(cls):
		"""Load a version object from environment information.

		Tries to load or construct version information based on the environment in
		the following order:

		 1. using the attributes of the ._data module (relative to this module),
		 2. the first line of the 'VERSION' file located two directory levels above
		    the module search path root for this module or package for the 'version'
		    attribute only,
		 3. from 'from_repo(version)'.
		"""
		try:
			from . import _data
		except ImportError:
			pass
		else:
			return cls(
				*map(fpartial(getattr, _data), cls.__slots__))

		try:
			with open(os.path.join(
				os.path.dirname(os.path.dirname(os.path.dirname(
					sys.modules[(__package__ or __name__).partition('.')[0]].__file__))),
				'VERSION')) \
			as f:
				version = f.readline(1<<10)
		except FileNotFoundError:
			version = None
		else:
			version = str(version).strip()

		return cls.from_repo(version)
Esempio n. 5
0
	def _parse_handle_archive(self, ns):
		f_archive = self.exitstack.enter_context(
			open(ns.archive, "wb",
				opener=fpartial(os.open, mode=0o777 if ns.executable else 0o666)))
		ns.archive = self.exitstack.enter_context(
			ZipFile(f_archive, "w", ns.compression_method,
				compress_options=ns.compression_level))
Esempio n. 6
0
 def __repr__(self):
     return '{0.__module__:s}.{0.__qualname__:s}({1:s})'.format(
         type(self), ', '.join(
             map(
                 '='.join,
                 zip(
                     self.__slots__,
                     map(repr, map(fpartial(getattr, self),
                                   self.__slots__))))))
Esempio n. 7
0
 def new_ax(self,text):
     self.canvas.pdata.myax.setax(self.canvas.pdata.reader,str(text))
         # set and connect sliders
     self.sliderbox.disconnect_all()
     self.sliderbox.setsliders(self.canvas.pdata.reader,self.canvas.pdata.myax)
     for ii in range(len(self.canvas.pdata.myax.sl_inds)):    
         self.sliderbox.sliderlist[ii].myslider.valueChanged.connect(self.sliderbox.sliderlist[ii].mylcd.display)
         self.sliderbox.sliderlist[ii].myslider.valueChanged.connect(fpartial(self.slider_moved,active_dim=ii))        
     self.buttons_horz.setbuttons(True,self.canvas.pdata.myax)
     self.buttons_vert.setbuttons(False,self.canvas.pdata.myax)                
     self.setcombo2()
Esempio n. 8
0
class _ZipWriteFile(zipfile._ZipWriteFile):
    # Monkey patch to pass compressor options through

    __slots__ = ()

    _get_compressor_orig = staticmethod(zipfile._get_compressor)

    _compressor_ctors = {
        zipfile.ZIP_STORED:
        None,
        zipfile.ZIP_DEFLATED:
        fpartial(zlib.compressobj, method=zlib.DEFLATED, wbits=-15),
        zipfile.ZIP_BZIP2:
        NotImplemented if bz2 is None else bz2.BZ2Compressor,
        zipfile.ZIP_LZMA:
        NotImplemented if lzma is None else LZMACompressor,
    }

    def __init__(self, zf, zinfo, zip64):
        super().__init__(zf, zinfo, zip64)
        self._compressor = self._get_compressor(zinfo.compress_type,
                                                zinfo.compress_options)

    @classmethod
    def _get_compressor(cls, compress_type, compress_options):
        compressor = cls._compressor_ctors.get(compress_type, NotImplemented)

        if compressor is None:
            return None

        if compressor is NotImplemented:
            try:
                compress_type = ("Unsupported",
                                 zipfile.compressor_names[compress_type])
            except KeyError:
                compress_type = ("Unknown", repr(compress_type))
            raise ValueError(" compression type: ".join(compress_type))

        if compress_options is None:
            return compressor()
        args, kwargs = compress_options
        if args is None:
            args = ()
        if kwargs is None:
            return compressor(*args)
        return compressor(*args, **kwargs)
Esempio n. 9
0
    def _attribute_items(self,
                         mandatory_attrs=(
                             'break_long_words', 'break_on_hyphens', 'drop_whitespace',
                             'expand_tabs', 'fix_sentence_endings', 'initial_indent',
                             'replace_whitespace', 'subsequent_indent', 'width', 'file'),
                         optional_attrs=(
                             'max_lines', 'placeholder', 'tabsize')
                         ):
        assert isinstance(mandatory_attrs, collections.abc.Sized)
        self_getattr = fpartial(getattr, self)
        yield from zip(mandatory_attrs, map(self_getattr, mandatory_attrs))

        for k in optional_attrs:
            try:
                yield (k, self_getattr(k))
            except AttributeError:
                pass
Esempio n. 10
0
def getlines(stream, delim, chunk_size=0, *, _exitstack):
    assert isinstance(chunk_size, int)
    assert isinstance(_exitstack, contextlib.ExitStack)

    if chunk_size <= 0:
        if chunk_size:
            raise ValueError("Non-positive chunk size " +
                             format(chunk_size, "n"))
        chunk_size = 1 << 20

    if isinstance(stream, io.TextIOBase):
        delim_alt = (None, "\n")[delim == stream.newlines != ""]
    elif isinstance(stream, io.IOBase):
        delim_alt = (None, b"\n")[delim == b"\n"]
    else:
        delim_alt = None

    if delim_alt is not None:
        return map(operator.methodcaller("rstrip", delim_alt), stream)

    if isinstance(delim, collections.abc.ByteString):
        return _getlines_impl_bytes(stream, delim, chunk_size, _exitstack)

    assert isinstance(delim, str)
    try:
        delim_alt = delim.encode(stream.encoding)
    except UnicodeEncodeError:
        pass
    else:
        assert isinstance(delim_alt, collections.abc.ByteString)
        if delim_alt:
            stream.flush()
            return map(
                fpartial(str, encoding=stream.encoding, errors=stream.errors),
                _getlines_impl_bytes(stream.buffer, delim_alt, chunk_size,
                                     _exitstack))

    #print("Using generic getlines implementation for delimiter {!r} ({!r} in {:s})".format(delim, delim_alt, stream.encoding))
    if len(delim) != 1:
        raise ValueError(
            "Delimiter must have length 1; got {!r} (length {:d})".format(
                delim, len(delim)))
    return _getlines_impl_generic(stream, delim, chunk_size, _exitstack, "")
Esempio n. 11
0
    def __format__(self, fmt):
        classes = self

        if fmt:
            fmt_orig = fmt
            fmt = fmt[1:].split(fmt[0])
            if len(fmt) % 2:
                classes, item_transform = (self._format_parse_options(
                    fmt.pop(), classes))
            else:
                item_transform = None
            if len(fmt) == 6:
                prefix_suffix = fmt[4:]
                del fmt[4:]
            else:
                prefix_suffix = ('', '')
            if len(fmt) == 4:
                class_prefix_suffix = fmt[2:]
                del fmt[2:]
            else:
                class_prefix_suffix = ('', '')
            if len(fmt) == 2:
                class_delimiter = fmt.pop()
                item_delimiter = fmt.pop()
            else:
                raise ValueError('Illegal format: ' + repr(fmt_orig))

        else:
            item_delimiter = ', '
            class_delimiter = '; '
            item_transform = repr
            prefix_suffix = class_prefix_suffix = ('{', '}')

        if item_transform is not None:
            classes = map(fpartial(map, item_transform), classes)

        s = class_delimiter.join(
            tuple(
                map(methodcaller('join', class_prefix_suffix),
                    map(item_delimiter.join, classes))))
        return s.join(prefix_suffix)
Esempio n. 12
0
def is_dev_null(file, *,
	null_device_paths=(b"/dev/null", b"/dev/zero"),
	null_device_numbers=set() if hasattr(os.stat_result, "st_rdev") else None
):
	assert null_device_paths
	f_stat = os.stat(file)

	if null_device_numbers is not None:
		if not f_stat.st_rdev:
			return False
		if not null_device_numbers:
			null_device_numbers.update(
				map(operator.attrgetter("st_rdev"), map(os.stat, null_device_paths)))
		if null_device_numbers:
			return f_stat.st_rdev in null_device_numbers
		is_dev_null.__kwdefaults__["null_device_numbers"] = None

	return (
		stat.S_ISCHR(f_stat.st_mode) and
		any(map(
			fpartial(os.path.samestat, f_stat), map(os.stat, null_device_paths))))
Esempio n. 13
0
def process_records(records, opts):
	_print = fpartial(print, sep=opts.output_field_separator)

	reuse_records = len(opts.aggregations) > 1
	if reuse_records:
		reuse_records = map(attrgetter('field_index'), opts.aggregations)
		if opts.input_field_separator is False:
			reuse_records = map(attrgetter('start', 'stop'), reuse_records)
		reuse_records = len(opts.aggregations) != len(frozenset(reuse_records))

	for group_key, group_records in records:
		if reuse_records:
			group_records = tuple(group_records)

		aggregated_fields = (
			format(
				agg.aggregator(sized_map(itemgetter(agg.field_index), group_records)),
				agg.format)
			for agg in opts.aggregations)

		if len(opts.groups) == 1:
			_print(group_key, *tuple(aggregated_fields))
		else:
			_print(*tuple(itertools.chain(group_key, aggregated_fields)))
Esempio n. 14
0
def findChapter(subchapterName):
    # goto first chapter by clicking last chapter btn 10 times
    s, e = splitSubchapterName(subchapterName)
    sourceImg = getScreenshot()
    chapter = Configure.getChapter(s)
    template = chapter.labels[0]
    # templateImg = cv.imread(template.path)
    hasChapter, loc = matchTemplate.hasItem(sourceImg, template.getImg(),
                                            template.threshold)
    if hasChapter:
        click(loc[0][0], loc[0][1], 20, 20, 50)
        return

    page = chapter.pageIndex
    count = 12
    btnLeft = Configure.getButton("lastchapter")
    btnright = Configure.getButton("nextchapter")
    imgLeftBtn = btnLeft.getImg()
    imgRightBtn = btnright.getImg()
    hasLeft, locL = matchTemplate.hasItem(sourceImg, imgLeftBtn,
                                          btnLeft.threshold)
    hasRight, locR = matchTemplate.hasItem(sourceImg, imgRightBtn,
                                           btnright.threshold)
    if hasLeft:
        funClickLeft = fpartial(click,
                                x=locL[0][0],
                                y=locL[0][1] - imgLeftBtn.shape[0],
                                w=50,
                                h=-90,
                                deltaT=50)
    else:
        funClickLeft = fpartial(print, "")
    if hasRight:
        funClickRight = fpartial(click,
                                 x=locR[0][0],
                                 y=locR[0][1] - imgRightBtn.shape[0],
                                 w=50,
                                 h=-90,
                                 deltaT=50)
    else:
        funClickRight = fpartial(print, "")
    print("========================== " + str(hasLeft) + " ==== " +
          str(hasRight) + " ==========")
    if not hasLeft:
        print("btn lastChapter not found")
        count = 0
    if (not hasRight) and (not hasLeft):
        return
    print("========================== click left " + str(count) +
          " ==========")
    while (count > 0):
        clickLeft = (10 * random.random()) > 1
        if clickLeft:
            funClickLeft()
            count -= 1
        else:
            funClickRight()
            count += 1
        time.sleep(2)
    extraRight = round(3 * random.random())
    count = page + extraRight
    i = count
    print("========================== click right " + str(count) +
          " ==========")
    while (i > 0):
        clickRight = (10 * random.random()) > 1.5
        if clickRight:
            funClickRight()
            time.sleep(1.5)
            i -= 1
        else:
            funClickLeft()
            time.sleep(2)
            i = min(count, i + 1)
    count = extraRight
    sourceImg = getScreenshot()
    hasLeft, loc = matchTemplate.hasItem(sourceImg, imgLeftBtn,
                                         btnLeft.threshold)
    hasRight, loc = matchTemplate.hasItem(sourceImg, imgRightBtn,
                                          btnright.threshold)
    if not hasRight:
        print("btn lastChapter not found")
        count = 10 - page
    if (not hasRight) and (not hasLeft):
        return
    print("========================== click left " + str(count) +
          " ==========")
    while (count > -1):
        funClickLeft()
        time.sleep(1)
        count -= 1
 def _format_epilog(self, items):
     return '\n'.join(
         reduce(fpartial(peek, list.extend),
                starmap(self._wrap_definition, items)))
Esempio n. 16
0
 def items(self):
     """Returns the attributes as a sequence of name-value tuples"""
     return zip(self.__slots__, map(fpartial(getattr, self),
                                    self.__slots__))
Esempio n. 17
0
 def _item_iters(self):
     return (self.__slots__, map(fpartial(getattr, self), self.__slots__))
Esempio n. 18
0
	def __repr__(self):
		return '{:s}({:s})'.format(
			type(self).__qualname__,
			', '.join(map('{:s}={!r}'.format,
				self.__slots__, map(fpartial(getattr, self), self.__slots__))))
Esempio n. 19
0
def parse_args(args):
    suppress_debug = (None if args and '--help-debug' in args else
                      argparse.SUPPRESS)

    translations.add_fallback(
        DictTranslations(ID_DESCRIPTION=prefix(
            aptsources_cleanup.__doc__, '\n\n\n', reverse=True).strip()))

    ap = MyArgumentParser(
        formatter_class=TerminalHelpFormatter,
        add_help=False,
        description=_('ID_DESCRIPTION'),
        epilog=((_('Author'), 'David P. W. Foerster'),
                (_('Source code and bug tracker location'),
                 'https://github.com/davidfoerster/aptsources-cleanup')))

    ap.add_argument(
        '-y',
        '--yes',
        dest='apply_changes',
        action='store_const',
        const=True,
        help=_('Apply all non-destructive changes without question.'))
    ap.add_argument(
        '-n',
        '--no-act',
        '--dry-run',
        dest='apply_changes',
        action='store_const',
        const=False,
        help=_('Never apply changes; only print what would be done.'))
    noarg_equivalent_schemes = EquivalenceRelation(
        (('http', 'https', 'ftp'), ), settype="ordered")
    ap.add_argument(
        '--equivalent-schemes',
        metavar='SCHEMES',
        type=fpartial(EquivalenceRelation.parse, settype="ordered"),
        default=noarg_equivalent_schemes,
        help=_(
            'Specify URI schemes that you consider equivalent using a list of '
            'equivalence classes delimited by semicolons (";") and elements '
            'delimited by commas (","). Defaults to "{:|,|;|a}". The empty argument '
            'disables this feature.').format(noarg_equivalent_schemes))
    ap.add_argument('-h',
                    '--help',
                    action='help',
                    default=argparse.SUPPRESS,
                    help=_('show this help message and exit'))
    ap.add_argument('--version', action=VersionAction)

    dg = ap.add_argument_group(
        _('Debugging Options'),
        _('For wizards only! Use these if you know and want to test the '
          'application source code.'))
    dg.add_argument(
        '--debug-import-fail',
        '--d-i-f',
        metavar='LEVEL',
        nargs='?',
        type=int,
        const=1,
        default=0,
        help=suppress_debug or _(
            "Force an ImportError for the '{module:s}' module and fail on all "
            "subsequent diagnoses.").format(module='aptsources.sourceslist'))
    debug_sources_dir = './test/sources.list.d'
    dg.add_argument(
        '--debug-sources-dir',
        '--d-s-d',
        metavar='DIR',
        nargs='?',
        const=debug_sources_dir,
        help=suppress_debug or
        _("Load sources list files from this directory instead of the default "
          "root-owned '{default:s}'. If omitted DIR defaults to '{const:s}'."
          ).format(default='/etc/apt/sources.list*', const=debug_sources_dir))
    dg.add_argument(
        '--debug-choices-print',
        '--d-c-p',
        action='store_true',
        default=False,
        help=suppress_debug
        or _('Debug the display of translated and formatted choices options.'))
    dg.add_argument('--help-debug',
                    action='help',
                    default=argparse.SUPPRESS,
                    help=_('Show help for debugging options.'))

    args, unkown = ap.parse_known_args(args)
    if unkown:
        ap.error('\n'.join(
            (_('unrecognized arguments: %s') % ' '.join(unkown),
             _("Use '{help_opt:s}' to display the program help.").format(
                 help_opt='--help'))))

    Choices.debug = args.debug_choices_print

    return args
	def items(self):
		"""Returns the attributes as a sequence of name-value tuples"""
		return zip(self.__slots__, map(fpartial(getattr, self), self.__slots__))
	def _format_epilog(self, items):
		return '\n'.join(reduce(
			fpartial(peek, list.extend), starmap(self._wrap_definition, items)))