Automated fixes from ruff

This commit is contained in:
Kovid Goyal 2023-01-09 18:13:56 +05:30
parent f7f0cf059f
commit d7c31f4a81
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
74 changed files with 260 additions and 141 deletions

View File

@ -810,7 +810,8 @@ def main(args, ext_dir, test_runner):
build_dir = abspath(join(mkdtemp('frozen-'), APPNAME + '.app'))
inc_dir = abspath(mkdtemp('include'))
if args.skip_tests:
test_runner = lambda *a: None
def test_runner(*a):
return None
Freeze(build_dir, ext_dir, inc_dir, test_runner, dont_strip=args.dont_strip, sign_installers=args.sign_installers, notarize=args.notarize)

View File

@ -40,7 +40,8 @@ if py3:
from urllib.parse import urlparse
from urllib.request import BaseHandler, build_opener, Request, urlopen, getproxies, addinfourl
import http.client as httplib
encode_for_subprocess = lambda x: x
def encode_for_subprocess(x):
return x
else:
from future_builtins import map
from urlparse import urlparse

View File

@ -156,7 +156,8 @@ def load_plugins_index():
def convert_node(fields, x, names={}, import_data=None):
name = x.__class__.__name__
conv = lambda x:convert_node(fields, x, names=names, import_data=import_data)
def conv(x):
return convert_node(fields, x, names=names, import_data=import_data)
if name == 'Str':
return x.s.decode('utf-8') if isinstance(x.s, bytes) else x.s
elif name == 'Num':

View File

@ -77,7 +77,8 @@ def to_unicode(raw, encoding='utf-8', errors='strict'):
def patheq(p1, p2):
p = os.path
d = lambda x : p.normcase(p.normpath(p.realpath(p.normpath(x))))
def d(x):
return p.normcase(p.normpath(p.realpath(p.normpath(x))))
if not p1 or not p2:
return False
return d(p1) == d(p2)

View File

@ -552,7 +552,7 @@ class CatalogPlugin(Plugin): # {{{
from calibre.customize.ui import config
from calibre.ptempfile import PersistentTemporaryDirectory
if not type(self) in builtin_plugins and self.name not in config['disabled_plugins']:
if type(self) not in builtin_plugins and self.name not in config['disabled_plugins']:
files_to_copy = [f"{self.name.lower()}.{ext}" for ext in ["ui","py"]]
resources = zipfile.ZipFile(self.plugin_path,'r')

View File

@ -180,7 +180,8 @@ def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'):
print('Running file type plugin %s failed with traceback:'%plugin.name, file=oe)
traceback.print_exc(file=oe)
sys.stdout, sys.stderr = oo, oe
x = lambda j: os.path.normpath(os.path.normcase(j))
def x(j):
return os.path.normpath(os.path.normcase(j))
if occasion == 'postprocess' and x(nfp) != x(path_to_file):
shutil.copyfile(nfp, path_to_file)
nfp = path_to_file

View File

@ -41,18 +41,23 @@ def compile_rule(rule):
if 'with' in mt:
q = icu_lower(rule['query'])
if 'startswith' in mt:
func = lambda filename: icu_lower(filename).startswith(q)
def func(filename):
return icu_lower(filename).startswith(q)
else:
func = lambda filename: icu_lower(filename).endswith(q)
def func(filename):
return icu_lower(filename).endswith(q)
elif 'glob' in mt:
q = compile_glob(rule['query'])
func = lambda filename: q.match(filename) is not None
def func(filename):
return (q.match(filename) is not None)
else:
q = re.compile(rule['query'])
func = lambda filename: q.match(filename) is not None
def func(filename):
return (q.match(filename) is not None)
ans = func
if mt.startswith('not_'):
ans = lambda filename: not func(filename)
def ans(filename):
return (not func(filename))
return ans, rule['action'] == 'add'

View File

@ -1262,7 +1262,8 @@ class DB:
import codecs
from apsw import Shell
if callback is None:
callback = lambda x: x
def callback(x):
return x
uv = int(self.user_version)
with TemporaryFile(suffix='.sql') as fname:
@ -1587,7 +1588,8 @@ class DB:
def compress_covers(self, path_map, jpeg_quality, progress_callback):
cpath_map = {}
if not progress_callback:
progress_callback = lambda book_id, old_sz, new_sz: None
def progress_callback(book_id, old_sz, new_sz):
return None
for book_id, path in path_map.items():
path = os.path.abspath(os.path.join(self.library_path, path, 'cover.jpg'))
try:

View File

@ -47,7 +47,8 @@ def numeric_sort_key(defval, x):
return x if type(x) in (int, float) else defval
IDENTITY = lambda x: x
def IDENTITY(x):
return x
class InvalidLinkTable(Exception):

View File

@ -223,7 +223,8 @@ def has_cover_getter(dbref, book_id, cache):
return ret
fmt_custom = lambda x:list(x) if isinstance(x, tuple) else x
def fmt_custom(x):
return (list(x) if isinstance(x, tuple) else x)
def custom_getter(field, dbref, book_id, cache):

View File

