From 03e3e8a83943c00389df0236a410e29f24d0760c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Mon, 11 Sep 2023 17:59:03 +0200 Subject: [PATCH 1/2] E228 and E225 in groups,interfaces,modules,plot --- src/sage/groups/cubic_braid.py | 24 +-- src/sage/groups/finitely_presented.py | 10 +- src/sage/groups/finitely_presented_named.py | 4 +- src/sage/groups/fqf_orthogonal.py | 6 +- src/sage/groups/free_group.py | 22 +-- src/sage/groups/libgap_morphism.py | 4 +- src/sage/interfaces/axiom.py | 26 +-- src/sage/interfaces/four_ti_2.py | 4 +- src/sage/interfaces/frobby.py | 20 +-- src/sage/interfaces/gap.py | 54 +++---- src/sage/interfaces/gap3.py | 4 +- src/sage/interfaces/genus2reduction.py | 18 +-- src/sage/interfaces/gnuplot.py | 8 +- src/sage/interfaces/interface.py | 38 ++--- src/sage/interfaces/jmoldata.py | 4 +- src/sage/interfaces/lisp.py | 18 +-- src/sage/interfaces/macaulay2.py | 32 ++-- src/sage/interfaces/magma_free.py | 2 +- src/sage/interfaces/maxima.py | 16 +- src/sage/interfaces/maxima_abstract.py | 60 +++---- src/sage/interfaces/maxima_lib.py | 150 +++++++++--------- src/sage/interfaces/mupad.py | 30 ++-- src/sage/interfaces/mwrank.py | 2 +- src/sage/interfaces/octave.py | 18 +-- src/sage/interfaces/psage.py | 6 +- src/sage/interfaces/qepcad.py | 8 +- src/sage/interfaces/quit.py | 2 +- src/sage/interfaces/r.py | 38 ++--- src/sage/interfaces/scilab.py | 8 +- src/sage/interfaces/singular.py | 60 +++---- src/sage/interfaces/tests.py | 6 +- src/sage/interfaces/tides.py | 114 ++++++------- src/sage/modules/free_module.py | 52 +++--- src/sage/modules/free_module_morphism.py | 14 +- ...free_quadratic_module_integer_symmetric.py | 12 +- src/sage/modules/matrix_morphism.py | 2 +- .../modules/vector_callable_symbolic_dense.py | 2 +- src/sage/plot/animate.py | 4 +- src/sage/plot/circle.py | 4 +- src/sage/plot/density_plot.py | 2 +- src/sage/plot/ellipse.py | 6 +- src/sage/plot/hyperbolic_regular_polygon.py | 8 +- src/sage/plot/matrix_plot.py | 40 ++--- src/sage/plot/misc.py | 14 +- src/sage/plot/plot.py | 14 +- src/sage/plot/plot_field.py | 2 +- 46 files changed, 496 insertions(+), 496 deletions(-) diff --git a/src/sage/groups/cubic_braid.py b/src/sage/groups/cubic_braid.py index f49293e9924..555c42c3797 100644 --- a/src/sage/groups/cubic_braid.py +++ b/src/sage/groups/cubic_braid.py @@ -805,9 +805,9 @@ def _repr_(self): Assion group on 2 strands of type U """ if self._cbg_type == CubicBraidGroup.type.Coxeter: - return "Cubic Braid group on %s strands"%(self.strands()) + return "Cubic Braid group on %s strands" % (self.strands()) else: - return "Assion group on %s strands of type %s"%(self.strands() ,self._cbg_type.value) + return "Assion group on %s strands of type %s" % (self.strands() ,self._cbg_type.value) def index_set(self): r""" @@ -901,7 +901,7 @@ def _internal_test_attached_group(self, attached_group, tester): elem = self.an_element() att_grp_elem = attached_group(elem) if self.is_finite() and self.strands() <= 7: # not realistic for larger number of strands - att_grp_elem_back= self(att_grp_elem) + att_grp_elem_back = self(att_grp_elem) tester.assertEqual(att_grp_elem_back, elem) return @@ -1161,14 +1161,14 @@ def create_sympl_realization(self, m): # computing a hyperbolic decomposition basis with respect # to the invariant bilinear form. # ----------------------------------------------------------- - xbas =[bas[mhalf -i -1] for i in range(mhalf)] - ybas =[bas[mhalf +i] for i in range(mhalf)] + xbas = [bas[mhalf - i - 1] for i in range(mhalf)] + ybas = [bas[mhalf + i] for i in range(mhalf)] # ----------------------------------------------------------- # computing the List of transvection vectors according to # the Assion paper, page 292. # ----------------------------------------------------------- - transvections =[xbas[0]] # t_1 = x_1 + transvections = [xbas[0]] # t_1 = x_1 for i in range(mhalf-1): transvections.append(ybas[i]) # t_{2i} = y_i transvections.append(xbas[i] + xbas[i+1]) # t_{2i+1} = x_j + x_(j+1) @@ -1234,26 +1234,26 @@ def create_unitary_realization(self, m): # computing a orthonormal basis with respect # to the invariant bilinear form. # ----------------------------------------------------------- - xbas =[] + xbas = [] for i in range(m): if 2*i == m-1: xbas.append(bas[i]) else: - xbas.append(a*bas[i] + a.frobenius()*bas[m-1 -i]) + xbas.append(a*bas[i] + a.frobenius()*bas[m-1 - i]) # ----------------------------------------------------------- # computing the List of transvection vectors according to # Assion paper, page 293. # ----------------------------------------------------------- - transvections =[xbas[0]] # t_1 = x_1 + transvections = [xbas[0]] # t_1 = x_1 if m > 1: transvections.append(xbas[0]+xbas[1]+xbas[2]) # t_2 = x_1 + x_2 + x_3 for j in range(mthird): pos = 3*(j+1)-1 transvections.append(xbas[pos-1]) # t_{3i} = x_{3i-1} - if pos +1 < m: + if pos + 1 < m: transvections.append(xbas[pos-1]+xbas[pos]+xbas[pos+1]) # t_{3i+1} = x_{3i-1} + x_{3i} + x_{3i+1} - if pos +3 < m: + if pos + 3 < m: transvections.append(xbas[pos+1]+xbas[pos+2]+xbas[pos+3]) # t_{3i+2} = x_{3i+1} + x_{3i+2} + x_{3i+3} # ----------------------------------------------------------- @@ -1264,7 +1264,7 @@ def create_unitary_realization(self, m): def transvec2mat(v, bas=bas, bform=bform, fact=a): # note x does not change under conjugation, since it belongs to standard basis - t = [x + fact *(x * bform * v.conjugate()) * v for x in bas] + t = [x + fact * (x * bform * v.conjugate()) * v for x in bas] return matrix(F, t) # ------------------------------------------------------------------------------ diff --git a/src/sage/groups/finitely_presented.py b/src/sage/groups/finitely_presented.py index f1ba2d8940f..bd980632a74 100644 --- a/src/sage/groups/finitely_presented.py +++ b/src/sage/groups/finitely_presented.py @@ -643,7 +643,7 @@ def rules(self): bfg = self._monoid_isomorphism.PreImagesRepresentative(bfpmon) btz = bfg.UnderlyingElement().TietzeWordAbstractWord(self._free_group.gap().GeneratorsOfGroup()) bf = self._free_group(btz.sage()) - dic[af]=bf + dic[af] = bf return dic def is_confluent(self): @@ -826,7 +826,7 @@ def _repr_(self): """ gens = ', '.join(self.variable_names()) rels = ', '.join([ str(r) for r in self.relations() ]) - return 'Finitely presented group ' + '< '+ gens + ' | ' + rels + ' >' + return 'Finitely presented group ' + '< ' + gens + ' | ' + rels + ' >' def _latex_(self): """ @@ -1112,7 +1112,7 @@ def direct_product(self, H, reduced=False, new_names=True): name_itr = _lexi_gen() # Python generator for lexicographical variable names gen_names = [next(name_itr) for i in GAP_gens] else: - gen_names= [str(g) for g in self.gens()] + [str(g) for g in H.gens()] + gen_names = [str(g) for g in self.gens()] + [str(g) for g in H.gens()] # Build the direct product in Sage for better variable names ret_F = FreeGroup(gen_names) ret_rls = tuple([ret_F(rel_word.TietzeWordAbstractWord(GAP_gens).sage()) @@ -1313,10 +1313,10 @@ def _element_constructor_(self, *args, **kwds): sage: H([1, 2, 1, -2]) # indirect doctest a*b*a*b^-1 """ - if len(args)!=1: + if len(args) != 1: return self.element_class(self, *args, **kwds) x = args[0] - if x==1: + if x == 1: return self.one() try: P = x.parent() diff --git a/src/sage/groups/finitely_presented_named.py b/src/sage/groups/finitely_presented_named.py index 177f7908895..d1024079cc7 100644 --- a/src/sage/groups/finitely_presented_named.py +++ b/src/sage/groups/finitely_presented_named.py @@ -196,7 +196,7 @@ def FinitelyGeneratedAbelianPresentation(int_list): invariants = FGP_Module(ZZ**(len(int_list)), col_sp).invariants() name_gen = _lexi_gen() F = FreeGroup([next(name_gen) for i in invariants]) - ret_rls = [F([i+1])**invariants[i] for i in range(len(invariants)) if invariants[i]!=0] + ret_rls = [F([i+1])**invariants[i] for i in range(len(invariants)) if invariants[i] != 0] # Build commutator relations gen_pairs = [[F.gen(i),F.gen(j)] for i in range(F.ngens()-1) for j in range(i+1,F.ngens())] @@ -285,7 +285,7 @@ def commutator(a, b): # Third set of relations: [z, yi] = 1 r3 = [commutator(z, y[i]) for i in range(n)] # Fourth set of relations: [xi, yi] = 1 for i != j - r4 = [commutator(x[i], y[j]) for i in range(n) for j in range(n) if i!=j] + r4 = [commutator(x[i], y[j]) for i in range(n) for j in range(n) if i != j] rls = r1 + r2 + r3 + r4 from sage.sets.primes import Primes diff --git a/src/sage/groups/fqf_orthogonal.py b/src/sage/groups/fqf_orthogonal.py index 32a434d3bd9..4ce3e59df18 100644 --- a/src/sage/groups/fqf_orthogonal.py +++ b/src/sage/groups/fqf_orthogonal.py @@ -377,7 +377,7 @@ def _repr_(self): [ 0 2/3] generated by 2 elements """ - return "Group of isometries of \n%s\ngenerated by %s elements"%(self.invariant_form(), len(self.gens())) + return "Group of isometries of \n%s\ngenerated by %s elements" % (self.invariant_form(), len(self.gens())) class ActionOnFqf(Action): r""" @@ -544,7 +544,7 @@ def orbits(G, L): raise ValueError("torsion quadratic modules are not isometric") n = len(A.smith_form_gens()) # separating the different primes here would speed things up - b_cand = [[b for b in B if b.q()==a.q() and b.order() == a.order()] for a in A.smith_form_gens()] + b_cand = [[b for b in B if b.q() == a.q() and b.order() == a.order()] for a in A.smith_form_gens()] G = B.orthogonal_group(tuple()) ambient = G.ambient() @@ -566,7 +566,7 @@ def orbits(G, L): a = A.smith_form_gens()[i] card = ZZ.prod(A.smith_form_gen(k).order() for k in range(i+1)) for b in b_cand[i]: - if all(b.b(f[k])==a.b(A.smith_form_gens()[k]) for k in range(i)): + if all(b.b(f[k]) == a.b(A.smith_form_gens()[k]) for k in range(i)): fnew = f + [b] # check that the elements of fnew are independent if B.submodule(fnew).cardinality() == card: diff --git a/src/sage/groups/free_group.py b/src/sage/groups/free_group.py index 0c51deafc64..4db145528a4 100644 --- a/src/sage/groups/free_group.py +++ b/src/sage/groups/free_group.py @@ -213,20 +213,20 @@ def __init__(self, parent, x): l = x.Tietze() except AttributeError: l = list(x) - if len(l)>0: + if len(l) > 0: if min(l) < -parent.ngens() or parent.ngens() < max(l): raise ValueError('generators not in the group') if 0 in l: raise ValueError('zero does not denote a generator') - i=0 - while i0: - i=i-1 + if i > 0: + i = i-1 else: - i=i+1 + i = i+1 AbstractWordTietzeWord = libgap.eval('AbstractWordTietzeWord') x = AbstractWordTietzeWord(l, parent.gap().GeneratorsOfGroup()) ElementLibGAP.__init__(self, parent, x) @@ -788,7 +788,7 @@ def _repr_(self): sage: G._repr_() 'Free Group on generators {a, b}' """ - return 'Free Group on generators {'+ ', '.join(self.variable_names()) + '}' + return 'Free Group on generators {' + ', '.join(self.variable_names()) + '}' def rank(self): """ @@ -870,10 +870,10 @@ def _element_constructor_(self, *args, **kwds): ... TypeError: 'sage.rings.integer.Integer' object is not iterable """ - if len(args)!=1: + if len(args) != 1: return self.element_class(self, *args, **kwds) x = args[0] - if x==1 or x == [] or x == (): + if x == 1 or x == [] or x == (): return self.one() try: P = x.parent() @@ -885,7 +885,7 @@ def _element_constructor_(self, *args, **kwds): return self([i.sign()*(self._names.index(P._names[abs(i)-1])+1) for i in x.Tietze()]) else: - raise ValueError('generators of %s not in the group'%x) + raise ValueError('generators of %s not in the group' % x) return self.element_class(self, x, **kwds) def abelian_invariants(self): diff --git a/src/sage/groups/libgap_morphism.py b/src/sage/groups/libgap_morphism.py index 93f33bf68a4..58423e4f755 100644 --- a/src/sage/groups/libgap_morphism.py +++ b/src/sage/groups/libgap_morphism.py @@ -546,9 +546,9 @@ def preimage(self, S): phi = self.gap() from sage.groups.perm_gps.permgroup import PermutationGroup_generic if not isinstance(S, (ParentLibGAP, PermutationGroup_generic)): - raise TypeError("%s must be a GAP or permutation group of %s"%(S, self)) + raise TypeError("%s must be a GAP or permutation group of %s" % (S, self)) if not self.codomain().gap().IsSubgroup(S.gap()).sage(): - raise ValueError("%s must be a subgroup of %s"%(S, self)) + raise ValueError("%s must be a subgroup of %s" % (S, self)) preimage = phi.PreImage(S.gap()) return self.domain()._subgroup_constructor(preimage) diff --git a/src/sage/interfaces/axiom.py b/src/sage/interfaces/axiom.py index 83f9cb95817..939a142aa70 100644 --- a/src/sage/interfaces/axiom.py +++ b/src/sage/interfaces/axiom.py @@ -275,7 +275,7 @@ def _read_in_file_command(self, filename): # For some reason this trivial comp # keeps certain random freezes from occurring. Do not remove this. # The space before the \n is also important. - return ')read %s \n'%filename + return ')read %s \n' % filename def _quit_string(self): """ @@ -384,11 +384,11 @@ def set(self, var, value): '2' """ - cmd = '%s := %s'%(var, value) + cmd = '%s := %s' % (var, value) out = self._eval_line(cmd, reformat=False) if out.find("error") != -1: - raise TypeError("Error executing code in Axiom\nCODE:\n\t%s\nAxiom ERROR:\n\t%s"%(cmd, out)) + raise TypeError("Error executing code in Axiom\nCODE:\n\t%s\nAxiom ERROR:\n\t%s" % (cmd, out)) def get(self, var): r""" @@ -565,7 +565,7 @@ def __call__(self, x): """ self._check_valid() P = self.parent() - return P('%s(%s)'%(self.name(), x)) + return P('%s(%s)' % (self.name(), x)) def _richcmp_(self, other, op): """ @@ -601,11 +601,11 @@ def _richcmp_(self, other, op): """ P = self.parent() - if 'true' in P.eval("(%s = %s) :: Boolean"%(self.name(),other.name())): + if 'true' in P.eval("(%s = %s) :: Boolean" % (self.name(),other.name())): return rich_to_bool(op, 0) - elif 'true' in P.eval("(%s < %s) :: Boolean"%(self.name(), other.name())): + elif 'true' in P.eval("(%s < %s) :: Boolean" % (self.name(), other.name())): return rich_to_bool(op, -1) - elif 'true' in P.eval("(%s > %s) :: Boolean"%(self.name(),other.name())): + elif 'true' in P.eval("(%s > %s) :: Boolean" % (self.name(),other.name())): return rich_to_bool(op, 1) return NotImplemented @@ -635,7 +635,7 @@ def __len__(self): 6 """ P = self._check_valid() - s = P.eval('# %s '%self.name()) + s = P.eval('# %s ' % self.name()) i = s.rfind('Type') return int(s[:i-1]) @@ -667,9 +667,9 @@ def __getitem__(self, n): raise IndexError("index out of range") P = self._check_valid() if not isinstance(n, tuple): - return P.new('%s(%s)'%(self._name, n)) + return P.new('%s(%s)' % (self._name, n)) else: - return P.new('%s(%s)'%(self._name, str(n)[1:-1])) + return P.new('%s(%s)' % (self._name, str(n)[1:-1])) def comma(self, *args): """ @@ -733,7 +733,7 @@ def as_type(self, type): """ P = self._check_valid() type = P(type) - return P.new("%s :: %s"%(self.name(), type.name())) + return P.new("%s :: %s" % (self.name(), type.name())) def unparsed_input_form(self): """ @@ -750,7 +750,7 @@ def unparsed_input_form(self): """ P = self._check_valid() - s = P.eval('unparse(%s::InputForm)'%self._name) + s = P.eval('unparse(%s::InputForm)' % self._name) if 'translation error' in s or 'Cannot convert' in s: raise NotImplementedError s = multiple_replace({'\r\n':'', # fix stupid Fortran-ish @@ -855,7 +855,7 @@ def _sage_(self): #If all else fails, try using the unparsed input form try: import sage.misc.sage_eval - vars=sage.symbolic.ring.var(str(self.variables())[1:-1]) + vars = sage.symbolic.ring.var(str(self.variables())[1:-1]) if isinstance(vars,tuple): return sage.misc.sage_eval.sage_eval(self.unparsed_input_form(), locals={str(x):x for x in vars}) else: diff --git a/src/sage/interfaces/four_ti_2.py b/src/sage/interfaces/four_ti_2.py index 79a07dcdad4..1f5a6beb559 100644 --- a/src/sage/interfaces/four_ti_2.py +++ b/src/sage/interfaces/four_ti_2.py @@ -176,7 +176,7 @@ def write_array(self, array, nrows, ncols, filename): sage: four_ti_2.write_array([[1,2,3],[3,4,5]], 2, 3, "test_file") """ f = open(os.path.join(self.directory(), filename), 'w') - f.write("%s %s\n"%(nrows, ncols)) + f.write("%s %s\n" % (nrows, ncols)) for row in array: f.write(" ".join(map(str, row))) f.write("\n") @@ -444,7 +444,7 @@ def ppi(self, n): """ self.call('ppi', f'{n} 2> /dev/null') - return self.read_matrix('ppi%s.gra'%n) + return self.read_matrix('ppi%s.gra' % n) def circuits(self, mat=None, project=None): r""" diff --git a/src/sage/interfaces/frobby.py b/src/sage/interfaces/frobby.py index ed6f5431dc3..aab3bd9b58f 100644 --- a/src/sage/interfaces/frobby.py +++ b/src/sage/interfaces/frobby.py @@ -168,14 +168,14 @@ def hilbert(self, monomial_ideal): """ frobby_input = self._ideal_to_string(monomial_ideal) frobby_output = self('hilbert', input=frobby_input) - ring=monomial_ideal.ring() - lines=frobby_output.split('\n') - if lines[-1]=='': + ring = monomial_ideal.ring() + lines = frobby_output.split('\n') + if lines[-1] == '': lines.pop(-1) - if lines[-1]=='(coefficient)': + if lines[-1] == '(coefficient)': lines.pop(-1) lines.pop(0) - resul=0 + resul = 0 for l in lines: lis = [int(_) for _ in l.split()] resul += lis[0]+prod([ring.gen(i)**lis[i+1] for i in range(len(lis)-1)]) @@ -206,9 +206,9 @@ def associated_primes(self, monomial_ideal): """ frobby_input = self._ideal_to_string(monomial_ideal) frobby_output = self('assoprimes', input=frobby_input) - lines=frobby_output.split('\n') + lines = frobby_output.split('\n') lines.pop(0) - if lines[-1]=='': + if lines[-1] == '': lines.pop(-1) lists = [[int(_) for _ in a.split()] for a in lines] @@ -334,10 +334,10 @@ def _parse_ideals(self, string, ring): lines.pop(0) matrices.append('1 '+str(ring.ngens())+'\n'+'0 '*ring.ngens()+'\n') else: - nrows=int(lines[0].split()[0]) - nmatrix=lines.pop(0)+'\n' + nrows = int(lines[0].split()[0]) + nmatrix = lines.pop(0)+'\n' for i in range(nrows): - nmatrix+=lines.pop(0)+'\n' + nmatrix += lines.pop(0)+'\n' matrices.append(nmatrix) def to_ideal(exps): diff --git a/src/sage/interfaces/gap.py b/src/sage/interfaces/gap.py index b7f9b5edd51..61f38af2d26 100644 --- a/src/sage/interfaces/gap.py +++ b/src/sage/interfaces/gap.py @@ -443,7 +443,7 @@ def load_package(self, pkg, verbose=False): print("Loading GAP package {}".format(pkg)) x = self.eval('LoadPackage("{}")'.format(pkg)) if x == 'fail': - raise RuntimeError("Error loading Gap package "+str(pkg)+". "+ + raise RuntimeError("Error loading Gap package "+str(pkg)+". " + "You may want to install gap_packages SPKG.") def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds): @@ -502,7 +502,7 @@ def eval(self, x, newlines=False, strip=True, split_lines=True, **kwds): #it is occurring in a string. If it is not in a string, we #strip off the comment. if not split_lines: - input_line=str(x) + input_line = str(x) else: input_line = "" for line in str(x).rstrip().split('\n'): @@ -528,10 +528,10 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False): raise RuntimeError("Passing commands this long to gap would hang") E.sendline(line) except OSError: - raise RuntimeError("Error evaluating %s in %s"%(line, self)) + raise RuntimeError("Error evaluating %s in %s" % (line, self)) if not wait_for_prompt: return (b'',b'') - if len(line)==0: + if len(line) == 0: return (b'',b'') try: terminal_echo = [] # to be discarded @@ -566,23 +566,23 @@ def _execute_line(self, line, wait_for_prompt=True, expect_eof=False): break elif x == 9: # @m finished running a child pass # there is no need to do anything - elif x==10: #@n normal output line + elif x == 10: #@n normal output line current_outputs = normal_outputs - elif x==11: #@r echoing input + elif x == 11: #@r echoing input current_outputs = terminal_echo - elif x==12: #@sN shouldn't happen + elif x == 12: #@sN shouldn't happen warnings.warn("this should never happen") - elif x==13: #@w GAP is trying to send a Window command + elif x == 13: #@w GAP is trying to send a Window command warnings.warn("this should never happen") - elif x ==14: #@x seems to be safely ignorable + elif x == 14: #@x seems to be safely ignorable pass elif x == 15:#@z GAP starting a subprocess pass # there is no need to do anything except pexpect.EOF: if not expect_eof: - raise RuntimeError("Unexpected EOF from %s executing %s"%(self,line)) + raise RuntimeError("Unexpected EOF from %s executing %s" % (self,line)) except IOError: - raise RuntimeError("IO Error from %s executing %s"%(self,line)) + raise RuntimeError("IO Error from %s executing %s" % (self,line)) return (b"".join(normal_outputs), b"".join(error_outputs)) def _keyboard_interrupt(self): @@ -603,7 +603,7 @@ def _keyboard_interrupt(self): 2 """ self.quit() - raise KeyboardInterrupt("Ctrl-c pressed while running %s"%self) + raise KeyboardInterrupt("Ctrl-c pressed while running %s" % self) def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=True): r""" @@ -688,7 +688,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if self.quit() gap_reset_workspace() error = error.replace('\r','') - raise RuntimeError("%s produced error output\n%s\n executing %s"%(self, error,line)) + raise RuntimeError("%s produced error output\n%s\n executing %s" % (self, error,line)) if not normal: return '' @@ -726,7 +726,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if except KeyboardInterrupt: self._keyboard_interrupt() - raise KeyboardInterrupt("Ctrl-c pressed while running %s"%self) + raise KeyboardInterrupt("Ctrl-c pressed while running %s" % self) def unbind(self, var): """ @@ -745,7 +745,7 @@ def unbind(self, var): Error, Variable: 'x' must have a value ... """ - self.eval('Unbind(%s)'%var) + self.eval('Unbind(%s)' % var) self.clear(var) def _contains(self, v1, v2): @@ -762,7 +762,7 @@ def _contains(self, v1, v2): sage: 2 in gap('Integers') True """ - return self.eval('%s in %s'%(v1,v2)) == "true" + return self.eval('%s in %s' % (v1,v2)) == "true" def _true_symbol(self): """ @@ -866,8 +866,8 @@ def function_call(self, function, args=None, kwds=None): #value, then that value will be in 'last', otherwise it will #be the marker. marker = '__SAGE_LAST__:="__SAGE_LAST__";;' - cmd = "%s(%s);;"%(function, ",".join([s.name() for s in args]+ - ['%s=%s'%(key,value.name()) for key, value in kwds.items()])) + cmd = "%s(%s);;" % (function, ",".join([s.name() for s in args] + + ['%s=%s' % (key,value.name()) for key, value in kwds.items()])) if len(marker) + len(cmd) <= self._eval_using_file_cutoff: # We combine the two commands so we only run eval() once and the # only output would be from the second command @@ -978,9 +978,9 @@ def __len__(self): it is false """ P = self.parent() - if P.eval('%s = true'%self.name()) == 'true': + if P.eval('%s = true' % self.name()) == 'true': return 1 - elif P.eval('%s = false'%self.name()) == 'true': + elif P.eval('%s = false' % self.name()) == 'true': return 0 else: return int(self.Length()) @@ -1145,7 +1145,7 @@ def _next_var_name(self): del self._available_vars[0] return v self.__seq += 1 - return r'\$sage%s'%self.__seq + return r'\$sage%s' % self.__seq def _start(self): """ @@ -1270,7 +1270,7 @@ def save_workspace(self): from sage.misc.temporary_file import atomic_write with atomic_write(WORKSPACE) as f: f.close() - self.eval('SaveWorkspace("%s");'%(f.name), allow_use_file=False) + self.eval('SaveWorkspace("%s");' % (f.name), allow_use_file=False) # Todo -- this -- but there is a tricky "when does it end" issue! # Maybe do via a file somehow? @@ -1356,14 +1356,14 @@ def get(self, var, use_file=False): tmp = self._local_tmpfile() if os.path.exists(tmp): os.unlink(tmp) - self.eval('PrintTo("%s", %s);'%(tmp,var), strip=False) + self.eval('PrintTo("%s", %s);' % (tmp,var), strip=False) with open(tmp) as f: r = f.read() r = r.strip().replace("\\\n","") os.unlink(tmp) return r else: - return self.eval('Print(%s);'%var, newlines=False) + return self.eval('Print(%s);' % var, newlines=False) def _pre_interact(self): """ @@ -1390,7 +1390,7 @@ def _eval_line_using_file(self, line): if j >= 0 and j < i: i = -1 if i == -1: - line0 = 'Print( %s );'%line.rstrip().rstrip(';') + line0 = 'Print( %s );' % line.rstrip().rstrip(';') try: # this is necessary, since Print requires something as input, and some functions (e.g., Read) return nothing. return Expect._eval_line_using_file(self, line0) except RuntimeError: @@ -1562,7 +1562,7 @@ def _latex_(self): """ P = self._check_valid() try: - s = P.eval('LaTeXObj(%s)'%self.name()) + s = P.eval('LaTeXObj(%s)' % self.name()) s = s.replace('\\\\','\\').replace('"','') s = s.replace('%\\n',' ') return s @@ -1585,7 +1585,7 @@ def _tab_completion(self): True """ P = self.parent() - v = P.eval(r'\$SAGE.OperationsAdmittingFirstArgument(%s)'%self.name()) + v = P.eval(r'\$SAGE.OperationsAdmittingFirstArgument(%s)' % self.name()) v = v.replace('Tester(','').replace('Setter(','').replace(')','').replace('\n', '') v = v.split(',') v = [ oper.split('"')[1] for oper in v ] diff --git a/src/sage/interfaces/gap3.py b/src/sage/interfaces/gap3.py index 78d05035cbf..beef28e562a 100644 --- a/src/sage/interfaces/gap3.py +++ b/src/sage/interfaces/gap3.py @@ -490,7 +490,7 @@ def help(self, topic, pager=True): elif x == 10: # matched @n (normal input mode); it seems we're done break - elif x==11: + elif x == 11: # matched @r (echoing input); skip to end of line E.expect_list(self._compiled_small_pattern) @@ -743,7 +743,7 @@ def _latex_(self): """ gap3_session = self._check_valid() try: - s = gap3_session.eval('FormatLaTeX(%s)'%self.name()) + s = gap3_session.eval('FormatLaTeX(%s)' % self.name()) s = s.replace('\\\\','\\').replace('"','') s = s.replace('%\\n',' ') return s diff --git a/src/sage/interfaces/genus2reduction.py b/src/sage/interfaces/genus2reduction.py index 0a03059f9b0..eeb63fcb939 100644 --- a/src/sage/interfaces/genus2reduction.py +++ b/src/sage/interfaces/genus2reduction.py @@ -160,17 +160,17 @@ def _repr_(self): if self.Q == 0: yterm = '' else: - yterm = '+ (%s)*y '%self.Q + yterm = '+ (%s)*y ' % self.Q s = 'Reduction data about this proper smooth genus 2 curve:\n' - s += '\ty^2 %s= %s\n'%(yterm, self.P) + s += '\ty^2 %s= %s\n' % (yterm, self.P) if self.Qmin: - s += 'A Minimal Equation:\n\ty^2 + (%s)y = %s\n'%(self.Qmin, self.Pmin) + s += 'A Minimal Equation:\n\ty^2 + (%s)y = %s\n' % (self.Qmin, self.Pmin) else: - s += 'A Minimal Equation:\n\ty^2 = %s\n'%self.Pmin - s += 'Minimal Discriminant: %s\n'%self.minimal_disc - s += 'Conductor: %s\n'%self.conductor - s += 'Local Data:\n%s'%self._local_data_str() + s += 'A Minimal Equation:\n\ty^2 = %s\n' % self.Pmin + s += 'Minimal Discriminant: %s\n' % self.minimal_disc + s += 'Conductor: %s\n' % self.conductor + s += 'Local Data:\n%s' % self._local_data_str() return s def _local_data_str(self): @@ -178,7 +178,7 @@ def _local_data_str(self): D = self.local_data K = sorted(D.keys()) for p in K: - s += 'p=%s\n%s\n'%(p, D[p]) + s += 'p=%s\n%s\n' % (p, D[p]) s = '\t' + '\n\t'.join(s.strip().split('\n')) return s @@ -217,7 +217,7 @@ def divisors_to_string(divs): # Next divisor is different or we are done? Print current one if s: s += "x" - s += "(%s)"%divs[i] + s += "(%s)" % divs[i] if n > 1: s += "^%s" % n n = 0 diff --git a/src/sage/interfaces/gnuplot.py b/src/sage/interfaces/gnuplot.py index 025a8155212..76841963721 100644 --- a/src/sage/interfaces/gnuplot.py +++ b/src/sage/interfaces/gnuplot.py @@ -99,7 +99,7 @@ def plot(self, cmd, file=None, verbose=True, reset=True): print("Saving plot to %s" % file) self(cmd) time.sleep(0.1) - os.system('mv %s %s 2>/dev/null'%(tmp, file)) + os.system('mv %s %s 2>/dev/null' % (tmp, file)) time.sleep(0.1) self('set terminal x11') @@ -110,7 +110,7 @@ def plot3d(self, f, xmin=-1, xmax=1, ymin=-1, ymax=1, zmin=-1, zmax=1, if title is None: title = str(f) f = f.replace('^','**') - cmd=""" + cmd = """ set xlabel "%s" set ylabel "%s" set key top @@ -125,7 +125,7 @@ def plot3d(self, f, xmin=-1, xmax=1, ymin=-1, ymax=1, zmin=-1, zmax=1, #show pm3d #show palette splot %s - """%(xlabel, ylabel, + """ % (xlabel, ylabel, xmin, xmax, ymin, ymax, #zmin, zmax, samples, isosamples, title, f) @@ -163,7 +163,7 @@ def plot3d_parametric(self, f='cos(u)*(3 + v*cos(u/2)), sin(u)*(3 + v*cos(u/2)), """ if title is None: title = str(f) - cmd=""" + cmd = """ set key top set border 4095 set samples %s diff --git a/src/sage/interfaces/interface.py b/src/sage/interfaces/interface.py index 3180113c9c7..78f94269ff4 100644 --- a/src/sage/interfaces/interface.py +++ b/src/sage/interfaces/interface.py @@ -324,7 +324,7 @@ def _coerce_from_special_method(self, x): If no such method is defined, raises an AttributeError instead of a TypeError. """ - s = '_%s_'%self.name() + s = '_%s_' % self.name() if s == '_maxima_lib_': s = '_maxima_' if s == '_pari_': @@ -375,11 +375,11 @@ def _coerce_impl(self, x, use_special=True): A.append(w.name()) z.append(w) X = ','.join(A) - r = self.new('%s%s%s'%(self._left_list_delim(), X, self._right_list_delim())) + r = self.new('%s%s%s' % (self._left_list_delim(), X, self._right_list_delim())) r.__sage_list = z # do this to avoid having the entries of the list be garbage collected return r - raise TypeError("unable to coerce element into %s"%self.name()) + raise TypeError("unable to coerce element into %s" % self.name()) def new(self, code): return self(code) @@ -412,14 +412,14 @@ def _true_symbol(self): try: return self.__true_symbol except AttributeError: - self.__true_symbol = self.get('1 %s 1'%self._equality_symbol()) + self.__true_symbol = self.get('1 %s 1' % self._equality_symbol()) return self.__true_symbol def _false_symbol(self): try: return self.__false_symbol except AttributeError: - self.__false_symbol = self.get('1 %s 2'%self._equality_symbol()) + self.__false_symbol = self.get('1 %s 2' % self._equality_symbol()) return self.__false_symbol def _lessthan_symbol(self): @@ -470,7 +470,7 @@ def set(self, var, value): """ Set the variable var to the given value. """ - cmd = '%s%s%s;'%(var,self._assign_symbol(), value) + cmd = '%s%s%s;' % (var,self._assign_symbol(), value) self.eval(cmd) def get(self, var): @@ -509,7 +509,7 @@ def _next_var_name(self): del self._available_vars[0] return v self.__seq += 1 - return "sage%s"%self.__seq + return "sage%s" % self.__seq def _create(self, value, name=None): name = self._next_var_name() if name is None else name @@ -612,7 +612,7 @@ def function_call(self, function, args=None, kwds=None): self._check_valid_function_name(function) s = self._function_call_string(function, [s.name() for s in args], - ['%s=%s'%(key,value.name()) for key, value in kwds.items()]) + ['%s=%s' % (key,value.name()) for key, value in kwds.items()]) return self.new(s) def _function_call_string(self, function, args, kwds): @@ -624,7 +624,7 @@ def _function_call_string(self, function, args, kwds): sage: maxima._function_call_string('diff', ['f(x)', 'x'], []) 'diff(f(x),x)' """ - return "%s(%s)"%(function, ",".join(list(args) + list(kwds))) + return "%s(%s)" % (function, ",".join(list(args) + list(kwds))) def call(self, function_name, *args, **kwds): return self.function_call(function_name, args, kwds) @@ -962,18 +962,18 @@ def _richcmp_(self, other, op): """ P = self._check_valid() try: - if P.eval("%s %s %s"%(self.name(), P._equality_symbol(), + if P.eval("%s %s %s" % (self.name(), P._equality_symbol(), other.name())) == P._true_symbol(): return rich_to_bool(op, 0) except RuntimeError: pass try: - if P.eval("%s %s %s"%(self.name(), P._lessthan_symbol(), other.name())) == P._true_symbol(): + if P.eval("%s %s %s" % (self.name(), P._lessthan_symbol(), other.name())) == P._true_symbol(): return rich_to_bool(op, -1) except RuntimeError: pass try: - if P.eval("%s %s %s"%(self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): + if P.eval("%s %s %s" % (self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): return rich_to_bool(op, 1) except Exception: pass @@ -1004,7 +1004,7 @@ def _check_valid(self): try: P = self.parent() if P is None: - raise ValueError("The %s session in which this object was defined is no longer running."%P.name()) + raise ValueError("The %s session in which this object was defined is no longer running." % P.name()) except AttributeError: raise ValueError("The session in which this object was defined is no longer running.") return P @@ -1285,14 +1285,14 @@ def attribute(self, attrname): -122023936/161051 """ P = self._check_valid() - return P('%s.%s'%(self.name(), attrname)) + return P('%s.%s' % (self.name(), attrname)) def __getitem__(self, n): P = self._check_valid() if not isinstance(n, tuple): - return P.new('%s[%s]'%(self._name, n)) + return P.new('%s[%s]' % (self._name, n)) else: - return P.new('%s[%s]'%(self._name, str(n)[1:-1])) + return P.new('%s[%s]' % (self._name, str(n)[1:-1])) def __int__(self): """ @@ -1429,7 +1429,7 @@ def name(self, new_name=None): def gen(self, n): P = self._check_valid() - return P.new('%s.%s'%(self._name, int(n))) + return P.new('%s.%s' % (self._name, int(n))) def _operation(self, operation, other=None): r""" @@ -1466,9 +1466,9 @@ def _operation(self, operation, other=None): """ P = self._check_valid() if other is None: - cmd = '%s %s'%(operation, self._name) + cmd = '%s %s' % (operation, self._name) else: - cmd = '%s %s %s'%(self._name, operation, other._name) + cmd = '%s %s %s' % (self._name, operation, other._name) try: return P.new(cmd) except Exception as msg: diff --git a/src/sage/interfaces/jmoldata.py b/src/sage/interfaces/jmoldata.py index 6660a14e1cc..a68e53e2d85 100644 --- a/src/sage/interfaces/jmoldata.py +++ b/src/sage/interfaces/jmoldata.py @@ -165,12 +165,12 @@ def export_image(self, datafile = cygwin.cygpath(datafile, 'w') launchscript = "" - if (datafile_cmd!='script'): + if (datafile_cmd != 'script'): launchscript = "load " launchscript = launchscript + datafile imagescript = 'write {} {!r}\n'.format(image_type, target_native) - size_arg = "%sx%s" %(figsize*100,figsize*100) + size_arg = "%sx%s" % (figsize*100,figsize*100) # Scratch file for Jmol errors scratchout = tmp_filename(ext=".txt") with open(scratchout, 'w') as jout: diff --git a/src/sage/interfaces/lisp.py b/src/sage/interfaces/lisp.py index 5c28b82bf88..3d6e620c4d1 100644 --- a/src/sage/interfaces/lisp.py +++ b/src/sage/interfaces/lisp.py @@ -136,7 +136,7 @@ def eval(self, code, strip=True, **kwds): x.append(M.strip()) self.__in_seq = s except TypeError as s: - return 'error evaluating "%s":\n%s'%(code,s) + return 'error evaluating "%s":\n%s' % (code,s) return '\n'.join(x) def _an_element_impl(self): @@ -165,10 +165,10 @@ def set(self, var, value): sage: lisp.eval('x') '2' """ - cmd = '(setq %s %s)'%(var, value) + cmd = '(setq %s %s)' % (var, value) out = self.eval(cmd) if '***' in out: - raise TypeError("Error executing code in Sage\nCODE:\n\t%s\nSAGE ERROR:\n\t%s"%(cmd, out)) + raise TypeError("Error executing code in Sage\nCODE:\n\t%s\nSAGE ERROR:\n\t%s" % (cmd, out)) def get(self, var): """ @@ -202,7 +202,7 @@ def _synchronize(self): E = self._expect r = random.randrange(2147483647) s = str(r+1) - cmd = "(+ 1 %s)"%r + cmd = "(+ 1 %s)" % r E.sendline(cmd) E.expect(s) E.expect(self._prompt) @@ -410,9 +410,9 @@ def _richcmp_(self, other, op): if parent(other) is not P: other = P(other) - if P.eval('(= %s %s)'%(self.name(), other.name())) == P._true_symbol(): + if P.eval('(= %s %s)' % (self.name(), other.name())) == P._true_symbol(): return rich_to_bool(op, 0) - elif P.eval('(< %s %s)'%(self.name(), other.name())) == P._true_symbol(): + elif P.eval('(< %s %s)' % (self.name(), other.name())) == P._true_symbol(): return rich_to_bool(op, -1) else: return rich_to_bool(op, 1) @@ -454,7 +454,7 @@ def _sub_(self, right): -1 """ P = self._check_valid() - return P.new('(- %s %s)'%(self._name, right._name)) + return P.new('(- %s %s)' % (self._name, right._name)) def _mul_(self, right): """ @@ -465,7 +465,7 @@ def _mul_(self, right): 2 """ P = self._check_valid() - return P.new('(* %s %s)'%(self._name, right._name)) + return P.new('(* %s %s)' % (self._name, right._name)) def _div_(self, right): """ @@ -476,7 +476,7 @@ def _div_(self, right): 1/2 """ P = self._check_valid() - return P.new('(/ %s %s)'%(self._name, right._name)) + return P.new('(/ %s %s)' % (self._name, right._name)) def __pow__(self, n): """ diff --git a/src/sage/interfaces/macaulay2.py b/src/sage/interfaces/macaulay2.py index 956ca018838..1d575b4ff7c 100644 --- a/src/sage/interfaces/macaulay2.py +++ b/src/sage/interfaces/macaulay2.py @@ -845,7 +845,7 @@ def new_from(self, type, value): """ type = self(type) value = self(value) - return self.new("new %s from %s"%(type.name(), value.name())) + return self.new("new %s from %s" % (type.name(), value.name())) def _macaulay2_input_ring(self, base_ring, vars, order='GRevLex'): """ @@ -972,13 +972,13 @@ def external_string(self): 'QQ(monoid[x..y, Degrees => {2:1}, Heft => {1}, MonomialOrder => VerticalList{MonomialSize => 32, GRevLex => {2:1}, Position => Up}, DegreeRank => 1])' """ P = self._check_valid() - code = 'toExternalString(%s)'%self.name() + code = 'toExternalString(%s)' % self.name() X = P.eval(code, strip=True) if 'stdio:' in X: if 'to external string' in X: - return P.eval('%s'%self.name()) - raise RuntimeError("Error evaluating Macaulay2 code.\nIN:%s\nOUT:%s"%(code, X)) + return P.eval('%s' % self.name()) + raise RuntimeError("Error evaluating Macaulay2 code.\nIN:%s\nOUT:%s" % (code, X)) s = multiple_replace({'\r':'', '\n':' '}, X) return s @@ -1050,7 +1050,7 @@ def __len__(self): """ self._check_valid() # we use str instead of repr to avoid wrapping - return int(str(self.parent()("#%s"%self.name()))) + return int(str(self.parent()("#%s" % self.name()))) def __getitem__(self, n): """ @@ -1062,7 +1062,7 @@ def __getitem__(self, n): """ self._check_valid() n = self.parent()(n) - return self.parent().new('%s # %s'%(self.name(), n.name())) + return self.parent().new('%s # %s' % (self.name(), n.name())) def __setitem__(self, index, value): """ @@ -1077,7 +1077,7 @@ def __setitem__(self, index, value): P = self.parent() index = P(index) value = P(value) - res = P.eval("%s # %s = %s"%(self.name(), index.name(), value.name())) + res = P.eval("%s # %s = %s" % (self.name(), index.name(), value.name())) if "assignment attempted to element of immutable list" in res: raise TypeError("item assignment not supported") @@ -1095,7 +1095,7 @@ def __call__(self, x): self._check_valid() P = self.parent() r = P(x) - return P('%s %s'%(self.name(), r.name())) + return P('%s %s' % (self.name(), r.name())) def __floordiv__(self, x): """ @@ -1119,10 +1119,10 @@ def __floordiv__(self, x): """ if isinstance(x, (list, tuple)): y = self.parent(x) - z = self.parent().new('%s // matrix{%s}'%(self.name(), y.name())) + z = self.parent().new('%s // matrix{%s}' % (self.name(), y.name())) return list(z.entries().flatten()) else: - return self.parent().new('%s // %s'%(self.name(), x.name())) + return self.parent().new('%s // %s' % (self.name(), x.name())) def __mod__(self, x): """ @@ -1148,10 +1148,10 @@ def __mod__(self, x): """ if isinstance(x, (list, tuple)): y = self.parent(x) - return self.parent().new('%s %% matrix{%s}'%(self.name(), y.name())) + return self.parent().new('%s %% matrix{%s}' % (self.name(), y.name())) if not isinstance(x, Macaulay2Element): x = self.parent(x) - return self.parent().new('%s %% %s'%(self.name(), x.name())) + return self.parent().new('%s %% %s' % (self.name(), x.name())) def __bool__(self): """ @@ -1219,7 +1219,7 @@ def structure_sheaf(self): """ from sage.misc.superseded import deprecation deprecation(27848, 'The function `structure_sheaf` is deprecated. Use `self.sheaf()` instead.') - return self.parent()('OO_%s'%self.name()) + return self.parent()('OO_%s' % self.name()) def substitute(self, *args, **kwds): """ @@ -1300,7 +1300,7 @@ def cls(self): Ring """ - return self.parent()("class %s"%self.name()) + return self.parent()("class %s" % self.name()) def after_print_text(self): r""" @@ -1356,7 +1356,7 @@ def _operator(self, opstr, x): """ parent = self.parent() x = parent(x) - return parent("%s%s%s"%(self.name(), opstr, x.name())) + return parent("%s%s%s" % (self.name(), opstr, x.name())) def sharp(self, x): """ @@ -1683,7 +1683,7 @@ def _sage_(self): try: return sage_eval(repr_str) except Exception: - raise NotImplementedError("cannot convert %s to a Sage object"%repr_str) + raise NotImplementedError("cannot convert %s to a Sage object" % repr_str) to_sage = deprecated_function_alias(27848, ExpectElement.sage) diff --git a/src/sage/interfaces/magma_free.py b/src/sage/interfaces/magma_free.py index 70f196a0fb2..d01d291c337 100644 --- a/src/sage/interfaces/magma_free.py +++ b/src/sage/interfaces/magma_free.py @@ -42,7 +42,7 @@ def magma_free_eval(code, strip=True, columns=0): processPath = "/xml/calculator.xml" refererPath = "/calc/" refererUrl = "http://%s%s" % ( server, refererPath) - code = "SetColumns(%s);\n"%columns + code + code = "SetColumns(%s);\n" % columns + code params = urlencode({'input':code}) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "Accept: text/html, application/xml, application/xhtml+xml", "Referer": refererUrl} diff --git a/src/sage/interfaces/maxima.py b/src/sage/interfaces/maxima.py index 959e75459a2..c55f9797ef2 100644 --- a/src/sage/interfaces/maxima.py +++ b/src/sage/interfaces/maxima.py @@ -887,7 +887,7 @@ def _batch(self, s, batchload=True): sage: maxima._batch('10003;',batchload=False) '...batch...10003...' """ - filename = '%s-%s'%(self._local_tmpfile(),randrange(2147483647)) + filename = '%s-%s' % (self._local_tmpfile(),randrange(2147483647)) F = open(filename, 'w') F.write(s) F.close() @@ -897,13 +897,13 @@ def _batch(self, s, batchload=True): tmp_to_use = filename if batchload: - cmd = 'batchload("%s");'%tmp_to_use + cmd = 'batchload("%s");' % tmp_to_use else: - cmd = 'batch("%s");'%tmp_to_use + cmd = 'batch("%s");' % tmp_to_use r = randrange(2147483647) s = str(r+1) - cmd = "%s1+%s;\n"%(cmd,r) + cmd = "%s1+%s;\n" % (cmd,r) self._sendline(cmd) self._expect_expr(s) @@ -969,7 +969,7 @@ def _error_msg(self, cmd, out): Maxima ERROR: Principal Value """ - raise TypeError("Error executing code in Maxima\nCODE:\n\t%s\nMaxima ERROR:\n\t%s"%(cmd, out.replace('-- an error. To debug this try debugmode(true);',''))) + raise TypeError("Error executing code in Maxima\nCODE:\n\t%s\nMaxima ERROR:\n\t%s" % (cmd, out.replace('-- an error. To debug this try debugmode(true);',''))) ########################################### # Direct access to underlying lisp interpreter. @@ -989,7 +989,7 @@ def lisp(self, cmd): 19 ( """ - self._eval_line(':lisp %s\n""'%cmd, allow_use_file=False, + self._eval_line(':lisp %s\n""' % cmd, allow_use_file=False, wait_for_prompt=False, reformat=False, error_check=False) self._expect_expr('(%i)') return self._before() @@ -1016,7 +1016,7 @@ def set(self, var, value): """ if not isinstance(value, str): raise TypeError - cmd = '%s : %s$'%(var, value.rstrip(';')) + cmd = '%s : %s$' % (var, value.rstrip(';')) if len(cmd) > self.__eval_using_file_cutoff: self._batch(cmd, batchload=True) else: @@ -1196,7 +1196,7 @@ def display2d(self, onscreen=True): P = self.parent() with gc_disabled(): P._eval_line('display2d : true$') - s = P._eval_line('disp(%s)$'%self.name(), reformat=False) + s = P._eval_line('disp(%s)$' % self.name(), reformat=False) P._eval_line('display2d : false$') s = s.strip('\r\n') diff --git a/src/sage/interfaces/maxima_abstract.py b/src/sage/interfaces/maxima_abstract.py index aecfcba5e23..9fe624a7f02 100644 --- a/src/sage/interfaces/maxima_abstract.py +++ b/src/sage/interfaces/maxima_abstract.py @@ -131,7 +131,7 @@ def chdir(self, dir): sage: maxima.chdir('/') """ - self.lisp('(ext::cd "%s")'%dir) + self.lisp('(ext::cd "%s")' % dir) ########################################### # Interactive help @@ -291,7 +291,7 @@ def completions(self, s, verbose=True): # create NAME-IMPL, without the leading $). This causes # name-impl to show up in $APROPOS. We remove it. # https://sourceforge.net/p/maxima/bugs/3643/ - cmd_list = self._eval_line('apropos("%s")'%s, error_check=False) + cmd_list = self._eval_line('apropos("%s")' % s, error_check=False) cmd_list = cmd_list.replace(' ', '').replace('\n', '').replace('\\ - ','-').replace('\\-','-') cmd_list = [x for x in cmd_list[1:-1].split(',') if x[0] != '?' and not x.endswith('-impl')] return [x for x in cmd_list if x.find(s) == 0] @@ -322,7 +322,7 @@ def _commands(self, verbose=True): return self.__commands except AttributeError: self.__commands = sum( - [self.completions(chr(65+n), verbose=verbose)+ + [self.completions(chr(65+n), verbose=verbose) + self.completions(chr(97+n), verbose=verbose) for n in range(26)], []) return self.__commands @@ -826,12 +826,12 @@ def plot3d_parametric(self, r, vars, urange, vrange, options=None): umax = urange[1] vmin = vrange[0] vmax = vrange[1] - cmd = 'plot3d([%s, %s, %s], [%s, %s, %s], [%s, %s, %s]'%( + cmd = 'plot3d([%s, %s, %s], [%s, %s, %s], [%s, %s, %s]' % ( r[0], r[1], r[2], vars[0], umin, umax, vars[1], vmin, vmax) if options is None: cmd += ')' else: - cmd += ', %s)'%options + cmd += ', %s)' % options self(cmd) def de_solve(self, de, vars, ics=None): @@ -861,18 +861,18 @@ def de_solve(self, de, vars, ics=None): y = -...%e^-1*(5*%e^x-3*%e*x-3*%e)... """ if not isinstance(vars, str): - str_vars = '%s, %s'%(vars[1], vars[0]) + str_vars = '%s, %s' % (vars[1], vars[0]) else: str_vars = vars - self.eval('depends(%s)'%str_vars) + self.eval('depends(%s)' % str_vars) m = self(de) - a = 'ode2(%s, %s)'%(m.name(), str_vars) + a = 'ode2(%s, %s)' % (m.name(), str_vars) if ics is not None: if len(ics) == 3: - cmd = "ic2("+a+",%s=%s,%s=%s,diff(%s,%s)=%s);"%(vars[0],ics[0], vars[1],ics[1], vars[1], vars[0], ics[2]) + cmd = "ic2("+a+",%s=%s,%s=%s,diff(%s,%s)=%s);" % (vars[0],ics[0], vars[1],ics[1], vars[1], vars[0], ics[2]) return self(cmd) if len(ics) == 2: - return self("ic1("+a+",%s=%s,%s=%s);"%(vars[0],ics[0], vars[1],ics[1])) + return self("ic1("+a+",%s=%s,%s=%s);" % (vars[0],ics[0], vars[1],ics[1])) return self(a+";") def de_solve_laplace(self, de, vars, ics=None): @@ -921,10 +921,10 @@ def de_solve_laplace(self, de, vars, ics=None): if not (ics is None): d = len(ics) for i in range(0,d-1): - ic = 'atvalue(diff(%s(%s), %s, %s), %s = %s, %s)'%( + ic = 'atvalue(diff(%s(%s), %s, %s), %s = %s, %s)' % ( vars[1], vars[0], vars[0], i, vars[0], ics[0], ics[1+i]) self.eval(ic) - return self('desolve(%s, %s(%s))'%(de, vars[1], vars[0])) + return self('desolve(%s, %s(%s))' % (de, vars[1], vars[0])) def solve_linear(self, eqns,vars): """ @@ -1026,11 +1026,11 @@ def plot_list(self, ptsx, ptsy, options=None): sage: opts='[gnuplot_preamble, "set nokey"], [gnuplot_term, ps], [gnuplot_out_file, "zeta.eps"]' sage: maxima.plot_list(zeta_ptsx, zeta_ptsy, opts) # not tested """ - cmd = 'plot2d([discrete,%s, %s]'%(ptsx, ptsy) + cmd = 'plot2d([discrete,%s, %s]' % (ptsx, ptsy) if options is None: cmd += ')' else: - cmd += ', %s)'%options + cmd += ', %s)' % options self(cmd) def plot_multilist(self, pts_list, options=None): @@ -1074,7 +1074,7 @@ def plot_multilist(self, pts_list, options=None): for i in range(n): if i < n-1: cmd = cmd+'[discrete,'+str(pts_list[i][0])+','+str(pts_list[i][1])+'],' - if i==n-1: + if i == n-1: cmd = cmd+'[discrete,'+str(pts_list[i][0])+','+str(pts_list[i][1])+']]' if options is None: self('plot2d('+cmd+')') @@ -1182,11 +1182,11 @@ def _richcmp_(self, other, op): # are what Maxima needs P = self.parent() try: - if P.eval("is (%s < %s)"%(self.name(), other.name())) == P._true_symbol(): + if P.eval("is (%s < %s)" % (self.name(), other.name())) == P._true_symbol(): return rich_to_bool(op, -1) - elif P.eval("is (%s > %s)"%(self.name(), other.name())) == P._true_symbol(): + elif P.eval("is (%s > %s)" % (self.name(), other.name())) == P._true_symbol(): return rich_to_bool(op, 1) - elif P.eval("is (%s = %s)"%(self.name(), other.name())) == P._true_symbol(): + elif P.eval("is (%s = %s)" % (self.name(), other.name())) == P._true_symbol(): return rich_to_bool(op, 0) except TypeError: pass @@ -1608,7 +1608,7 @@ def __float__(self): try: return float(repr(self.numer())) except ValueError: - raise TypeError("unable to coerce '%s' to float"%repr(self)) + raise TypeError("unable to coerce '%s' to float" % repr(self)) def __len__(self): """ @@ -1625,7 +1625,7 @@ def __len__(self): 6 """ P = self._check_valid() - return int(P.eval('length(%s)'%self.name())) + return int(P.eval('length(%s)' % self.name())) def dot(self, other): """ @@ -1646,7 +1646,7 @@ def dot(self, other): """ P = self._check_valid() Q = P(other) - return P('%s . %s'%(self.name(), Q.name())) + return P('%s . %s' % (self.name(), Q.name())) def __getitem__(self, n): r""" @@ -1678,7 +1678,7 @@ def __getitem__(self, n): """ n = int(n) if n < 0 or n >= len(self): - raise IndexError("n = (%s) must be between %s and %s"%(n, 0, len(self)-1)) + raise IndexError("n = (%s) must be between %s and %s" % (n, 0, len(self)-1)) # If you change the n+1 to n below, better change __iter__ as well. return InterfaceElement.__getitem__(self, n+1) @@ -1740,7 +1740,7 @@ def comma(self, args): """ self._check_valid() P = self.parent() - return P('%s, %s'%(self.name(), args)) + return P('%s, %s' % (self.name(), args)) def _latex_(self): r""" @@ -1849,10 +1849,10 @@ def _matrix_(self, R): from sage.matrix.matrix_space import MatrixSpace self._check_valid() P = self.parent() - nrows = int(P.eval('length(%s)'%self.name())) + nrows = int(P.eval('length(%s)' % self.name())) if nrows == 0: return MatrixSpace(R, 0, 0)(0) - ncols = int(P.eval('length(%s[1])'%self.name())) + ncols = int(P.eval('length(%s[1])' % self.name())) M = MatrixSpace(R, nrows, ncols) s = self.str().replace('matrix','').replace(',',"','").\ replace("]','[","','").replace('([',"['").replace('])',"']") @@ -1920,12 +1920,12 @@ def _operation(self, operation, other=None): P = self._check_valid() if other is None: - cmd = '%s %s'%(operation, self._name) + cmd = '%s %s' % (operation, self._name) elif isinstance(other, P._object_function_class()): fself = P.function('', repr(self)) return fself._operation(operation, other) else: - cmd = '%s %s %s'%(self._name, operation, other._name) + cmd = '%s %s %s' % (self._name, operation, other._name) try: return P.new(cmd) except Exception as msg: @@ -2026,8 +2026,8 @@ def __call__(self, *args): """ P = self._check_valid() if len(args) == 1: - args = '(%s)'%args - return P('%s%s'%(self.name(), args)) + args = '(%s)' % args + return P('%s%s' % (self.name(), args)) def _repr_(self): """ @@ -2132,7 +2132,7 @@ def integral(self, var): """ var = str(var) P = self._check_valid() - f = P('integrate(%s(%s), %s)'%(self.name(), + f = P('integrate(%s(%s), %s)' % (self.name(), self.arguments(split=False), var)) args = self.arguments() diff --git a/src/sage/interfaces/maxima_lib.py b/src/sage/interfaces/maxima_lib.py index c8f9d574763..211018e52cc 100644 --- a/src/sage/interfaces/maxima_lib.py +++ b/src/sage/interfaces/maxima_lib.py @@ -222,14 +222,14 @@ # See trac # 6818. init_code.append('nolabels : true') for l in init_code: - ecl_eval("#$%s$"%l) + ecl_eval("#$%s$" % l) # To get more debug information uncomment the next line # should allow to do this through a method #ecl_eval("(setf *standard-output* original-standard-output)") # This is the main function (ECL object) used for evaluation # This returns an EclObject -maxima_eval=ecl_eval(""" +maxima_eval = ecl_eval(""" (defun maxima-eval( form ) (with-$error (meval form))) """) @@ -240,27 +240,27 @@ # Here we define several useful ECL/Maxima objects # The Maxima string function can change the structure of its input #maxprint=EclObject("$STRING") -maxprint=EclObject(r"""(defun mstring-for-sage (form) +maxprint = EclObject(r"""(defun mstring-for-sage (form) (coerce (mstring form) 'string))""").eval() -meval=EclObject("MEVAL") -msetq=EclObject("MSETQ") -mlist=EclObject("MLIST") -mequal=EclObject("MEQUAL") -cadadr=EclObject("CADADR") - -max_integrate=EclObject("$INTEGRATE") -max_sum=EclObject("$SUM") -max_simplify_sum=EclObject("$SIMPLIFY_SUM") -max_prod=EclObject("$PRODUCT") -max_simplify_prod=EclObject("$SIMPLIFY_PRODUCT") -max_ratsimp=EclObject("$RATSIMP") -max_limit=EclObject("$LIMIT") -max_tlimit=EclObject("$TLIMIT") -max_plus=EclObject("$PLUS") -max_minus=EclObject("$MINUS") -max_use_grobner=EclObject("$USE_GROBNER") -max_to_poly_solve=EclObject("$TO_POLY_SOLVE") -max_at=EclObject("%AT") +meval = EclObject("MEVAL") +msetq = EclObject("MSETQ") +mlist = EclObject("MLIST") +mequal = EclObject("MEQUAL") +cadadr = EclObject("CADADR") + +max_integrate = EclObject("$INTEGRATE") +max_sum = EclObject("$SUM") +max_simplify_sum = EclObject("$SIMPLIFY_SUM") +max_prod = EclObject("$PRODUCT") +max_simplify_prod = EclObject("$SIMPLIFY_PRODUCT") +max_ratsimp = EclObject("$RATSIMP") +max_limit = EclObject("$LIMIT") +max_tlimit = EclObject("$TLIMIT") +max_plus = EclObject("$PLUS") +max_minus = EclObject("$MINUS") +max_use_grobner = EclObject("$USE_GROBNER") +max_to_poly_solve = EclObject("$TO_POLY_SOLVE") +max_at = EclObject("%AT") def stdout_to_string(s): r""" @@ -284,7 +284,7 @@ def stdout_to_string(s): '2\n\n' """ return ecl_eval(r"""(with-output-to-string (*standard-output*) - (maxima-eval #$%s$))"""%s).python()[1:-1] + (maxima-eval #$%s$))""" % s).python()[1:-1] def max_to_string(s): r""" @@ -306,7 +306,7 @@ def max_to_string(s): return maxprint(s).python()[1:-1] -my_mread=ecl_eval(""" +my_mread = ecl_eval(""" (defun my-mread (cmd) (caddr (mread (make-string-input-stream cmd)))) """) @@ -327,7 +327,7 @@ def parse_max_string(s): sage: parse_max_string('1+1') """ - return my_mread('"%s;"'%s) + return my_mread('"%s;"' % s) class MaximaLib(MaximaAbstract): """ @@ -458,9 +458,9 @@ def _eval_line(self, line, locals=None, reformat=True, **kwds): """ result = '' while line: - ind_dollar=line.find("$") - ind_semi=line.find(";") - if ind_dollar == -1 or (ind_semi >=0 and ind_dollar > ind_semi): + ind_dollar = line.find("$") + ind_semi = line.find(";") + if ind_dollar == -1 or (ind_semi >= 0 and ind_dollar > ind_semi): if ind_semi == -1: statement = line line = '' @@ -468,7 +468,7 @@ def _eval_line(self, line, locals=None, reformat=True, **kwds): statement = line[:ind_semi] line = line[ind_semi+1:] if statement: - result = ((result + '\n') if result else '') + max_to_string(maxima_eval("#$%s$"%statement)) + result = ((result + '\n') if result else '') + max_to_string(maxima_eval("#$%s$" % statement)) else: statement = line[:ind_dollar] line = line[ind_dollar+1:] @@ -526,7 +526,7 @@ def set(self, var, value): """ if not isinstance(value, str): raise TypeError - cmd = '%s : %s$'%(var, value.rstrip(';')) + cmd = '%s : %s$' % (var, value.rstrip(';')) self.eval(cmd) def clear(self, var): @@ -550,8 +550,8 @@ def clear(self, var): 'xxxxx' """ try: - self.eval('kill(%s)$'%var) - ecl_eval("(unintern '$%s)"%var) + self.eval('kill(%s)$' % var) + ecl_eval("(unintern '$%s)" % var) except (TypeError, AttributeError): pass @@ -572,7 +572,7 @@ def get(self, var): sage: maxima_lib.get('xxxxx') '2' """ - s = self.eval('%s;'%var) + s = self.eval('%s;' % var) return s def _create(self, value, name=None): @@ -617,7 +617,7 @@ def _create(self, value, name=None): name = self._next_var_name() if name is None else name try: if isinstance(value,EclObject): - maxima_eval([[msetq],cadadr("#$%s$#$"%name),value]) + maxima_eval([[msetq],cadadr("#$%s$#$" % name),value]) else: self.set(name, value) except RuntimeError as error: @@ -1051,7 +1051,7 @@ def _missing_assumption(self,errstr): k = errstr.find(' ',jj+1) outstr = "Computation failed since Maxima requested additional constraints; using the 'assume' command before evaluation *may* help (example of legal syntax is 'assume("\ - + errstr[jj+1:k] +">0)', see `assume?` for more details)\n" + errstr + + errstr[jj+1:k] + ">0)', see `assume?` for more details)\n" + errstr outstr = outstr.replace('_SAGE_VAR_','') raise ValueError(outstr) @@ -1110,7 +1110,7 @@ def ecl(self): try: return self._ecl except AttributeError: - self._ecl=maxima_eval("#$%s$"%self._name) + self._ecl = maxima_eval("#$%s$" % self._name) return self._ecl def to_poly_solve(self,vars,options=""): @@ -1136,10 +1136,10 @@ def to_poly_solve(self,vars,options=""): [[x == pi*z...]] """ if options.find("use_grobner=true") != -1: - cmd=EclObject([[max_to_poly_solve], self.ecl(), sr_to_max(vars), + cmd = EclObject([[max_to_poly_solve], self.ecl(), sr_to_max(vars), [[mequal],max_use_grobner,True]]) else: - cmd=EclObject([[max_to_poly_solve], self.ecl(), sr_to_max(vars)]) + cmd = EclObject([[max_to_poly_solve], self.ecl(), sr_to_max(vars)]) return self.parent()(maxima_eval(cmd)) def display2d(self, onscreen=True): @@ -1166,7 +1166,7 @@ def display2d(self, onscreen=True): self._check_valid() P = self.parent() P._eval_line('display2d : true$') - s = stdout_to_string('disp(%s)'%self.name()) + s = stdout_to_string('disp(%s)' % self.name()) #s = P._eval_line('disp(%s)$'%self.name()) P._eval_line('display2d : false$') s = s.strip('\r\n') @@ -1216,17 +1216,17 @@ def reduce_load_MaximaLib(): from sage.rings.number_field.number_field_element_base import NumberFieldElement_base from sage.symbolic.operators import FDerivativeOperator, add_vararg, mul_vararg -car=EclObject("car") -cdr=EclObject("cdr") -caar=EclObject("caar") -cadr=EclObject("cadr") -cddr=EclObject("cddr") -caddr=EclObject("caddr") -caaadr=EclObject("caaadr") -cadadr=EclObject("cadadr") -meval=EclObject("meval") -NIL=EclObject("NIL") -lisp_length=EclObject("length") +car = EclObject("car") +cdr = EclObject("cdr") +caar = EclObject("caar") +cadr = EclObject("cadr") +cddr = EclObject("cddr") +caddr = EclObject("caddr") +caaadr = EclObject("caaadr") +cadadr = EclObject("cadadr") +meval = EclObject("meval") +NIL = EclObject("NIL") +lisp_length = EclObject("length") # Dictionaries for standard operators sage_op_dict = { @@ -1280,12 +1280,12 @@ def sage_rat(x,y): return x/y -mplus=EclObject("MPLUS") -mtimes=EclObject("MTIMES") -rat=EclObject("RAT") -max_op_dict[mplus]=add_vararg -max_op_dict[mtimes]=mul_vararg -max_op_dict[rat]=sage_rat +mplus = EclObject("MPLUS") +mtimes = EclObject("MTIMES") +rat = EclObject("RAT") +max_op_dict[mplus] = add_vararg +max_op_dict[mtimes] = mul_vararg +max_op_dict[rat] = sage_rat # Here we build dictionaries for operators needing special conversions. @@ -1365,9 +1365,9 @@ def mqapply_to_sage(expr): mlist_to_sage(car(cdr(cdr(cdr(expr))))), max_to_sr(car(cdr(cdr(cdr(cdr(expr))))))) else: - op=max_to_sr(cadr(expr)) - max_args=cddr(expr) - args=[max_to_sr(a) for a in max_args] + op = max_to_sr(cadr(expr)) + max_args = cddr(expr) + args = [max_to_sr(a) for a in max_args] return op(*args) def mdiff_to_sage(expr): @@ -1436,13 +1436,13 @@ def max_at_to_sage(expr): sage: max_at_to_sage(a.ecl()) f(1, y, z) """ - arg=max_to_sr(expr.cadr()) - subsarg=caddr(expr) - if caar(subsarg)==mlist: - subsvalues=dict( (v.lhs(),v.rhs()) for v in max_to_sr(subsarg)) + arg = max_to_sr(expr.cadr()) + subsarg = caddr(expr) + if caar(subsarg) == mlist: + subsvalues = dict( (v.lhs(),v.rhs()) for v in max_to_sr(subsarg)) else: - v=max_to_sr(subsarg) - subsvalues=dict([(v.lhs(),v.rhs())]) + v = max_to_sr(subsarg) + subsvalues = dict([(v.lhs(),v.rhs())]) return SR(arg).subs(subsvalues) def dummy_integrate(expr): @@ -1526,24 +1526,24 @@ def max_pochhammer_to_sage(expr): max_pochhammer: max_pochhammer_to_sage } -special_sage_to_max={ +special_sage_to_max = { sage.functions.log.polylog : lambda N,X : [[mqapply],[[max_li, max_array],N],X], sage.functions.gamma.psi1 : lambda X : [[mqapply],[[max_psi, max_array],0],X], sage.functions.gamma.psi2 : lambda N,X : [[mqapply],[[max_psi, max_array],N],X], - sage.functions.log.lambert_w : lambda N,X : [[max_lambert_w], X] if N==EclObject(0) else [[mqapply],[[max_lambert_w, max_array],N],X], + sage.functions.log.lambert_w : lambda N,X : [[max_lambert_w], X] if N == EclObject(0) else [[mqapply],[[max_lambert_w, max_array],N],X], sage.functions.log.harmonic_number : lambda N,X : [[max_harmo],X,N], sage.functions.hypergeometric.hypergeometric : lambda A, B, X : [[mqapply],[[max_hyper, max_array],lisp_length(A.cdr()),lisp_length(B.cdr())],A,B,X] } # Dictionaries for symbols -sage_sym_dict={} -max_sym_dict={} +sage_sym_dict = {} +max_sym_dict = {} # Generic conversion functions -max_i=EclObject("$%I") +max_i = EclObject("$%I") def pyobject_to_max(obj): r""" Convert a (simple) Python object into a Maxima object. @@ -1639,13 +1639,13 @@ def sr_to_max(expr): # _symbol0=1. See trac #12796. Note that we cannot use # SR.temp_var here since two conversions of the same # expression have to be equal. - temp_args = [SR.symbol("_symbol%s"%i) for i in range(len(args))] + temp_args = [SR.symbol("_symbol%s" % i) for i in range(len(args))] f = sr_to_max(op.function()(*temp_args)) params = op.parameter_set() deriv_max = [[mdiff],f] for i in set(params): deriv_max.extend([sr_to_max(temp_args[i]), EclObject(params.count(i))]) - at_eval=sr_to_max([temp_args[i]==args[i] for i in range(len(args))]) + at_eval = sr_to_max([temp_args[i] == args[i] for i in range(len(args))]) return EclObject([[max_at],deriv_max,at_eval]) f = sr_to_max(op.function()(*args)) @@ -1718,7 +1718,7 @@ def max_to_sr(expr): True """ if expr.consp(): - op_max=caar(expr) + op_max = caar(expr) if op_max in special_max_to_sage: return special_max_to_sage[op_max](expr) if op_max not in max_op_dict: @@ -1732,8 +1732,8 @@ def max_to_sr(expr): op = sage_expr.operator() if op in sage_op_dict: raise RuntimeError("Encountered operator mismatch in maxima-to-sr translation") - max_op_dict[op_max]=op - sage_op_dict[op]=op_max + max_op_dict[op_max] = op + sage_op_dict[op] = op_max else: op = max_op_dict[op_max] max_args = cdr(expr) diff --git a/src/sage/interfaces/mupad.py b/src/sage/interfaces/mupad.py index d5115f297d3..956de696806 100644 --- a/src/sage/interfaces/mupad.py +++ b/src/sage/interfaces/mupad.py @@ -264,11 +264,11 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, global seq seq += 1 - START = '__start__(%s+1)'%seq - END = '__end__(%s+1)'%seq - line = '%s; %s; %s;'%(START, line, END) - START = '__start__(%s)'%(seq+1) - END = '__end__(%s)'%(seq+1) + START = '__start__(%s+1)' % seq + END = '__end__(%s+1)' % seq + line = '%s; %s; %s;' % (START, line, END) + START = '__start__(%s)' % (seq+1) + END = '__end__(%s)' % (seq+1) E = self._expect E.sendline(line) @@ -276,7 +276,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, z = E.before i = z.find(START) if i == -1: - raise RuntimeError("%s\nError evaluating code in MuPAD"%z) + raise RuntimeError("%s\nError evaluating code in MuPAD" % z) z = z[i+len(START)+2:] z = z.rstrip().rstrip(END).rstrip('"').rstrip().strip('\n').strip('\r').strip('\n').replace('\\\r\n','') i = z.find('Error: ') @@ -294,7 +294,7 @@ def cputime(self, t=None): if t is None: return float(str(self('time()')))/1000 else: - return float(str(self('time() - %s'%float(t))))/1000 + return float(str(self('time() - %s' % float(t))))/1000 def set(self, var, value): """ @@ -306,7 +306,7 @@ def set(self, var, value): sage: mupad.get('a').strip() # optional - mupad '4' """ - cmd = '%s:=%s:'%(var,value) + cmd = '%s:=%s:' % (var,value) out = self.eval(cmd) i = out.find('Error: ') if i != -1: @@ -323,7 +323,7 @@ def get(self, var): '4' """ - s = self.eval('%s'%var) + s = self.eval('%s' % var) i = s.find('=') return s[i+1:] @@ -425,7 +425,7 @@ def completions(self, string, strip=False): sage: mupad.completions('linal') # optional - mupad ['linalg'] """ - res = self.eval('_pref(Complete)("%s")'%string).strip() + res = self.eval('_pref(Complete)("%s")' % string).strip() res = res.replace('\n', '').split(',') res = [s.strip().strip('"') for s in res] res = [s for s in res if not s.endswith('::')] @@ -507,7 +507,7 @@ def __getattr__(self, attrname): else: return self.__dict__[attrname] name = self._name+"::"+attrname - if P.eval('type(%s)'%name) == "DOM_DOMAIN": + if P.eval('type(%s)' % name) == "DOM_DOMAIN": return MupadElement(P, name) else: return MupadFunctionElement(self._obj, name) @@ -538,7 +538,7 @@ def __call__(self, *args): s[1, 1, 1] """ P = self._obj.parent() - if P.eval('type(%s)'%(self._obj.name())).strip() == "DOM_DOMAIN": + if P.eval('type(%s)' % (self._obj.name())).strip() == "DOM_DOMAIN": return P.function_call(self._name, list(args)) else: return P.function_call(self._name, [self._obj] + list(args)) @@ -572,8 +572,8 @@ def __getattr__(self, attrname): name = self._name + "::" + attrname try: - if P.eval('type(%s::%s)'%(self.name(),attrname)).strip() == "DOM_DOMAIN": - return P.new("%s::%s"%(self.name(),attrname)) + if P.eval('type(%s::%s)' % (self.name(),attrname)).strip() == "DOM_DOMAIN": + return P.new("%s::%s" % (self.name(),attrname)) else: return MupadFunctionElement(self, name) except RuntimeError as err: @@ -605,7 +605,7 @@ def _latex_(self): """ self._check_valid() P = self.parent() - s = P._eval_line('generate::TeX(%s)'%self.name()) + s = P._eval_line('generate::TeX(%s)' % self.name()) s = s.replace('\\\\','\\').strip().strip('"') return s diff --git a/src/sage/interfaces/mwrank.py b/src/sage/interfaces/mwrank.py index 406c4b15098..35d73277109 100644 --- a/src/sage/interfaces/mwrank.py +++ b/src/sage/interfaces/mwrank.py @@ -126,7 +126,7 @@ def validate_mwrank_input(s): """ if isinstance(s,(list,tuple)): from sage.rings.integer_ring import ZZ - if len(s)!=5: + if len(s) != 5: raise ValueError("%s is not valid input to mwrank (should have 5 entries)" % s) try: ai = [ZZ(a) for a in s] diff --git a/src/sage/interfaces/octave.py b/src/sage/interfaces/octave.py index cf4f828151c..a1a9ba50582 100644 --- a/src/sage/interfaces/octave.py +++ b/src/sage/interfaces/octave.py @@ -294,18 +294,18 @@ def _eval_line(self, line, reformat=True, allow_use_file=False, return '' if self._expect is None: self._start() - if allow_use_file and len(line)>3000: + if allow_use_file and len(line) > 3000: return self._eval_line_using_file(line) try: E = self._expect # debug # self._synchronize(cmd='1+%s\n') - verbose("in = '%s'"%line,level=3) + verbose("in = '%s'" % line,level=3) E.sendline(line) E.expect(self._prompt) out = bytes_to_str(E.before) # debug - verbose("out = '%s'"%out,level=3) + verbose("out = '%s'" % out,level=3) except EOF: if self._quit_string() in line: return '' @@ -321,7 +321,7 @@ def _eval_line(self, line, reformat=True, allow_use_file=False, return '' def _keyboard_interrupt(self): - print("CntrlC: Interrupting %s..."%self) + print("CntrlC: Interrupting %s..." % self) if self._restart_on_ctrlc: try: self._expect.close(force=1) @@ -411,7 +411,7 @@ def set(self, var, value): cmd = '%s=%s;' % (var, value) out = self.eval(cmd) if out.find("error") != -1 or out.find("Error") != -1: - raise TypeError("Error executing code in Octave\nCODE:\n\t%s\nOctave ERROR:\n\t%s"%(cmd, out)) + raise TypeError("Error executing code in Octave\nCODE:\n\t%s\nOctave ERROR:\n\t%s" % (cmd, out)) def get(self, var): """ @@ -423,7 +423,7 @@ def get(self, var): sage: octave.get('x') # optional - octave ' 2' """ - s = self.eval('%s'%var) + s = self.eval('%s' % var) i = s.find('=') return s[i+1:] @@ -578,11 +578,11 @@ def de_system_plot(self, f, ics, trange): """ eqn1 = f[0].replace('x','x(1)').replace('y','x(2)') eqn2 = f[1].replace('x','x(1)').replace('y','x(2)') - fcn = "function xdot = f(x,t) xdot(1) = %s; xdot(2) = %s; endfunction"%(eqn1, eqn2) + fcn = "function xdot = f(x,t) xdot(1) = %s; xdot(2) = %s; endfunction" % (eqn1, eqn2) self.eval(fcn) - x0_eqn = "x0 = [%s; %s]"%(ics[0], ics[1]) + x0_eqn = "x0 = [%s; %s]" % (ics[0], ics[1]) self.eval(x0_eqn) - t_eqn = "t = linspace(%s, %s, 200)'"%(trange[0], trange[1]) + t_eqn = "t = linspace(%s, %s, 200)'" % (trange[0], trange[1]) self.eval(t_eqn) x_eqn = 'x = lsode("f",x0,t);' self.eval(x_eqn) diff --git a/src/sage/interfaces/psage.py b/src/sage/interfaces/psage.py index f00d0612703..b64a0b15c5f 100644 --- a/src/sage/interfaces/psage.py +++ b/src/sage/interfaces/psage.py @@ -74,7 +74,7 @@ def _repr_(self): A running non-blocking (parallel) instance of Sage (number ...) """ - return 'A running non-blocking (parallel) instance of Sage (number %s)'%(self._number) + return 'A running non-blocking (parallel) instance of Sage (number %s)' % (self._number) def _unlock(self): self._locked = False @@ -124,7 +124,7 @@ def __del__(self): pass if not (self._expect is None): - cmd = 'kill -9 %s'%self._expect.pid + cmd = 'kill -9 %s' % self._expect.pid os.system(cmd) def eval(self, x, strip=True, **kwds): @@ -158,7 +158,7 @@ def set(self, var, value): """ Set the variable var to the given value. """ - cmd = '%s=%s'%(var,value) + cmd = '%s=%s' % (var,value) self._send_nowait(cmd) time.sleep(0.02) diff --git a/src/sage/interfaces/qepcad.py b/src/sage/interfaces/qepcad.py index 8322aa361d0..b6b657515bc 100644 --- a/src/sage/interfaces/qepcad.py +++ b/src/sage/interfaces/qepcad.py @@ -660,7 +660,7 @@ def _qepcad_cmd(memcells=None): memcells_arg = '+N%s' % memcells else: memcells_arg = '' - return "env qe=%s qepcad %s"%(SAGE_LOCAL, memcells_arg) + return "env qe=%s qepcad %s" % (SAGE_LOCAL, memcells_arg) _command_info_cache = None @@ -835,7 +835,7 @@ def __init__(self, formula, self._cell_cache = {} if verbose: - logfile=sys.stdout + logfile = sys.stdout varlist = None if vars is not None: @@ -1320,14 +1320,14 @@ def _function_call(self, name, args): name = name.replace('_', '-') args = [str(_) for _ in args] pre_phase = self.phase() - result = self._eval_line('%s %s'%(name, ' '.join(args))) + result = self._eval_line('%s %s' % (name, ' '.join(args))) post_phase = self.phase() if len(result) and post_phase != 'EXITED': return AsciiArtString(result) if pre_phase != post_phase: if post_phase == 'EXITED' and name != 'quit': return self.answer() - return AsciiArtString("QEPCAD object has moved to phase '%s'"%post_phase) + return AsciiArtString("QEPCAD object has moved to phase '%s'" % post_phase) def _format_cell_index(a): """ diff --git a/src/sage/interfaces/quit.py b/src/sage/interfaces/quit.py index e068c324b13..575646f2365 100644 --- a/src/sage/interfaces/quit.py +++ b/src/sage/interfaces/quit.py @@ -45,7 +45,7 @@ def register_spawned_process(pid, cmd=''): # This is safe, since only this process writes to this file. try: with open(sage_spawned_process_file(), 'a') as o: - o.write('%s %s\n'%(pid, cmd)) + o.write('%s %s\n' % (pid, cmd)) except IOError: pass else: diff --git a/src/sage/interfaces/r.py b/src/sage/interfaces/r.py index acf984ddba9..068e65a2096 100644 --- a/src/sage/interfaces/r.py +++ b/src/sage/interfaces/r.py @@ -287,7 +287,7 @@ lazy_import("rpy2.robjects.help", "Package") lazy_import("rpy2", "rinterface") -COMMANDS_CACHE = '%s/r_commandlist.sobj'%DOT_SAGE +COMMANDS_CACHE = '%s/r_commandlist.sobj' % DOT_SAGE #there is a mirror network, but lets take #1 for now RRepositoryURL = "http://cran.r-project.org/" @@ -596,8 +596,8 @@ def _start(self): # pager needed to replace help view from less to printout # option device= is for plotting, is set to x11, NULL would be better? self.eval('options(pager="cat",device="png")') - self.eval('options(repos="%s")'%RRepositoryURL) - self.eval('options(CRAN="%s")'%RRepositoryURL) + self.eval('options(repos="%s")' % RRepositoryURL) + self.eval('options(CRAN="%s")' % RRepositoryURL) # don't abort on errors, just raise them! # necessary for non-interactive execution @@ -683,8 +683,8 @@ def install_packages(self, package_name): ... Please restart Sage in order to use 'aaMI'. """ - cmd = """options(repos="%s"); install.packages("%s")"""%(RRepositoryURL, package_name) - os.system("time echo '%s' | R --vanilla"%cmd) + cmd = """options(repos="%s"); install.packages("%s")""" % (RRepositoryURL, package_name) + os.system("time echo '%s' | R --vanilla" % cmd) print("Please restart Sage in order to use '%s'." % package_name) def _repr_(self): @@ -744,7 +744,7 @@ def _read_in_file_command(self, filename): sage: r._read_in_file_command('file.txt') # optional - rpy2 'file=file("file.txt",open="r")\nsource(file)' """ - return 'file=file("%s",open="r")\nsource(file)'%filename + return 'file=file("%s",open="r")\nsource(file)' % filename def read(self, filename): r""" @@ -788,7 +788,7 @@ def _source(self, s): """ if s[-2:] == "()": s = s[-2:] - return self.eval('%s'%s) + return self.eval('%s' % s) def source(self, s): """ @@ -891,7 +891,7 @@ def available_packages(self): sage: len(ap) > 20 # optional - internet # optional - rpy2 True """ - p = self.new('available.packages("%s/src/contrib")'%RRepositoryURL) + p = self.new('available.packages("%s/src/contrib")' % RRepositoryURL) s = str(p).splitlines()[1:] v = [x.split()[0].strip("'") for x in s] return v @@ -1071,7 +1071,7 @@ def function_call(self, function, args=None, kwds=None): """ args, kwds = self._convert_args_kwds(args, kwds) self._check_valid_function_name(function) - return self.new("%s(%s)"%(function, ",".join([s.name() for s in args] + + return self.new("%s(%s)" % (function, ",".join([s.name() for s in args] + [self._sage_to_r_name(key)+'='+kwds[key].name() for key in kwds ] ))) def call(self, function_name, *args, **kwds): @@ -1117,7 +1117,7 @@ def set(self, var, value): '[1] 5' """ - cmd = '%s <- %s'%(var,value) + cmd = '%s <- %s' % (var,value) out = self.eval(cmd) def get(self, var): @@ -1136,7 +1136,7 @@ def get(self, var): sage: r.get('a') # optional - rpy2 '[1] 2' """ - return self.eval('%s'%var) + return self.eval('%s' % var) def na(self): """ @@ -1195,7 +1195,7 @@ def _commands(self): if lib.find("package:") != 0: continue #only packages - raw = self('objects("%s")'%lib)._sage_() + raw = self('objects("%s")' % lib)._sage_() #TODO are there others? many of them are shortcuts or #should be done on another level, like selections in lists @@ -1508,7 +1508,7 @@ def __len__(self): sage: len(x) # optional - rpy2 5 """ - return self.parent()('length(%s)'%self.name()).sage() + return self.parent()('length(%s)' % self.name()).sage() def __getattr__(self, attrname): """ @@ -1589,11 +1589,11 @@ def __getitem__(self, n): P = self._check_valid() if isinstance(n, str): n = n.replace('self', self._name) - return P.new('%s[%s]'%(self._name, n)) + return P.new('%s[%s]' % (self._name, n)) elif parent(n) is P: # the key is RElement itself - return P.new('%s[%s]'%(self._name, n.name())) + return P.new('%s[%s]' % (self._name, n.name())) elif not isinstance(n,tuple): - return P.new('%s[%s]'%(self._name, n)) + return P.new('%s[%s]' % (self._name, n)) else: L = [] for i in range(len(n)): @@ -1601,7 +1601,7 @@ def __getitem__(self, n): L.append(n[i].name()) else: L.append(str(n[i])) - return P.new('%s[%s]'%(self._name, ','.join(L))) + return P.new('%s[%s]' % (self._name, ','.join(L))) def __bool__(self): """ @@ -1646,7 +1646,7 @@ def _comparison(self, other, symbol): """ P = self.parent() other = P(other) - return P('%s %s %s'%(self.name(), symbol, other.name())) + return P('%s %s %s' % (self.name(), symbol, other.name())) def __eq__(self, other): """ @@ -1791,7 +1791,7 @@ def dot_product(self, other): P = self._check_valid() Q = P(other) # the R operator is %*% for matrix multiplication - return P('%s %%*%% %s'%(self.name(), Q.name())) + return P('%s %%*%% %s' % (self.name(), Q.name())) def _sage_(self): r""" diff --git a/src/sage/interfaces/scilab.py b/src/sage/interfaces/scilab.py index 2e00b08372a..54c28f55598 100644 --- a/src/sage/interfaces/scilab.py +++ b/src/sage/interfaces/scilab.py @@ -349,10 +349,10 @@ def set(self, var, value): sage: scilab.get('a') # optional - scilab '\n \n 123.' """ - cmd = '%s=%s;'%(var,value) + cmd = '%s=%s;' % (var,value) out = self.eval(cmd) if out.find("error") != -1: - raise TypeError("Error executing code in Scilab\nCODE:\n\t%s\nScilab ERROR:\n\t%s"%(cmd, out)) + raise TypeError("Error executing code in Scilab\nCODE:\n\t%s\nScilab ERROR:\n\t%s" % (cmd, out)) def get(self, var): """ @@ -365,7 +365,7 @@ def get(self, var): sage: scilab.get('b') # optional - scilab '\n \n 124.' """ - s = self.eval('%s'%var) + s = self.eval('%s' % var) i = s.find('=') return s[i+1:] @@ -509,7 +509,7 @@ def set(self, i, j, x): """ P = self._check_valid() z = P(x) - P.eval('%s(%s,%s) = %s'%(self.name(), i, j, z.name())) + P.eval('%s(%s,%s) = %s' % (self.name(), i, j, z.name())) # An instance diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py index c7e24d5ae46..c4fb1261288 100644 --- a/src/sage/interfaces/singular.py +++ b/src/sage/interfaces/singular.py @@ -664,7 +664,7 @@ def eval(self, x, allow_semicolon=True, strip=True, **kwds): # "Segment fault" is not a typo: # Singular actually does use that string if s.find("error occurred") != -1 or s.find("Segment fault") != -1: - raise SingularError('Singular error:\n%s'%s) + raise SingularError('Singular error:\n%s' % s) if get_verbose() > 0: for line in s.splitlines(): @@ -703,8 +703,8 @@ def set(self, type, name, value): '0' """ - cmd = ''.join('if(defined(%s)){kill %s;};'%(v,v) for v in self.__to_clear) - cmd += '%s %s=%s;'%(type, name, value) + cmd = ''.join('if(defined(%s)){kill %s;};' % (v,v) for v in self.__to_clear) + cmd += '%s %s=%s;' % (type, name, value) self.__to_clear = [] self.eval(cmd) @@ -718,7 +718,7 @@ def get(self, var): sage: singular.get('x') '2' """ - return self.eval('print(%s);'%var) + return self.eval('print(%s);' % var) def clear(self, var): """ @@ -843,7 +843,7 @@ def cputime(self, t=None): 0.02 """ if t: - return float(self.eval('timer-(%d)'%(int(1000*t))))/1000.0 + return float(self.eval('timer-(%d)' % (int(1000*t))))/1000.0 else: return float(self.eval('timer'))/1000.0 @@ -1041,9 +1041,9 @@ def matrix(self, nrows, ncols, entries=None): """ name = self._next_var_name() if entries is None: - self.eval('matrix %s[%s][%s]'%(name, nrows, ncols)) + self.eval('matrix %s[%s][%s]' % (name, nrows, ncols)) else: - self.eval('matrix %s[%s][%s] = %s'%(name, nrows, ncols, entries)) + self.eval('matrix %s[%s][%s] = %s' % (name, nrows, ncols, entries)) return SingularElement(self, None, name, True) def ring(self, char=0, vars='(x)', order='lp', check=None): @@ -1442,13 +1442,13 @@ def __copy__(self): 0, y,0, x*y,0,0 """ - if (self.type()=='ring') or (self.type()=='qring'): + if (self.type() == 'ring') or (self.type() == 'qring'): # Problem: singular has no clean method to produce # a copy of a ring/qring. We use ringlist, but this # is only possible if we make self the active ring, # use ringlist, and switch back to the previous # base ring. - br=self.parent().current_ring() + br = self.parent().current_ring() self.set_ring() OUT = (self.ringlist()).ring() br.set_ring() @@ -1508,9 +1508,9 @@ def __setitem__(self, n, value): if len(n) != 2: raise ValueError("If n (=%s) is a tuple, it must be a 2-tuple" % n) x, y = n - P.eval('%s[%s,%s] = %s'%(self.name(), x, y, value.name())) + P.eval('%s[%s,%s] = %s' % (self.name(), x, y, value.name())) else: - P.eval('%s[%s] = %s'%(self.name(), n, value.name())) + P.eval('%s[%s] = %s' % (self.name(), n, value.name())) def __bool__(self): """ @@ -1634,7 +1634,7 @@ def sage_global_ring(self): singular = self.parent() charstr = singular.eval('charstr(basering)').split(',',1) from sage.rings.integer_ring import ZZ - is_extension = len(charstr)==2 + is_extension = len(charstr) == 2 if charstr[0] in ['integer', 'ZZ']: br = ZZ is_extension = False @@ -1648,7 +1648,7 @@ def sage_global_ring(self): prec = singular.eval('ringlist(basering)[1][2][1]') br = RealField(ceil((ZZ(prec)+1)/log(2,10))) is_extension = False - elif charstr[0]=='complex': + elif charstr[0] == 'complex': from sage.rings.complex_mpfr import ComplexField from sage.functions.other import ceil from sage.misc.functional import log @@ -1678,7 +1678,7 @@ def sage_global_ring(self): if is_short != '0': singular.eval('short=0') minpoly = ZZ[charstr[1]](singular.eval('minpoly')) - singular.eval('short=%s'%is_short) + singular.eval('short=%s' % is_short) else: minpoly = ZZ[charstr[1]](minpoly) BR = br.extension(minpoly,names=charstr[1]) @@ -1692,7 +1692,7 @@ def sage_global_ring(self): # Meanwhile Singulars quotient rings are also of 'ring' type, not 'qring' as it was in the past. # To find out if a singular ring is a quotient ring or not checking for ring type does not help # and instead of that we check if the quotient ring is zero or not: - if (singular.eval('ideal(basering)==0')=='1'): + if (singular.eval('ideal(basering)==0') == '1'): return PolynomialRing(BR, names=singular.eval('varstr(basering)'), order=termorder_from_singular(singular)) P = PolynomialRing(BR, names=singular.eval('varstr(basering)'), order=termorder_from_singular(singular)) return P.quotient(singular('ringlist(basering)[4]')._sage_(P), names=singular.eval('varstr(basering)')) @@ -1822,15 +1822,15 @@ def sage_poly(self, R=None, kcache=None): # as we know what to expect. is_short = self.parent().eval('short') - if is_short!='0': + if is_short != '0': self.parent().eval('short=0') if isinstance(R, MPolynomialRing_libsingular): out = R(self) - self.parent().eval('short=%s'%is_short) + self.parent().eval('short=%s' % is_short) return out singular_poly_list = self.parent().eval("string(coef(%s,%s))" % ( self.name(),variable_str)).split(",") - self.parent().eval('short=%s'%is_short) + self.parent().eval('short=%s' % is_short) else: if isinstance(R, MPolynomialRing_libsingular): return R(self) @@ -1864,19 +1864,19 @@ def sage_poly(self, R=None, kcache=None): variables = [var.split("^") for var in monomial.split("*") ] for e in variables: var = e[0] - if len(e)==int(2): + if len(e) == int(2): power = int(e[1]) else: - power=1 - exp[var_dict[var]]=power + power = 1 + exp[var_dict[var]] = power if kcache is None: - sage_repr[ETuple(exp,ngens)]=k(singular_poly_list[coeff_start+i]) + sage_repr[ETuple(exp,ngens)] = k(singular_poly_list[coeff_start+i]) else: elem = singular_poly_list[coeff_start+i] if elem not in kcache: kcache[elem] = k( elem ) - sage_repr[ETuple(exp,ngens)]= kcache[elem] + sage_repr[ETuple(exp,ngens)] = kcache[elem] return R(sage_repr) @@ -1890,7 +1890,7 @@ def sage_poly(self, R=None, kcache=None): if monomial not in ['1', '(1.000e+00)']: term = monomial.split("^") - if len(term)==int(2): + if len(term) == int(2): exp = int(term[1]) else: exp = int(1) @@ -1901,7 +1901,7 @@ def sage_poly(self, R=None, kcache=None): elem = singular_poly_list[coeff_start+i] if elem not in kcache: kcache[elem] = k( elem ) - sage_repr[ exp ]= kcache[elem] + sage_repr[ exp ] = kcache[elem] return R(sage_repr) @@ -1941,14 +1941,14 @@ def sage_matrix(self, R, sparse=True): #this is slow for x in range(nrows): for y in range(ncols): - A[x,y]=self[x+1,y+1].sage_poly(R) + A[x,y] = self[x+1,y+1].sage_poly(R) return A A = Matrix(R, nrows, ncols, sparse=sparse) #this is slow for x in range(nrows): for y in range(ncols): - A[x,y]=R(self[x+1,y+1]) + A[x,y] = R(self[x+1,y+1]) return A @@ -2027,9 +2027,9 @@ def _sage_(self, R=None): """ typ = self.type() - if typ=='poly': + if typ == 'poly': return self.sage_poly(R) - elif typ=='int': + elif typ == 'int': return sage.rings.integer.Integer(repr(self)) elif typ == 'module': return self.sage_matrix(R,sparse=True) @@ -2149,7 +2149,7 @@ def sage_structured_str_list(self): sage: RL.sage_structured_str_list() ['0', ['x', 'y'], [['dp', '1,\n1'], ['C', '0']], '0'] """ - if not (self.type()=='list'): + if not (self.type() == 'list'): return str(self) return [X.sage_structured_str_list() for X in self] diff --git a/src/sage/interfaces/tests.py b/src/sage/interfaces/tests.py index 559855d9f85..8c760c2a2c0 100644 --- a/src/sage/interfaces/tests.py +++ b/src/sage/interfaces/tests.py @@ -51,14 +51,14 @@ def manyvars(s, num=70000, inlen=1, step=2000): Test that > 65,000 variable names works in each system. """ print("Testing -- %s" % s) - t = '"%s"'%('9'*int(inlen)) + t = '"%s"' % ('9'*int(inlen)) try: t = cputime() w = walltime() v = [] for i in range(num): - if i%step==0: - sys.stdout.write('%s '%i) + if i % step == 0: + sys.stdout.write('%s ' % i) sys.stdout.flush() v.append(s(t)) print('\nsuccess -- time = cpu: %s, wall: %s' % (cputime(t), diff --git a/src/sage/interfaces/tides.py b/src/sage/interfaces/tides.py index bb48e4a2fd8..765b8bd3cb4 100644 --- a/src/sage/interfaces/tides.py +++ b/src/sage/interfaces/tides.py @@ -156,9 +156,9 @@ def subexpressions_list(f, pars=None): F = symbolic_expression([i(*variables) for i in f]).function(*varpar) lis = flatten([fast_callable(i,vars=varpar).op_list() for i in F], max_level=1) stack = [] - const =[] - stackcomp=[] - detail=[] + const = [] + stackcomp = [] + detail = [] for i in lis: if i[0] == 'load_arg': stack.append(varpar[i[1]]) @@ -166,76 +166,76 @@ def subexpressions_list(f, pars=None): if i[1] in NN: basis = stack[-1] for j in range(i[1]-1): - a=stack.pop(-1) + a = stack.pop(-1) detail.append(('mul', a, basis)) stack.append(a*basis) stackcomp.append(stack[-1]) else: detail.append(('pow',stack[-1],i[1])) - stack[-1]=stack[-1]**i[1] + stack[-1] = stack[-1]**i[1] stackcomp.append(stack[-1]) elif i[0] == 'load_const': const.append(i[1]) stack.append(i[1]) elif i == 'mul': - a=stack.pop(-1) - b=stack.pop(-1) + a = stack.pop(-1) + b = stack.pop(-1) detail.append(('mul', a, b)) stack.append(a*b) stackcomp.append(stack[-1]) elif i == 'div': - a=stack.pop(-1) - b=stack.pop(-1) + a = stack.pop(-1) + b = stack.pop(-1) detail.append(('div', a, b)) stack.append(b/a) stackcomp.append(stack[-1]) elif i == 'add': - a=stack.pop(-1) - b=stack.pop(-1) + a = stack.pop(-1) + b = stack.pop(-1) detail.append(('add',a,b)) stack.append(a+b) stackcomp.append(stack[-1]) elif i == 'pow': - a=stack.pop(-1) - b=stack.pop(-1) + a = stack.pop(-1) + b = stack.pop(-1) detail.append(('pow', b, a)) stack.append(b**a) stackcomp.append(stack[-1]) - elif i[0] == 'py_call' and str(i[1])=='log': - a=stack.pop(-1) + elif i[0] == 'py_call' and str(i[1]) == 'log': + a = stack.pop(-1) detail.append(('log', a)) stack.append(log(a)) stackcomp.append(stack[-1]) - elif i[0] == 'py_call' and str(i[1])=='exp': - a=stack.pop(-1) + elif i[0] == 'py_call' and str(i[1]) == 'exp': + a = stack.pop(-1) detail.append(('exp', a)) stack.append(exp(a)) stackcomp.append(stack[-1]) - elif i[0] == 'py_call' and str(i[1])=='sin': - a=stack.pop(-1) + elif i[0] == 'py_call' and str(i[1]) == 'sin': + a = stack.pop(-1) detail.append(('sin', a)) detail.append(('cos', a)) stackcomp.append(sin(a)) stackcomp.append(cos(a)) stack.append(sin(a)) - elif i[0] == 'py_call' and str(i[1])=='cos': - a=stack.pop(-1) + elif i[0] == 'py_call' and str(i[1]) == 'cos': + a = stack.pop(-1) detail.append(('sin', a)) detail.append(('cos', a)) stackcomp.append(sin(a)) stackcomp.append(cos(a)) stack.append(cos(a)) - elif i[0] == 'py_call' and str(i[1])=='tan': - a=stack.pop(-1) + elif i[0] == 'py_call' and str(i[1]) == 'tan': + a = stack.pop(-1) b = sin(a) c = cos(a) detail.append(('sin', a)) @@ -246,8 +246,8 @@ def subexpressions_list(f, pars=None): stackcomp.append(b/c) stack.append(b/c) - elif i[0] == 'py_call' and str(i[1])=='arctan': - a=stack.pop(-1) + elif i[0] == 'py_call' and str(i[1]) == 'arctan': + a = stack.pop(-1) detail.append(('mul', a, a)) detail.append(('add', 1, a*a)) detail.append(('atan', a)) @@ -256,12 +256,12 @@ def subexpressions_list(f, pars=None): stackcomp.append(arctan(a)) stack.append(arctan(a)) - elif i[0] == 'py_call' and str(i[1])=='arcsin': - a=stack.pop(-1) + elif i[0] == 'py_call' and str(i[1]) == 'arcsin': + a = stack.pop(-1) detail.append(('mul', a, a)) detail.append(('mul', -1, a*a)) detail.append(('add', 1, -a*a)) - detail.append(('pow', 1- a*a, 0.5)) + detail.append(('pow', 1 - a*a, 0.5)) detail.append(('asin', a)) stackcomp.append(a*a) stackcomp.append(-a*a) @@ -270,12 +270,12 @@ def subexpressions_list(f, pars=None): stackcomp.append(arcsin(a)) stack.append(arcsin(a)) - elif i[0] == 'py_call' and str(i[1])=='arccos': - a=stack.pop(-1) + elif i[0] == 'py_call' and str(i[1]) == 'arccos': + a = stack.pop(-1) detail.append(('mul', a, a)) detail.append(('mul', -1, a*a)) detail.append(('add', 1, -a*a)) - detail.append(('pow', 1- a*a, 0.5)) + detail.append(('pow', 1 - a*a, 0.5)) detail.append(('mul', -1, sqrt(1-a*a))) detail.append(('acos', a)) stackcomp.append(a*a) @@ -287,7 +287,7 @@ def subexpressions_list(f, pars=None): stack.append(arccos(a)) elif i[0] == 'py_call' and 'sqrt' in str(i[1]): - a=stack.pop(-1) + a = stack.pop(-1) detail.append(('pow', a, 0.5)) stackcomp.append(sqrt(a)) stack.append(sqrt(a)) @@ -334,13 +334,13 @@ def remove_repeated(l1, l2): """ for i in range(len(l1)-1): - j=i+1 - while j) failed: NotImplementedError> """ if not isinstance(base_field, ring.Field): - raise TypeError("The base_field (=%s) must be a field"%base_field) + raise TypeError("The base_field (=%s) must be a field" % base_field) super().__init__(base_field, dimension, degree, sparse=sparse, category=category) def _Hom_(self, Y, category): @@ -5597,9 +5597,9 @@ def _repr_(self): Ambient free module of rank 12 over Ring of integers modulo 12 """ if self.is_sparse(): - return "Ambient sparse free module of rank %s over %s"%(self.rank(), self.base_ring()) + return "Ambient sparse free module of rank %s over %s" % (self.rank(), self.base_ring()) else: - return "Ambient free module of rank %s over %s"%(self.rank(), self.base_ring()) + return "Ambient free module of rank %s over %s" % (self.rank(), self.base_ring()) def _latex_(self): r""" @@ -6063,10 +6063,10 @@ def _repr_(self): Ambient free module of rank 7 over the integral domain Univariate Polynomial Ring in x over Integer Ring """ if self.is_sparse(): - return "Ambient sparse free module of rank %s over the integral domain %s"%( + return "Ambient sparse free module of rank %s over the integral domain %s" % ( self.rank(), self.base_ring()) else: - return "Ambient free module of rank %s over the integral domain %s"%( + return "Ambient free module of rank %s over the integral domain %s" % ( self.rank(), self.base_ring()) def ambient_vector_space(self): @@ -6255,10 +6255,10 @@ def _repr_(self): Ambient free module of rank 7 over the principal ideal domain Integer Ring """ if self.is_sparse(): - return "Ambient sparse free module of rank %s over the principal ideal domain %s"%( + return "Ambient sparse free module of rank %s over the principal ideal domain %s" % ( self.rank(), self.base_ring()) else: - return "Ambient free module of rank %s over the principal ideal domain %s"%( + return "Ambient free module of rank %s over the principal ideal domain %s" % ( self.rank(), self.base_ring()) @@ -6332,9 +6332,9 @@ def _repr_(self): Vector space of dimension 7 over Rational Field """ if self.is_sparse(): - return "Sparse vector space of dimension %s over %s"%(self.dimension(), self.base_ring()) + return "Sparse vector space of dimension %s over %s" % (self.dimension(), self.base_ring()) else: - return "Vector space of dimension %s over %s"%(self.dimension(), self.base_ring()) + return "Vector space of dimension %s over %s" % (self.dimension(), self.base_ring()) def ambient_vector_space(self): """ @@ -6783,11 +6783,11 @@ def _repr_(self): [-1 0 0 0 0 0 0 1] """ if self.is_sparse(): - s = "Sparse free module of degree %s and rank %s over %s\n"%( + s = "Sparse free module of degree %s and rank %s over %s\n" % ( self.degree(), self.rank(), self.base_ring()) + \ "User basis matrix:\n%r" % self.basis_matrix() else: - s = "Free module of degree %s and rank %s over %s\n"%( + s = "Free module of degree %s and rank %s over %s\n" % ( self.degree(), self.rank(), self.base_ring()) + \ "User basis matrix:\n%r" % self.basis_matrix() return s @@ -6803,7 +6803,7 @@ def _latex_(self): sage: M._latex_() '\\mathrm{RowSpan}_{\\Bold{Z}}\\left(\\begin{array}{rrr}\n1 & 2 & 3 \\\\\n4 & 5 & 6\n\\end{array}\\right)' """ - return "\\mathrm{RowSpan}_{%s}%s"%(latex.latex(self.base_ring()), latex.latex(self.basis_matrix())) + return "\\mathrm{RowSpan}_{%s}%s" % (latex.latex(self.base_ring()), latex.latex(self.basis_matrix())) def ambient_module(self): """ @@ -7605,13 +7605,13 @@ def _repr_(self): [ 0 0 0 0 0 0 1 -1] """ if self.is_sparse(): - s = "Sparse free module of degree %s and rank %s over %s\n"%( + s = "Sparse free module of degree %s and rank %s over %s\n" % ( self.degree(), self.rank(), self.base_ring()) + \ - "Echelon basis matrix:\n%s"%self.basis_matrix() + "Echelon basis matrix:\n%s" % self.basis_matrix() else: - s = "Free module of degree %s and rank %s over %s\n"%( + s = "Free module of degree %s and rank %s over %s\n" % ( self.degree(), self.rank(), self.base_ring()) + \ - "Echelon basis matrix:\n%s"%self.basis_matrix() + "Echelon basis matrix:\n%s" % self.basis_matrix() return s def coordinate_vector(self, v, check=True): @@ -7809,11 +7809,11 @@ def _repr_(self): [ 0 0 0 1 -1] """ if self.is_sparse(): - return "Sparse vector space of degree %s and dimension %s over %s\n"%( + return "Sparse vector space of degree %s and dimension %s over %s\n" % ( self.degree(), self.dimension(), self.base_field()) + \ "User basis matrix:\n%r" % self.basis_matrix() else: - return "Vector space of degree %s and dimension %s over %s\n"%( + return "Vector space of degree %s and dimension %s over %s\n" % ( self.degree(), self.dimension(), self.base_field()) + \ "User basis matrix:\n%r" % self.basis_matrix() @@ -8008,11 +8008,11 @@ def _repr_(self): [ 0 0 0 1 -1] """ if self.is_sparse(): - return "Sparse vector space of degree %s and dimension %s over %s\n"%( + return "Sparse vector space of degree %s and dimension %s over %s\n" % ( self.degree(), self.dimension(), self.base_field()) + \ "Basis matrix:\n%r" % self.basis_matrix() else: - return "Vector space of degree %s and dimension %s over %s\n"%( + return "Vector space of degree %s and dimension %s over %s\n" % ( self.degree(), self.dimension(), self.base_field()) + \ "Basis matrix:\n%r" % self.basis_matrix() @@ -8059,7 +8059,7 @@ def echelon_coordinates(self, v, check=True): if not isinstance(v, free_module_element.FreeModuleElement): v = self.ambient_vector_space()(v) if v.degree() != self.degree(): - raise ArithmeticError("v (=%s) is not in self"%v) + raise ArithmeticError("v (=%s) is not in self" % v) E = self.echelonized_basis_matrix() P = E.pivots() if not P: diff --git a/src/sage/modules/free_module_morphism.py b/src/sage/modules/free_module_morphism.py index 2dbf903eba8..cdc933f23d0 100644 --- a/src/sage/modules/free_module_morphism.py +++ b/src/sage/modules/free_module_morphism.py @@ -355,7 +355,7 @@ def inverse_image(self, V): else: if not hasattr(A, 'hermite_form'): - raise NotImplementedError("base ring (%s) must have hermite_form algorithm in order to compute inverse image"%R) + raise NotImplementedError("base ring (%s) must have hermite_form algorithm in order to compute inverse image" % R) # 1. Compute H such that U*A = H = hnf(A) without zero # rows. What this "does" is find a basis for the image of @@ -463,7 +463,7 @@ def lift(self, x): else: # see inverse_image for similar code but with comments if not hasattr(A, 'hermite_form'): - raise NotImplementedError("base ring (%s) must have hermite_form algorithm in order to compute inverse image"%R) + raise NotImplementedError("base ring (%s) must have hermite_form algorithm in order to compute inverse image" % R) H, U = A.hermite_form(transformation=True,include_zero_rows=False) Y = H.solve_left(vector(self.codomain().coordinates(x))) C = Y*U @@ -557,13 +557,13 @@ def eigenvectors(self, extend=True): if self.base_ring().is_field(): if self.is_endomorphism(): if self.side() == "right": - seigenvec=self.matrix().eigenvectors_right(extend=extend) + seigenvec = self.matrix().eigenvectors_right(extend=extend) else: - seigenvec=self.matrix().eigenvectors_left(extend=extend) - resu=[] + seigenvec = self.matrix().eigenvectors_left(extend=extend) + resu = [] for i in seigenvec: - V=self.domain().base_extend(i[0].parent()) - svectors=Sequence([V(j * V.basis_matrix()) for j in i[1]], cr=True) + V = self.domain().base_extend(i[0].parent()) + svectors = Sequence([V(j * V.basis_matrix()) for j in i[1]], cr=True) resu.append((i[0],svectors,i[2])) return resu else: diff --git a/src/sage/modules/free_quadratic_module_integer_symmetric.py b/src/sage/modules/free_quadratic_module_integer_symmetric.py index 9cdc7637140..e4959cc7a55 100644 --- a/src/sage/modules/free_quadratic_module_integer_symmetric.py +++ b/src/sage/modules/free_quadratic_module_integer_symmetric.py @@ -593,7 +593,7 @@ def IntegralLatticeGluing(Lattices, glue, return_embeddings=False): [direct_sum, phi] = IntegralLatticeDirectSum(Lattices, return_embeddings=True) N = len(Lattices) for g in glue: - if not len(g)==N: + if not len(g) == N: raise ValueError("the lengths of the lists do not match") for i in range(N): ALi = Lattices[i].discriminant_group() @@ -692,7 +692,7 @@ def _mul_(self, other, switch_sides=False): B = self.basis_matrix() B = other * B if switch_sides else B * other # check whether it is integral - if other in ZZ or other.denominator()==1: + if other in ZZ or other.denominator() == 1: return self.sublattice(B.rows()) else: return self.span(B.rows()) @@ -1058,7 +1058,7 @@ def maximal_overlattice(self, p=None): # it might speed up things to use the algorithms given in # https://arxiv.org/abs/1208.2481 # and trac:11940 - if not self.is_even() and (p is None or p==2): + if not self.is_even() and (p is None or p == 2): raise ValueError("this lattice must be even to admit an even overlattice") from sage.rings.finite_rings.finite_field_constructor import GF L = self @@ -1306,7 +1306,7 @@ def orthogonal_group(self, gens=None, is_finite=None): invariant_quotient_module=D) return G - automorphisms=orthogonal_group + automorphisms = orthogonal_group def genus(self): r""" @@ -1481,7 +1481,7 @@ def LLL(self): from sage.libs.pari import pari m = self.gram_matrix().__pari__() gp.read(SAGE_EXTCODE + "/pari/simon/qfsolve.gp") - m = gp.eval('qflllgram_indefgoon(%s)'%m) + m = gp.eval('qflllgram_indefgoon(%s)' % m) # convert the output string to sage G, U = pari(m).sage() U = U.T @@ -1572,7 +1572,7 @@ def twist(self, s, discard_basis=False): s = self.base_ring()(s) except TypeError: raise ValueError("the scaling factor must be an element of the base ring.") - if s==0: + if s == 0: raise ValueError("the scaling factor must be non zero") if discard_basis: return IntegralLattice(s * self.gram_matrix()) diff --git a/src/sage/modules/matrix_morphism.py b/src/sage/modules/matrix_morphism.py index 2ad91a155ae..b9d45e9755f 100644 --- a/src/sage/modules/matrix_morphism.py +++ b/src/sage/modules/matrix_morphism.py @@ -188,7 +188,7 @@ def _call_(self, x): if parent(x) is not self.domain(): x = self.domain()(x) except TypeError: - raise TypeError("%s must be coercible into %s"%(x,self.domain())) + raise TypeError("%s must be coercible into %s" % (x,self.domain())) if self.domain().is_ambient(): x = x.element() else: diff --git a/src/sage/modules/vector_callable_symbolic_dense.py b/src/sage/modules/vector_callable_symbolic_dense.py index 306982c2cc3..1929eabcf46 100644 --- a/src/sage/modules/vector_callable_symbolic_dense.py +++ b/src/sage/modules/vector_callable_symbolic_dense.py @@ -69,7 +69,7 @@ def _repr_(self): """ ring = self.coordinate_ring() args = ring.arguments() - repr_x=self.change_ring(SR)._repr_() + repr_x = self.change_ring(SR)._repr_() if len(args) == 1: return "%s |--> %s" % (args[0], repr_x) else: diff --git a/src/sage/plot/animate.py b/src/sage/plot/animate.py index 49f2ecd87d5..c917452e2be 100644 --- a/src/sage/plot/animate.py +++ b/src/sage/plot/animate.py @@ -327,7 +327,7 @@ def _repr_(self): num = len(self) except TypeError: num = "unknown number of" - return "Animation with %s frames"%num + return "Animation with %s frames" % num def __add__(self, other): """ @@ -498,7 +498,7 @@ def png(self, dir=None): dir = tmp_dir() i = 0 for frame in self._frames: - filename = '%s/%08d.png'%(dir,i) + filename = '%s/%08d.png' % (dir,i) try: save_image = frame.save_image except AttributeError: diff --git a/src/sage/plot/circle.py b/src/sage/plot/circle.py index 512080a6ed8..41281b66735 100644 --- a/src/sage/plot/circle.py +++ b/src/sage/plot/circle.py @@ -133,7 +133,7 @@ def _repr_(self): sage: c = C[0]; c Circle defined by (2.0,3.0) with r=5.0 """ - return "Circle defined by (%s,%s) with r=%s"%(self.x, self.y, self.r) + return "Circle defined by (%s,%s) with r=%s" % (self.x, self.y, self.r) def _render_on_subplot(self, subplot): """ @@ -148,7 +148,7 @@ def _render_on_subplot(self, subplot): options = self.options() p = patches.Circle((float(self.x), float(self.y)), float(self.r), clip_on=options['clip']) if not options['clip']: - self._bbox_extra_artists=[p] + self._bbox_extra_artists = [p] p.set_linewidth(float(options['thickness'])) p.set_fill(options['fill']) a = float(options['alpha']) diff --git a/src/sage/plot/density_plot.py b/src/sage/plot/density_plot.py index b9f993239d0..8d6123ff226 100644 --- a/src/sage/plot/density_plot.py +++ b/src/sage/plot/density_plot.py @@ -127,7 +127,7 @@ def _repr_(self): sage: d = D[0]; d DensityPlot defined by a 25 x 25 data grid """ - return "DensityPlot defined by a %s x %s data grid"%(self.xy_array_row, self.xy_array_col) + return "DensityPlot defined by a %s x %s data grid" % (self.xy_array_row, self.xy_array_col) def _render_on_subplot(self, subplot): """ diff --git a/src/sage/plot/ellipse.py b/src/sage/plot/ellipse.py index 6d99cc90401..791b719fe68 100644 --- a/src/sage/plot/ellipse.py +++ b/src/sage/plot/ellipse.py @@ -170,7 +170,7 @@ def _repr_(self): sage: Ellipse(0,0,2,1,0,{})._repr_() 'Ellipse centered at (0.0, 0.0) with radii (2.0, 1.0) and angle 0.0' """ - return "Ellipse centered at (%s, %s) with radii (%s, %s) and angle %s"%(self.x, self.y, self.r1, self.r2, self.angle) + return "Ellipse centered at (%s, %s) with radii (%s, %s) and angle %s" % (self.x, self.y, self.r1, self.r2, self.angle) def _render_on_subplot(self, subplot): """ @@ -362,7 +362,7 @@ def ellipse(center, r1, r2, angle=0, **options): if options['legend_label']: g.legend(True) g._legend_colors = [options['legend_color']] - if len(center)==2: + if len(center) == 2: return g - elif len(center)==3: + elif len(center) == 3: raise NotImplementedError("plotting ellipse in 3D is not implemented") diff --git a/src/sage/plot/hyperbolic_regular_polygon.py b/src/sage/plot/hyperbolic_regular_polygon.py index a20d7d5a002..9be2169ab63 100644 --- a/src/sage/plot/hyperbolic_regular_polygon.py +++ b/src/sage/plot/hyperbolic_regular_polygon.py @@ -110,14 +110,14 @@ def __init__(self, sides, i_angle, center, options): """ self.center = CC(center) if self.center.imag() <= 0: - raise ValueError("center: %s is not a valid point in the upper half plane model of the hyperbolic plane"%(self.center)) + raise ValueError("center: %s is not a valid point in the upper half plane model of the hyperbolic plane" % (self.center)) if sides < 3: raise ValueError("degenerated polygons (sides<=2) are not supported") if i_angle <= 0 or i_angle >= pi: - raise ValueError("interior angle %s must be in (0, pi) interval"%(i_angle)) + raise ValueError("interior angle %s must be in (0, pi) interval" % (i_angle)) if pi*(sides-2) - sides*i_angle <= 0: raise ValueError("there exists no hyperbolic regular compact polygon," - " for sides=%s the interior angle must be less than %s"%(sides, pi * (sides-2) / sides)) + " for sides=%s the interior angle must be less than %s" % (sides, pi * (sides-2) / sides)) self.sides = sides self.i_angle = i_angle beta = 2 * pi / self.sides # compute the rotation angle to be used ahead @@ -151,7 +151,7 @@ def __init__(self, sides, i_angle, center, options): new_z_k = self._i_rotation(z_k[-1], beta).n(digits=8) z_k = z_k + [new_z_k] d_z_k = d_z_k + [new_z_k * scale + h_disp] - r_z_k=[-(new_z_k).conjugate() * scale + h_disp] + r_z_k + r_z_k = [-(new_z_k).conjugate() * scale + h_disp] + r_z_k if is_odd(self.sides): HyperbolicPolygon.__init__(self, d_z_k + r_z_k, "UHP", options) else: diff --git a/src/sage/plot/matrix_plot.py b/src/sage/plot/matrix_plot.py index d34bd473829..f113f5aaa62 100644 --- a/src/sage/plot/matrix_plot.py +++ b/src/sage/plot/matrix_plot.py @@ -121,9 +121,9 @@ def get_minmax_data(self): # for example, the square representing the (0,0) entry is centered on # the origin. if not xrange: - xrange = (-.5, self.xy_array_col -.5) + xrange = (-.5, self.xy_array_col - .5) if not yrange: - yrange = (-.5, self.xy_array_row -.5) + yrange = (-.5, self.xy_array_row - .5) return minmax_data(xrange, yrange, dict=True) def _allowed_options(self): @@ -162,7 +162,7 @@ def _repr_(self): sage: m = M[0]; m # needs sage.symbolic MatrixPlot defined by a 5 x 5 data grid """ - return "MatrixPlot defined by a %s x %s data grid"%(self.xy_array_row, self.xy_array_col) + return "MatrixPlot defined by a %s x %s data grid" % (self.xy_array_row, self.xy_array_col) def _render_on_subplot(self, subplot): """ @@ -175,29 +175,29 @@ def _render_on_subplot(self, subplot): cmap = get_cmap(options.pop('cmap',None)) flip_y = options['flip_y'] - norm=options['norm'] + norm = options['norm'] - if norm=='value': + if norm == 'value': import matplotlib - norm=matplotlib.colors.NoNorm() + norm = matplotlib.colors.NoNorm() - lim=self.get_minmax_data() + lim = self.get_minmax_data() if options['subdivisions']: - subdiv_options=options['subdivision_options'] + subdiv_options = options['subdivision_options'] if isinstance(subdiv_options['boundaries'], (list, tuple)): - rowsub,colsub=subdiv_options['boundaries'] + rowsub,colsub = subdiv_options['boundaries'] else: - rowsub=subdiv_options['boundaries'] - colsub=subdiv_options['boundaries'] + rowsub = subdiv_options['boundaries'] + colsub = subdiv_options['boundaries'] if isinstance(subdiv_options['style'], (list, tuple)): - rowstyle,colstyle=subdiv_options['style'] + rowstyle,colstyle = subdiv_options['style'] else: - rowstyle=subdiv_options['style'] - colstyle=subdiv_options['style'] + rowstyle = subdiv_options['style'] + colstyle = subdiv_options['style'] if rowstyle is None: - rowstyle=dict() + rowstyle = dict() if colstyle is None: - colstyle=dict() + colstyle = dict() # Make line objects for subdivisions from .line import line2d @@ -215,7 +215,7 @@ def _render_on_subplot(self, subplot): if hasattr(self.xy_data_array, 'tocoo'): # Sparse matrix -- use spy - opts=options.copy() + opts = options.copy() for opt in ['vmin', 'vmax', 'norm', 'flip_y', 'subdivisions', 'subdivision_options', 'colorbar', 'colorbar_options']: del opts[opt] @@ -233,7 +233,7 @@ def _render_on_subplot(self, subplot): if options.get('colorbar', False): colorbar_options = options['colorbar_options'] from matplotlib import colorbar - cax,kwds=colorbar.make_axes_gridspec(subplot,**colorbar_options) + cax,kwds = colorbar.make_axes_gridspec(subplot,**colorbar_options) colorbar.Colorbar(cax, image, **kwds) if flip_y: @@ -569,7 +569,7 @@ def matrix_plot(mat, xrange=None, yrange=None, **options): from sage.plot.all import Graphics from sage.structure.element import is_Matrix from sage.rings.real_double import RDF - orig_mat=mat + orig_mat = mat if is_Matrix(mat): sparse = mat.is_sparse() if sparse: @@ -612,7 +612,7 @@ def matrix_plot(mat, xrange=None, yrange=None, **options): yrange = tuple(float(v) for v in yrange) if options['subdivisions'] and options['subdivision_options']['boundaries'] is None: - options['subdivision_options']['boundaries']=orig_mat.get_subdivisions() + options['subdivision_options']['boundaries'] = orig_mat.get_subdivisions() # Custom position the title. Otherwise it overlaps with tick labels if options['flip_y'] and 'title_pos' not in options: diff --git a/src/sage/plot/misc.py b/src/sage/plot/misc.py index 72ee2c049b0..fa06484c4cf 100644 --- a/src/sage/plot/misc.py +++ b/src/sage/plot/misc.py @@ -259,8 +259,8 @@ def unify_arguments(funcs): sage: sage.plot.misc.unify_arguments((x+y,x-y)) ((x, y), (x, y)) """ - vars=set() - free_variables=set() + vars = set() + free_variables = set() if not isinstance(funcs, (list, tuple)): funcs = [funcs] @@ -317,7 +317,7 @@ def _multiple_of_constant(n, pos, const): k = 1 while cf.quotient(k) != Infinity and cf.denominator(k) < 12: k += 1 - return '$%s$'%latex(cf.convergent(k-1)*const) + return '$%s$' % latex(cf.convergent(k-1)*const) def get_matplotlib_linestyle(linestyle, return_type): @@ -404,9 +404,9 @@ def get_matplotlib_linestyle(linestyle, return_type): '--', ':', '-.', ''} """ - long_to_short_dict={'solid' : '-','dashed' : '--', 'dotted' : ':', + long_to_short_dict = {'solid' : '-','dashed' : '--', 'dotted' : ':', 'dashdot':'-.'} - short_to_long_dict={'-' : 'solid','--' : 'dashed', ':' : 'dotted', + short_to_long_dict = {'-' : 'solid','--' : 'dashed', ':' : 'dotted', '-.':'dashdot'} # We need this to take care of region plot. Essentially, if None is @@ -441,7 +441,7 @@ def get_matplotlib_linestyle(linestyle, return_type): raise ValueError("WARNING: Unrecognized linestyle '%s'. " "Possible linestyle options are:\n{'solid', " "'dashed', 'dotted', dashdot', 'None'}, " - "respectively {'-', '--', ':', '-.', ''}"% + "respectively {'-', '--', ':', '-.', ''}" % (linestyle)) elif return_type == 'long': @@ -455,7 +455,7 @@ def get_matplotlib_linestyle(linestyle, return_type): raise ValueError("WARNING: Unrecognized linestyle '%s'. " "Possible linestyle options are:\n{'solid', " "'dashed', 'dotted', dashdot', 'None'}, " - "respectively {'-', '--', ':', '-.', ''}"% + "respectively {'-', '--', ':', '-.', ''}" % (linestyle)) diff --git a/src/sage/plot/plot.py b/src/sage/plot/plot.py index 69e78f16ab4..b614b2ef3db 100644 --- a/src/sage/plot/plot.py +++ b/src/sage/plot/plot.py @@ -736,8 +736,8 @@ def __init__(self, formatter, skip_values): sage: with NamedTemporaryFile(suffix=".png") as f: ....: fig.savefig(f.name) """ - self.formatter=formatter - self.skip_values=skip_values + self.formatter = formatter + self.skip_values = skip_values def set_locs(self, locs): """ @@ -2175,7 +2175,7 @@ def _plot(funcs, xrange, parametric=False, options['plot_points'], imaginary_tolerance=imag_tol) xmin, xmax, delta = ranges[0] - xrange=ranges[0][:2] + xrange = ranges[0][:2] # parametric_plot will be a list or tuple of two functions (f,g) # and will plotted as (f(x), g(x)) for all x in the given range if parametric: @@ -2314,7 +2314,7 @@ def golden_rainbow(i,lightness=0.4): if i < len(legend_color_temp): legend_color_entry = legend_color_temp[i] elif legend_color_temp == 'automatic': - if len(funcs)>1: + if len(funcs) > 1: legend_color_entry = golden_rainbow(i) elif legend_color_temp is not None: legend_color_entry = legend_color_temp @@ -2858,7 +2858,7 @@ def polar_plot(funcs, *args, **kwds): sphinx_plot(g) """ - kwds['polar']=True + kwds['polar'] = True return plot(funcs, *args, **kwds) @options(aspect_ratio='automatic') @@ -3903,14 +3903,14 @@ def adaptive_refinement(f, p1, p2, adaptive_tolerance=0.01, try: y = float(f(x)) if str(y) in ['nan', 'NaN', 'inf', '-inf']: - sage.misc.verbose.verbose("%s\nUnable to compute f(%s)"%(msg, x),1) + sage.misc.verbose.verbose("%s\nUnable to compute f(%s)" % (msg, x),1) # give up for this branch if excluded: return [(x, 'NaN')] return [] except (ZeroDivisionError, TypeError, ValueError, OverflowError) as msg: - sage.misc.verbose.verbose("%s\nUnable to compute f(%s)"%(msg, x), 1) + sage.misc.verbose.verbose("%s\nUnable to compute f(%s)" % (msg, x), 1) # give up for this branch if excluded: return [(x, 'NaN')] diff --git a/src/sage/plot/plot_field.py b/src/sage/plot/plot_field.py index 28d509fe156..9b2746c5a27 100644 --- a/src/sage/plot/plot_field.py +++ b/src/sage/plot/plot_field.py @@ -139,7 +139,7 @@ def _repr_(self): 20 """ - return "PlotField defined by a %s x %s vector grid"%( + return "PlotField defined by a %s x %s vector grid" % ( self._options['plot_points'], self._options['plot_points']) def _render_on_subplot(self, subplot): From 31e6f0463ce2a51adf9556c82c56db55c50106f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Mon, 11 Sep 2023 18:02:39 +0200 Subject: [PATCH 2/2] a bit more in plot and modules --- src/sage/modules/fg_pid/fgp_element.py | 2 +- src/sage/modules/fg_pid/fgp_morphism.py | 2 +- src/sage/modules/with_basis/morphism.py | 12 ++++++------ src/sage/plot/plot3d/plot3d.py | 10 +++++----- src/sage/plot/plot3d/tri_plot.py | 4 ++-- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/sage/modules/fg_pid/fgp_element.py b/src/sage/modules/fg_pid/fgp_element.py index 0a0f435d779..dbb13dadbad 100644 --- a/src/sage/modules/fg_pid/fgp_element.py +++ b/src/sage/modules/fg_pid/fgp_element.py @@ -21,7 +21,7 @@ # This adds extra maybe-not-necessary checks in the code, but could # slow things down. It can impact what happens in more than just this # file. -DEBUG=True +DEBUG = True class FGP_Element(ModuleElement): diff --git a/src/sage/modules/fg_pid/fgp_morphism.py b/src/sage/modules/fg_pid/fgp_morphism.py index 809bb439f0c..d1c8b221994 100644 --- a/src/sage/modules/fg_pid/fgp_morphism.py +++ b/src/sage/modules/fg_pid/fgp_morphism.py @@ -127,7 +127,7 @@ def _repr_(self): sage: phi._repr_() 'Morphism from module over Integer Ring with invariants (4, 12) to module with invariants (4, 12) that sends the generators to [(1, 3), (0, 11)]' """ - return "Morphism from module over %s with invariants %s to module with invariants %s that sends the generators to %s"%( + return "Morphism from module over %s with invariants %s to module with invariants %s that sends the generators to %s" % ( self.domain().base_ring(), self.domain().invariants(), self.codomain().invariants(), list(self.im_gens())) diff --git a/src/sage/modules/with_basis/morphism.py b/src/sage/modules/with_basis/morphism.py index d6b4586ce83..b94629a8dfe 100644 --- a/src/sage/modules/with_basis/morphism.py +++ b/src/sage/modules/with_basis/morphism.py @@ -691,9 +691,9 @@ def __init__(self, triangular="upper", unitriangular=False, self._inverse_on_support = inverse_on_support if invertible is None and (domain.basis().keys() == codomain.basis().keys()) and \ - (self._inverse_on_support==identity or domain in Modules.FiniteDimensional): + (self._inverse_on_support == identity or domain in Modules.FiniteDimensional): invertible = True - self._invertible=invertible + self._invertible = invertible def _richcmp_(self, other, op): r""" @@ -772,10 +772,10 @@ def _test_triangular(self, **options): bs, co = self._dominant_item(on_basis(x)) if self._unitriangular: tester.assertEqual(co, self.domain().base_ring().one(), - LazyFormat("morphism is not unitriangular on %s")%(x)) + LazyFormat("morphism is not unitriangular on %s") % (x)) xback = self._inverse_on_support(bs) tester.assertEqual(x, xback, - LazyFormat("morphism is not triangular on %s")%(x)) + LazyFormat("morphism is not triangular on %s") % (x)) def __invert__(self): """ @@ -1452,12 +1452,12 @@ def __init__(self, domain, diagonal, codomain=None, category=None): "and the same basis indexing") from collections.abc import Callable if not isinstance(diagonal, Callable): - raise ValueError("diagonal (=%s) should be a function"%diagonal) + raise ValueError("diagonal (=%s) should be a function" % diagonal) if category is None: category = ModulesWithBasis(domain.base_ring()) ModuleMorphismByLinearity.__init__( self, domain=domain, codomain=codomain, category=category) - self._diagonal=diagonal + self._diagonal = diagonal def _richcmp_(self, other, op): r""" diff --git a/src/sage/plot/plot3d/plot3d.py b/src/sage/plot/plot3d/plot3d.py index 2d2bfb9e34d..5687c6f9c8c 100644 --- a/src/sage/plot/plot3d/plot3d.py +++ b/src/sage/plot/plot3d/plot3d.py @@ -263,7 +263,7 @@ def __init__(self, dep_var, indep_vars): """ all_vars = sage_getargspec(self.transform).args[1:] if set(all_vars) != set(indep_vars + [dep_var]): - raise ValueError('variables were specified incorrectly for this coordinate system; incorrect variables were %s'%list(set(all_vars).symmetric_difference(set(indep_vars+[dep_var])))) + raise ValueError('variables were specified incorrectly for this coordinate system; incorrect variables were %s' % list(set(all_vars).symmetric_difference(set(indep_vars+[dep_var])))) self.dep_var = dep_var self.indep_vars = indep_vars @@ -1372,11 +1372,11 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): from sage.modules.vector_callable_symbolic_dense import Vector_callable_symbolic_dense if isinstance(transformation, (tuple, list,Vector_callable_symbolic_dense)): - if len(transformation)==3: + if len(transformation) == 3: if params is None: raise ValueError("must specify independent variable names in the ranges when using generic transformation") indep_vars = params - elif len(transformation)==4: + elif len(transformation) == 4: indep_vars = transformation[3] transformation = transformation[0:3] else: @@ -1384,8 +1384,8 @@ def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): # find out which variable is the function variable by # eliminating the parameter variables. all_vars = set(sum([list(s.variables()) for s in transformation],[])) - dep_var=all_vars - set(indep_vars) - if len(dep_var)==1: + dep_var = all_vars - set(indep_vars) + if len(dep_var) == 1: dep_var = dep_var.pop() transformation = _ArbitraryCoordinates(transformation, dep_var, indep_vars) else: diff --git a/src/sage/plot/plot3d/tri_plot.py b/src/sage/plot/plot3d/tri_plot.py index 0841f9dc730..da719020117 100644 --- a/src/sage/plot/plot3d/tri_plot.py +++ b/src/sage/plot/plot3d/tri_plot.py @@ -64,7 +64,7 @@ class of the form sage: print(tri.str()) [0, 0, 0] [-1, 2, 3] [0, 2, 0] 0 """ - return "%s %s %s %s"%(self._a, self._b, self._c, self._color) + return "%s %s %s %s" % (self._a, self._b, self._c, self._color) def set_color(self, color): """ @@ -135,7 +135,7 @@ def str(self): sage: print(t.str()) [1, 2, 3] [2, 3, 4] [0, 0, 0] 0 [0, 0, 1] [0, 1, 0] [1, 0, 0] """ - return "%s %s %s %s %s %s %s"%(self._a, self._b, self._c, self._color, self._da, self._db, self._dc) + return "%s %s %s %s %s %s %s" % (self._a, self._b, self._c, self._color, self._da, self._db, self._dc) def get_normals(self): """