@ -181,7 +181,8 @@ class LibraryDatabase:
self.is_second_db = is_second_db
if progress_callback is None:
progress_callback = lambda x, y:True
def progress_callback(x, y):
return True
self.listeners = set()
backend = self.backend = create_backend(library_path, default_prefs=default_prefs,

View File

@ -237,9 +237,11 @@ class NumericSearch: # {{{
dt = datatype
if is_many and query in {'true', 'false'}:
valcheck = lambda x: True
def valcheck(x):
return True
if datatype == 'rating':
valcheck = lambda x: x is not None and x > 0
def valcheck(x):
return (x is not None and x > 0)
found = set()
for val, book_ids in field_iter():
if valcheck(val):
@ -248,14 +250,18 @@ class NumericSearch: # {{{
if query == 'false':
if location == 'cover':
relop = lambda x,y: not bool(x)
def relop(x, y):
return (not bool(x))
else:
relop = lambda x,y: x is None
def relop(x, y):
return (x is None)
elif query == 'true':
if location == 'cover':
relop = lambda x,y: bool(x)
def relop(x, y):
return bool(x)
else:
relop = lambda x,y: x is not None
def relop(x, y):
return (x is not None)
else:
for k, relop in iteritems(self.operators):
if query.startswith(k):
@ -265,8 +271,10 @@ class NumericSearch: # {{{
relop = self.operators['=']
if dt == 'rating':
cast = lambda x: 0 if x is None else int(x)
adjust = lambda x: x // 2
def cast(x):
return (0 if x is None else int(x))
def adjust(x):
return (x // 2)
else:
# Datatype is empty if the source is a template. Assume float
cast = float if dt in ('float', 'composite', 'half-rating', '') else int

View File

@ -186,7 +186,8 @@ class FilesystemTest(BaseTest):
def test_find_books_in_directory(self):
from calibre.db.adding import find_books_in_directory, compile_rule
strip = lambda files: frozenset({os.path.basename(x) for x in files})
def strip(files):
return frozenset({os.path.basename(x) for x in files})
def q(one, two):
one, two = {strip(a) for a in one}, {strip(b) for b in two}

View File

@ -57,7 +57,8 @@ def run_funcs(self, db, ndb, funcs):
if callable(meth):
meth(*args)
else:
fmt = lambda x:x
def fmt(x):
return x
if meth[0] in {'!', '@', '#', '+', '$', '-', '%'}:
if meth[0] != '+':
fmt = {'!':dict, '@':lambda x:frozenset(x or ()), '#':lambda x:set((x or '').split(',')),
@ -256,12 +257,14 @@ class LegacyTest(BaseTest):
'books_in_series_of':[(0,), (1,), (2,)],
'books_with_same_title':[(Metadata(db.title(0)),), (Metadata(db.title(1)),), (Metadata('1234'),)],
}):
fmt = lambda x: x
def fmt(x):
return x
if meth[0] in {'!', '@'}:
fmt = {'!':dict, '@':frozenset}[meth[0]]
meth = meth[1:]
elif meth == 'get_authors_with_ids':
fmt = lambda val:{x[0]:tuple(x[1:]) for x in val}
def fmt(val):
return {x[0]: tuple(x[1:]) for x in val}
for a in args:
self.assertEqual(fmt(getattr(db, meth)(*a)), fmt(getattr(ndb, meth)(*a)),
f'The method: {meth}() returned different results for argument {a}')

View File

@ -612,9 +612,11 @@ class ReadingTest(BaseTest):
self.assertSetEqual(set(mi.custom_field_keys()), set(pmi.custom_field_keys()))
for field in STANDARD_METADATA_FIELDS | {'#series_index'}:
f = lambda x: x
def f(x):
return x
if field == 'formats':
f = lambda x: x if x is None else tuple(x)
def f(x):
return (x if x is None else tuple(x))
self.assertEqual(f(getattr(mi, field)), f(getattr(pmi, field)),
f'Standard field: {field} not the same for book {book_id}')
self.assertEqual(mi.format_field(field), pmi.format_field(field),

View File

@ -23,20 +23,23 @@ class WritingTest(BaseTest):
def create_getter(self, name, getter=None):
if getter is None:
if name.endswith('_index'):
ans = lambda db:partial(db.get_custom_extra, index_is_id=True,
label=name[1:].replace('_index', ''))
def ans(db):
return partial(db.get_custom_extra, index_is_id=True, label=name[1:].replace('_index', ''))
else:
ans = lambda db:partial(db.get_custom, label=name[1:],
index_is_id=True)
def ans(db):
return partial(db.get_custom, label=name[1:], index_is_id=True)
else:
ans = lambda db:partial(getattr(db, getter), index_is_id=True)
def ans(db):
return partial(getattr(db, getter), index_is_id=True)
return ans
def create_setter(self, name, setter=None):
if setter is None:
ans = lambda db:partial(db.set_custom, label=name[1:], commit=True)
def ans(db):
return partial(db.set_custom, label=name[1:], commit=True)
else:
ans = lambda db:partial(getattr(db, setter), commit=True)
def ans(db):
return partial(getattr(db, setter), commit=True)
return ans
def create_test(self, name, vals, getter=None, setter=None):

View File

@ -408,7 +408,8 @@ def atof(string):
def type_safe_sort_key_function(keyfunc=None):
if keyfunc is None:
keyfunc = lambda x: x
def keyfunc(x):
return x
sentinel = object()
first_value = sentinel

View File

@ -164,11 +164,13 @@ def get_adapter(name, metadata):
elif dt == 'comments':
ans = single_text
elif dt == 'rating':
ans = lambda x: None if x in {None, 0} else min(10, max(0, adapt_number(int, x)))
def ans(x):
return (None if x in {None, 0} else min(10, max(0, adapt_number(int, x))))
elif dt == 'enumeration':
ans = single_text
elif dt == 'composite':
ans = lambda x: x
def ans(x):
return x
if name == 'title':
return lambda x: ans(x) or _('Unknown')

View File

@ -48,7 +48,6 @@ class ANDROID(USBMS):
0x0cf5 : HTC_BCDS,
0x2910 : HTC_BCDS,
0xe77 : HTC_BCDS,
0xff9 : HTC_BCDS,
0x0001 : [0x255],
},

View File

@ -45,9 +45,11 @@ def strip_encoding_declarations(raw, limit=50*1024, preserve_newlines=False):
is_binary = isinstance(raw, bytes)
if preserve_newlines:
if is_binary:
sub = lambda m: b'\n' * m.group().count(b'\n')
def sub(m):
return (b'\n' * m.group().count(b'\n'))
else:
sub = lambda m: '\n' * m.group().count('\n')
def sub(m):
return ('\n' * m.group().count('\n'))
else:
sub = b'' if is_binary else ''
for pat in lazy_encoding_pats(is_binary):

View File

@ -63,9 +63,11 @@ def find_pages(dir, sort_on_mtime=False, verbose=False):
# levels, in which case simply use the filenames.
basename = os.path.basename if len(sep_counts) > 1 else lambda x: x
if sort_on_mtime:
key = lambda x:os.stat(x).st_mtime
def key(x):
return os.stat(x).st_mtime
else:
key = lambda x:numeric_sort_key(basename(x))
def key(x):
return numeric_sort_key(basename(x))
pages.sort(key=key)
if verbose:

View File

@ -193,7 +193,8 @@ class HTMLOutput(OutputFormatPlugin):
# render template
templite = Templite(template_html_data)
toc = lambda: self.generate_html_toc(oeb_book, path, output_dir)
def toc():
return self.generate_html_toc(oeb_book, path, output_dir)
t = templite.render(ebookContent=ebook_content,
prevLink=prevLink, nextLink=nextLink,
has_toc=bool(oeb_book.toc.count()), toc=toc,

View File

@ -500,8 +500,10 @@ class BZZDecoder():
# Decode
mtfno = 3
markerpos = -1
zc = lambda i: self.zpcodec_decode(self.ctx, i)
dc = lambda i, bits: self.decode_binary(self.ctx, i, bits)
def zc(i):
return self.zpcodec_decode(self.ctx, i)
def dc(i, bits):
return self.decode_binary(self.ctx, i, bits)
for i in range(self.xsize):
ctxid = CTXIDS - 1
if ctxid > mtfno:

View File

@ -247,7 +247,8 @@ def test_parse_fields(return_tests=False):
class TestParseFields(unittest.TestCase):
def test_hyperlink(self):
ae = lambda x, y: self.assertEqual(parse_hyperlink(x, None), y)
def ae(x, y):
return self.assertEqual(parse_hyperlink(x, None), y)
ae(r'\l anchor1', {'anchor':'anchor1'})
ae(r'www.calibre-ebook.com', {'url':'www.calibre-ebook.com'})
ae(r'www.calibre-ebook.com \t target \o tt', {'url':'www.calibre-ebook.com', 'target':'target', 'title': 'tt'})
@ -255,13 +256,15 @@ def test_parse_fields(return_tests=False):
ae(r'xxxx \y yyyy', {'url': 'xxxx'})
def test_xe(self):
ae = lambda x, y: self.assertEqual(parse_xe(x, None), y)
def ae(x, y):
return self.assertEqual(parse_xe(x, None), y)
ae(r'"some name"', {'text':'some name'})
ae(r'name \b \i', {'text':'name', 'bold':None, 'italic':None})
ae(r'xxx \y a', {'text':'xxx', 'yomi':'a'})
def test_index(self):
ae = lambda x, y: self.assertEqual(parse_index(x, None), y)
def ae(x, y):
return self.assertEqual(parse_index(x, None), y)
ae(r'', {})
ae(r'\b \c 1', {'bookmark':None, 'columns-per-page': '1'})

View File

@ -64,7 +64,8 @@ class CombinedStyle:
def serialize(self, styles, normal_style):
makeelement = self.namespace.makeelement
w = lambda x: '{{{}}}{}'.format(self.namespace.namespaces['w'], x)
def w(x):
return '{{{}}}{}'.format(self.namespace.namespaces['w'], x)
block = makeelement(styles, 'w:style', w_styleId=self.id, w_type='paragraph')
makeelement(block, 'w:name', w_val=self.name)
makeelement(block, 'w:qFormat')

View File

@ -28,7 +28,8 @@ class Parser:
# No leading zeros, except for numbers in (0, 1) and no trailing zeros for the fractional part
frac = r'\.[0-9]*[1-9]'
number = r'(?:[1-9][0-9]*(?:{0})?)|(?:0{0})|(?:0)'.format(frac)
c = lambda x:regex.compile(x, flags=regex.VERSION1)
def c(x):
return regex.compile(x, flags=regex.VERSION1)
# A step of the form /integer
self.step_pat = c(r'/(%s)' % integer)

View File

@ -811,7 +811,8 @@ class HTMLConverter:
for x, y in [('\xad', ''), ('\xa0', ' '), ('\ufb00', 'ff'), ('\ufb01', 'fi'), ('\ufb02', 'fl'), ('\ufb03', 'ffi'), ('\ufb04', 'ffl')]:
src = src.replace(x, y)
valigner = lambda x: x
def valigner(x):
return x
if 'vertical-align' in css:
valign = css['vertical-align']
if valign in ('sup', 'super', 'sub'):

View File

@ -54,8 +54,10 @@ def reset_field_metadata():
field_metadata = FieldMetadata()
ck = lambda typ: icu_lower(typ).strip().replace(':', '').replace(',', '')
cv = lambda val: val.strip().replace(',', '|')
def ck(typ):
return icu_lower(typ).strip().replace(':', '').replace(',', '')
def cv(val):
return val.strip().replace(',', '|')
class Metadata:

View File

@ -38,7 +38,8 @@ def short_be(buf):
def get_metadata(f):
read = lambda at, amount: _read(f, at, amount)
def read(at, amount):
return _read(f, at, amount)
f.seek(0)
buf = f.read(12)
if buf[4:] == b'ftypLRX2':

View File

@ -1652,7 +1652,8 @@ def metadata_to_opf(mi, as_string=True, default_lang=None):
if mi.tags:
for tag in mi.tags:
factory(DC('subject'), tag)
meta = lambda n, c: factory('meta', name='calibre:'+n, content=c)
def meta(n, c):
return factory('meta', name='calibre:' + n, content=c)
if getattr(mi, 'author_link_map', None) is not None:
meta('author_link_map', dump_dict(mi.author_link_map))
if mi.series:

View File

@ -21,7 +21,8 @@ def get_metadata(stream):
return mi
stream.read(10)
read_i32 = lambda: struct.unpack('<I', stream.read(4))[0]
def read_i32():
return struct.unpack('<I', stream.read(4))[0]
stream.seek(read_i32())
toc_count = read_i32()

View File

@ -96,7 +96,8 @@ def parse_details_page(url, log, timeout, browser, domain):
from calibre.ebooks.metadata.sources.update import search_engines_module
get_data_for_cached_url = search_engines_module().get_data_for_cached_url
except Exception:
get_data_for_cached_url = lambda *a: None
def get_data_for_cached_url(*a):
return None
raw = get_data_for_cached_url(url)
if raw:
log('Using cached details for url:', url)

View File

@ -509,7 +509,8 @@ def identify(log, abort, # {{{
am_rules = compile_rules(am_rules)
# normalize unicode strings
n = lambda x: unicodedata.normalize('NFC', as_unicode(x or '', errors='replace'))
def n(x):
return unicodedata.normalize('NFC', as_unicode(x or '', errors='replace'))
for r in results:
if r.tags:
r.tags = list(map(n, r.tags))

View File

@ -542,7 +542,8 @@ def metadata_to_xmp_packet(mi):
def find_used_namespaces(elem):
getns = lambda x: (x.partition('}')[0][1:] if '}' in x else None)
def getns(x):
return (x.partition('}')[0][1:] if '}' in x else None)
ans = {getns(x) for x in list(elem.attrib) + [elem.tag]}
for child in elem.iterchildren(etree.Element):
ans |= find_used_namespaces(child)

View File

@ -37,7 +37,8 @@ class FDST:
def __str__(self):
ans = ['FDST record']
a = lambda k, v:ans.append('%s: %s'%(k, v))
def a(k, v):
return ans.append('%s: %s' % (k, v))
a('Offset to sections', self.sec_off)
a('Number of section records', self.num_sections)
ans.append('**** %d Sections ****'% len(self.sections))

View File

@ -823,7 +823,8 @@ class MobiReader:
unpack = decompress_doc
elif self.book_header.compression_type == b'\x00\x01':
unpack = lambda x: x
def unpack(x):
return x
else:
raise MobiError('Unknown compression algorithm: %r' % self.book_header.compression_type)
self.mobi_html = b''.join(map(unpack, text_sections))

View File

@ -640,6 +640,7 @@ def convert_color_for_font_tag(val):
rgba = parse_color_string(str(val or ''))
if rgba is None or rgba == 'currentColor':
return str(val)
clamp = lambda x: min(x, max(0, x), 1)
def clamp(x):
return min(x, max(0, x), 1)
rgb = map(clamp, rgba[:3])
return '#' + ''.join(map(lambda x:'%02x' % int(x * 255), rgb))

View File

@ -14,9 +14,12 @@ from calibre.ebooks.mobi.utils import align_block
from polyglot.builtins import iteritems, as_bytes
NULL = 0xffffffff
zeroes = lambda x: b'\0'*x
nulls = lambda x: b'\xff'*x
short = lambda x: pack(b'>H', x)
def zeroes(x):
return (b'\x00' * x)
def nulls(x):
return (b'\xff' * x)
def short(x):
return pack(b'>H', x)
class Header(OrderedDict):

View File

@ -13,7 +13,8 @@ from calibre.ebooks.mobi.writer8.header import Header
TagMeta_ = namedtuple('TagMeta',
'name number values_per_entry bitmask end_flag')
TagMeta = lambda x:TagMeta_(*x)
def TagMeta(x):
return TagMeta_(*x)
EndTagTable = TagMeta(('eof', 0, 0, 0, 1))
# map of mask to number of shifts needed, works with 1 bit and two-bit wide masks

View File

@ -161,7 +161,8 @@ def update_metadata(ebook, new_opf):
def polish_one(ebook, opts, report, customization=None):
rt = lambda x: report('\n### ' + x)
def rt(x):
return report('\n### ' + x)
jacket = None
changed = False
customization = customization or CUSTOMIZATION.copy()

View File

@ -248,7 +248,8 @@ def apply_func_to_match_groups(match, func=icu_upper, handle_entities=handle_ent
found_groups = False
i = 0
parts, pos = [], match.start()
f = lambda text:handle_entities(text, func)
def f(text):
return handle_entities(text, func)
while True:
i += 1
try:
@ -268,7 +269,8 @@ def apply_func_to_match_groups(match, func=icu_upper, handle_entities=handle_ent
def apply_func_to_html_text(match, func=icu_upper, handle_entities=handle_entities):
''' Apply the specified function only to text between HTML tag definitions. '''
f = lambda text:handle_entities(text, func)
def f(text):
return handle_entities(text, func)
parts = re.split(r'(<[^>]+>)', match.group())
parts = (x if x.startswith('<') else f(x) for x in parts)
return ''.join(parts)

View File

@ -116,8 +116,6 @@ if another paragraph_def is found, the state changes to collect_tokens.
'sect-note_' : 'endnotes-in-section',
# list=> ls
'list-text_' : 'list-text',
# this line must be wrong because it duplicates an earlier one
'list-text_' : 'list-text',
'list______' : 'list',
'list-lev-d' : 'list-level-definition',
'list-cardi' : 'list-cardinal-numbering',

View File

@ -136,7 +136,6 @@ class Tokenize:
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
"\\~": "\\~ ",
"\\_": "\\_ ",
"\\:": "\\: ",
"\\-": "\\- ",

View File

@ -70,11 +70,15 @@ class ConfigWidget(QWidget, Ui_ConfigWidget):
if isinstance(extra_customization_message, list):
self.opt_extra_customization = []
if len(extra_customization_message) > 6:
row_func = lambda x, y: ((x//2) * 2) + y
col_func = lambda x: x%2
def row_func(x, y):
return (x // 2 * 2 + y)
def col_func(x):
return (x % 2)
else:
row_func = lambda x, y: x*2 + y
col_func = lambda x: 0
def row_func(x, y):
return (x * 2 + y)
def col_func(x):
return 0
for i, m in enumerate(extra_customization_message):
label_text, tt = parse_msg(m)

View File

@ -274,11 +274,15 @@ class ExtraCustomization(DeviceConfigTab): # {{{
if isinstance(extra_customization_message, list):
self.opt_extra_customization = []
if len(extra_customization_message) > 6:
row_func = lambda x, y: ((x//2) * 2) + y
col_func = lambda x: x%2
def row_func(x, y):
return (x // 2 * 2 + y)
def col_func(x):
return (x % 2)
else:
row_func = lambda x, y: x*2 + y
col_func = lambda x: 0
def row_func(x, y):
return (x * 2 + y)
def col_func(x):
return 0
for i, m in enumerate(extra_customization_message):
label_text, tt = parse_msg(m)

View File

@ -567,7 +567,8 @@ class CustomRecipes(Dialog):
l.addWidget(self.bb)
self.list_actions = []
la = lambda *args:self.list_actions.append(args)
def la(*args):
return self.list_actions.append(args)
la('plus.png', _('&New recipe'), _('Create a new recipe from scratch'), self.add_recipe)
la('news.png', _('Customize &builtin recipe'), _('Customize a builtin news download source'), self.customize_recipe)
la('document_open.png', _('Load recipe from &file'), _('Load a recipe from a file'), self.load_recipe)

View File

@ -127,7 +127,8 @@ def read_theme_from_folder(path):
return int(x)
except Exception:
return -1
g = lambda x, defval='': metadata.get(x, defval)
def g(x, defval=''):
return metadata.get(x, defval)
theme = Theme(g('title'), g('author'), safe_int(g('version', -1)), g('description'), g('license', 'Unknown'), g('url', None))
ans = Report(path, name_map, extra, missing, theme)

View File

@ -11,10 +11,14 @@ from calibre.ebooks.lrf.fonts import LIBERATION_FONT_MAP
from calibre.ebooks.hyphenate import hyphenate_word
from polyglot.builtins import string_or_bytes
WEIGHT_MAP = lambda wt : int((wt/10)-1)
NULL = lambda a, b: a
COLOR = lambda a, b: QColor(*a)
WEIGHT = lambda a, b: WEIGHT_MAP(a)
def WEIGHT_MAP(wt):
return int(wt / 10 - 1)
def NULL(a, b):
return a
def COLOR(a, b):
return QColor(*a)
def WEIGHT(a, b):
return WEIGHT_MAP(a)
class PixmapItem(QGraphicsPixmapItem):

View File

@ -783,7 +783,8 @@ if __name__ == '__main__':
ids = sorted(db.all_ids(), reverse=True)
ids = tuple(zip(ids[0::2], ids[1::2]))
gm = partial(db.get_metadata, index_is_id=True, get_cover=True, cover_as_data=True)
get_metadata = lambda x:list(map(gm, ids[x]))
def get_metadata(x):
return list(map(gm, ids[x]))
d = CompareMany(list(range(len(ids))), get_metadata, db.field_metadata, db=db)
d.exec()
for changed, mi in itervalues(d.accepted):

View File

@ -181,7 +181,8 @@ class ResultsModel(QAbstractTableModel): # {{{
return None
def sort(self, col, order=Qt.SortOrder.AscendingOrder):
key = lambda x: x
def key(x):
return x
if col == 0:
key = attrgetter('gui_rank')
elif col == 1:
@ -196,7 +197,8 @@ class ResultsModel(QAbstractTableModel): # {{{
elif col == 3:
key = attrgetter('has_cached_cover_url')
elif key == 4:
key = lambda x: bool(x.comments)
def key(x):
return bool(x.comments)
self.beginResetModel()
self.results.sort(key=key, reverse=order==Qt.SortOrder.AscendingOrder)

View File

@ -267,7 +267,8 @@ class TagBrowserMixin: # {{{
db = self.current_db
if category == 'series':
key = lambda x:sort_key(title_sort(x))
def key(x):
return sort_key(title_sort(x))
else:
key = sort_key

View File

@ -69,7 +69,8 @@ def pygments_lexer(filename):
from pygments.util import ClassNotFound
except ImportError:
return None
glff = lambda n: get_lexer_for_filename(n, stripnl=False)
def glff(n):
return get_lexer_for_filename(n, stripnl=False)
try:
return glff(filename)
except ClassNotFound:

View File

@ -423,7 +423,8 @@ class Diff(Dialog):
self.busy.setVisible(True)
return True
kwargs = lambda name: {'context':self.context, 'beautify':self.beautify, 'syntax':syntax_map.get(name, None)}
def kwargs(name):
return {'context': self.context, 'beautify': self.beautify, 'syntax': syntax_map.get(name, None)}
if isinstance(changed_names, dict):
for name, other_name in sorted(iteritems(changed_names), key=lambda x:numeric_sort_key(x[0])):

View File

@ -85,7 +85,8 @@ def find_closest_containing_tag(block, offset, max_tags=sys.maxsize):
''' Find the closest containing tag. To find it, we search for the first
opening tag that does not have a matching closing tag before the specified
position. Search through at most max_tags. '''
prev_tag_boundary = lambda b, o: next_tag_boundary(b, o, forward=False)
def prev_tag_boundary(b, o):
return next_tag_boundary(b, o, forward=False)
block, boundary = prev_tag_boundary(block, offset)
if block is None:

View File

@ -13,7 +13,8 @@ from calibre.gui2.tweak_book.editor.smarts.utils import (
get_text_before_cursor, get_leading_whitespace_on_block as lw,
smart_home, smart_backspace, smart_tab)
get_leading_whitespace_on_block = lambda editor, previous=False: expand_tabs(lw(editor, previous=previous))
def get_leading_whitespace_on_block(editor, previous=False):
return expand_tabs(lw(editor, previous=previous))
tw = 4 # The tab width (hardcoded to the pep8 value)

View File

@ -16,7 +16,8 @@ def get_text_around_cursor(editor, before=True):
get_text_before_cursor = get_text_around_cursor
get_text_after_cursor = lambda editor: get_text_around_cursor(editor, before=False)
def get_text_after_cursor(editor):
return get_text_around_cursor(editor, before=False)
def is_cursor_on_wrapped_line(editor):

View File

@ -26,7 +26,8 @@ from calibre.utils.icu import string_length as strlen
from calibre.utils.localization import localize_user_manual_link
from polyglot.builtins import codepoint_to_chr, iteritems, itervalues
string_length = lambda x: strlen(str(x)) # Needed on narrow python builds, as subclasses of unicode dont work
def string_length(x):
return strlen(str(x)) # Needed on narrow python builds, as subclasses of unicode dont work
KEY = Qt.Key.Key_J
MODIFIER = Qt.KeyboardModifier.MetaModifier if ismacos else Qt.KeyboardModifier.ControlModifier
@ -97,10 +98,12 @@ def escape_funcs():
if escape is None:
escapem = {('\\' + x):codepoint_to_chr(i+1) for i, x in enumerate('\\${}')}
escape_pat = re.compile('|'.join(map(re.escape, escapem)))
escape = lambda x: escape_pat.sub(lambda m: escapem[m.group()], x.replace(r'\\', '\x01'))
def escape(x):
return escape_pat.sub(lambda m: escapem[m.group()], x.replace('\\\\', '\x01'))
unescapem = {v:k[1] for k, v in iteritems(escapem)}
unescape_pat = re.compile('|'.join(unescapem))
unescape = lambda x:unescape_pat.sub(lambda m:unescapem[m.group()], x)
def unescape(x):
return unescape_pat.sub(lambda m: unescapem[m.group()], x)
return escape, unescape

View File

@ -64,9 +64,11 @@ class SimpleUserData(QTextBlockUserData):
class SyntaxHighlighter:
create_formats_func = lambda highlighter: {}
def create_formats_func(highlighter):
return {}
spell_attributes = ()
tag_ok_for_spell = lambda x: False
def tag_ok_for_spell(x):
return False
user_data_factory = SimpleUserData
def __init__(self):

View File

@ -142,7 +142,8 @@ class Declaration(QWidget):
def do_layout(self):
fm = self.fontMetrics()
bounding_rect = lambda text: fm.boundingRect(0, 0, 10000, 10000, Cell.FLAGS, text)
def bounding_rect(text):
return fm.boundingRect(0, 0, 10000, 10000, Cell.FLAGS, text)
line_spacing = 2
side_margin = Cell.SIDE_MARGIN
self.rows = []

View File

@ -806,7 +806,8 @@ class InsertSemantics(Dialog):
return QSize(800, 600)
def create_known_type_map(self):
_ = lambda x: x
def _(x):
return x
self.epubtype_guide_map = {v: k for k, v in guide_epubtype_map.items()}
self.known_type_map = {
'titlepage': _('Title page'),

View File

@ -172,7 +172,8 @@ class BookmarkManager(QWidget):
def set_bookmarks(self, bookmarks=()):
csb = self.current_sort_by
if csb in ('name', 'title'):
sk = lambda x: primary_sort_key(x['title'])
def sk(x):
return primary_sort_key(x['title'])
elif csb == 'timestamp':
sk = itemgetter('timestamp')
else:

View File

@ -363,9 +363,11 @@ def search_in_name(name, search_query, ctx_size=75):
else:
spans = []
miter = lambda: spans
def miter():
return spans
if raw:
a = lambda s, l: spans.append((s, s + l))
def a(s, l):
return spans.append((s, s + l))
primary_collator_without_punctuation().find_all(search_query.text, raw, a, search_query.mode == 'word')
for (start, end) in miter():

View File

@ -437,21 +437,26 @@ class ResultCache(SearchQueryParser): # {{{
if val_func is None:
loc = self.field_metadata[location]['rec_index']
val_func = lambda item, loc=loc: item[loc]
def val_func(item, loc=loc):
return item[loc]
q = ''
cast = adjust = lambda x: x
dt = self.field_metadata[location]['datatype']
if query == 'false':
if dt == 'rating' or location == 'cover':
relop = lambda x,y: not bool(x)
def relop(x, y):
return (not bool(x))
else:
relop = lambda x,y: x is None
def relop(x, y):
return (x is None)
elif query == 'true':
if dt == 'rating' or location == 'cover':
relop = lambda x,y: bool(x)
def relop(x, y):
return bool(x)
else:
relop = lambda x,y: x is not None
def relop(x, y):
return (x is not None)
else:
relop = None
for k in self.numeric_search_relops.keys():
@ -462,14 +467,19 @@ class ResultCache(SearchQueryParser): # {{{
(p, relop) = self.numeric_search_relops['=']
if dt == 'int':
cast = lambda x: int(x)
def cast(x):
return int(x)
elif dt == 'rating':
cast = lambda x: 0 if x is None else int(x)
adjust = lambda x: x//2
def cast(x):
return (0 if x is None else int(x))
def adjust(x):
return (x // 2)
elif dt in ('float', 'composite'):
cast = lambda x : float(x)
def cast(x):
return float(x)
else: # count operation
cast = (lambda x: int(x))
def cast(x):
return int(x)
if len(query) > 1:
mult = query[-1:].lower()
@ -720,9 +730,8 @@ class ResultCache(SearchQueryParser): # {{{
if fm['is_multiple'] and \
len(query) > 1 and query.startswith('#') and \
query[1:1] in '=<>!':
vf = lambda item, loc=fm['rec_index'], \
ms=fm['is_multiple']['cache_to_list']:\
len(item[loc].split(ms)) if item[loc] is not None else 0
def vf(item, loc=fm['rec_index'], ms=fm['is_multiple']['cache_to_list']):
return (len(item[loc].split(ms)) if item[loc] is not None else 0)
return self.get_numeric_matches(location, query[1:],
candidates, val_func=vf)

View File

@ -1261,7 +1261,7 @@ class CatalogBuilder:
else:
# Validate custom field is usable as a genre source
field_md = self.db.metadata_for_field(self.opts.genre_source_field)
if field_md is None or not field_md['datatype'] in ['enumeration', 'text']:
if field_md is None or field_md['datatype'] not in ['enumeration', 'text']:
all_custom_fields = self.db.custom_field_keys()
eligible_custom_fields = []
for cf in all_custom_fields:

View File

@ -188,7 +188,8 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
# we need to do it before we call initialize_dynamic
if apply_default_prefs and default_prefs is not None:
if progress_callback is None:
progress_callback = lambda x, y: True
def progress_callback(x, y):
return True
dbprefs = DBPrefs(self)
progress_callback(None, len(default_prefs))
for i, key in enumerate(default_prefs):
@ -1972,32 +1973,39 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
icon_map[category] = icon
datatype = cat['datatype']
avgr = lambda x: 0.0 if x.rc == 0 else x.rt/x.rc
def avgr(x):
return (0.0 if x.rc == 0 else x.rt / x.rc)
# Duplicate the build of items below to avoid using a lambda func
# in the main Tag loop. Saves a few %
if datatype == 'rating':
formatter = (lambda x:'\u2605'*int(x//2))
avgr = lambda x: x.n
def formatter(x):
return ('' * int(x // 2))
def avgr(x):
return x.n
# eliminate the zero ratings line as well as count == 0
items = [v for v in tcategories[category].values() if v.c > 0 and v.n != 0]
elif category == 'authors':
# Clean up the authors strings to human-readable form
formatter = (lambda x: x.replace('|', ','))
def formatter(x):
return x.replace('|', ',')
items = [v for v in tcategories[category].values() if v.c > 0]
elif category == 'languages':
# Use a human readable language string
formatter = calibre_langcode_to_name
items = [v for v in tcategories[category].values() if v.c > 0]
else:
formatter = (lambda x:str(x))
def formatter(x):
return str(x)
items = [v for v in tcategories[category].values() if v.c > 0]
# sort the list
if sort == 'name':
kf = lambda x:sort_key(x.s)
def kf(x):
return sort_key(x.s)
reverse=False
elif sort == 'popularity':
kf = lambda x: x.c
def kf(x):
return x.c
reverse=True
else:
kf = avgr
@ -3597,7 +3605,8 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
def move_library_to(self, newloc, progress=None):
if progress is None:
progress = lambda x:x
def progress(x):
return x
if not os.path.exists(newloc):
os.makedirs(newloc)
old_dirs = set()

View File

@ -1136,7 +1136,8 @@ X-GNOME-UsesNotifications=true
def get_appdata():
_ = lambda x: x # Make sure the text below is not translated, but is marked for translation
def _(x):
return x # Make sure the text below is not translated, but is marked for translation
return {
'calibre-gui': {
'name':'calibre',

View File

@ -19,7 +19,8 @@ NS_MAP = {
'manifest': 'http://openoffice.org/2001/manifest',
}
XPath = lambda x: etree.XPath(x, namespaces=NS_MAP)
def XPath(x):
return etree.XPath(x, namespaces=NS_MAP)
BUILTIN_LOCALES = {'en-US', 'en-GB', 'es-ES'}

View File

@ -2167,7 +2167,6 @@ utf8enc2latex_mapping = { # {{{
# Items from simple list
'\u0106': "{\\a\\'C}",
'\u0408': '{\\CYRJE}',
'\u20ac': '{\\texteuro}',
'\u2191': '{\\textuparrow}',
'\u0493': '{\\cyrghcrs}',
'\u2116': '{\\textnumero}',

View File

@ -151,7 +151,8 @@ def dt_factory(time_t, assume_utc=False, as_utc=True):
return dt.astimezone(_utc_tz if as_utc else _local_tz)
safeyear = lambda x: min(max(x, MINYEAR), MAXYEAR)
def safeyear(x):
return min(max(x, MINYEAR), MAXYEAR)
def qt_to_dt(qdate_or_qdatetime, as_utc=True):

View File

@ -231,7 +231,8 @@ def capitalize(x):
try:
swapcase = _icu.swap_case
except AttributeError: # For people running from source
swapcase = lambda x:x.swapcase()
def swapcase(x):
return x.swapcase()
find = make_two_arg_func(collator, 'find')
primary_find = make_two_arg_func(primary_collator, 'find')

View File

@ -120,7 +120,8 @@ class TestICU(unittest.TestCase):
self.ae((0, 5), icu.primary_no_punc_find('abcd', 'ab cd'))
# test find all
m = []
a = lambda p,l : m.append((p, l))
def a(p, l):
return m.append((p, l))
icu.primary_collator_without_punctuation().find_all('a', 'a a🐱a', a)
self.ae(m, [(0, 1), (2, 1), (5, 1)])
# test find whole words

View File

@ -334,9 +334,11 @@ class Tester(SearchQueryParser):
if location in self.fields.keys():
getter = operator.itemgetter(self.fields[location])
elif location == 'all':
getter = lambda y: ''.join(x if x else '' for x in y)
def getter(y):
return ''.join(x if x else '' for x in y)
else:
getter = lambda x: ''
def getter(x):
return ''
if not query:
return set()

View File

@ -108,7 +108,6 @@ class WMF:
247: 'CreatePalette',
248: 'CreateBrush',
322: 'DibCreatePatternBrush',
496: 'DeleteObject',
505: 'CreatePatternBrush',
762: 'CreatePenIndirect',
763: 'CreateFontIndirect',

View File

@ -745,7 +745,8 @@ by William Shakespeare
def test_select_shakespeare(self):
document = html.document_fromstring(self.HTML_SHAKESPEARE)
select = Select(document)
count = lambda s: sum(1 for r in select(s))
def count(s):
return sum(1 for r in select(s))
# Data borrowed from http://mootools.net/slickspeed/