rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def onSeekEditorButtonResponse (self, dialog, response):
def onEditSeekDialogResponse (self, dialog, response):
def onSeekEditorButtonResponse (self, dialog, response): self.widgets["editSeekDialog"].hide() if response != gtk.RESPONSE_OK: return self.__saveSeekEditor(self.seeknumber) self.__writeSavedSeeks(self.seeknumber)
"myname": "PyChess %s" % VERSION
"myname": "PyChess %s" % pychess.VERSION
def __init__ (self): PyChess.__init__(self) self.board = LBoard(NORMALCHESS) self.board.applyFen(FEN_START) self.forced = False self.analyzing = False self.worker = None self.features = { "setboard": 1, "analyze": 1, "usermove": 1, "reuse": 0, "draw": 1, "sigterm": 1, "variants": "normal,nocastle,fischerandom", "myna...
"PyChess is the chess engine bundled with the PyChess %s " % VERSION +
"PyChess is the chess engine bundled with the PyChess %s " % pychess.VERSION +
def makeReady(self): PyChess.makeReady(self) self.connection = FICSConnection("freechess.org",self.ports, self.username, self.password) self.connection.connect("connectingMsg", self.__showConnectLog) self.connection._connect() self.connection.glm.connect("addPlayer", self.__onAddPlayer) self.connection.glm.connect("r...
oldstyle = self.get_style() self.set_style(tooltipStyle) tooltipStyle.paint_flat_box (self.window, gtk.STATE_NORMAL, gtk.SHADOW_NONE, None, tooltip, "tooltip",
self.get_style().paint_flat_box (self.window, gtk.STATE_NORMAL, gtk.SHADOW_NONE, r, self, "tooltip",
def draw (self, context, r): alloc = self.get_allocation() width = alloc.width height = alloc.height #------------------------------------------------------ Paint side ruler context.move_to(alloc.x+line, alloc.y+line) context.rel_line_to(0, height-line*2-curve) context.rel_curve_to(0, curve, 0, curve, curve, curve) ...
self.set_style(oldstyle)
def draw (self, context, r): alloc = self.get_allocation() width = alloc.width height = alloc.height #------------------------------------------------------ Paint side ruler context.move_to(alloc.x+line, alloc.y+line) context.rel_line_to(0, height-line*2-curve) context.rel_curve_to(0, curve, 0, curve, curve, curve) ...
context.set_source_color(tooltipStyle.fg[self.state])
context.set_source_color(self.get_style().fg[self.state])
def draw (self, context, r): alloc = self.get_allocation() width = alloc.width height = alloc.height #------------------------------------------------------ Paint side ruler context.move_to(alloc.x+line, alloc.y+line) context.rel_line_to(0, height-line*2-curve) context.rel_curve_to(0, curve, 0, curve, curve, curve) ...
self.widgets["challengeExpander"].set_sensitive(False)
def onPlayingGame (self): self.widgets["seekListContent"].set_sensitive(False) self.widgets["challengeExpander"].set_sensitive(False) self.widgets["clearSeeksButton"].set_sensitive(False) self.store.clear() self.__updateActiveSeeksLabel()
self.widgets["challengeExpander"].set_sensitive(True)
def onCurGameEnded (self): self.widgets["seekListContent"].set_sensitive(True) self.widgets["challengeExpander"].set_sensitive(True) self.connection.glm.refreshSeeks()
if "C" in player["titles"]:
adminicon = load_icon(size, "stock_book_blue", "accessories-dictionary") if "U" in player["titles"]: icon = guesticon elif "C" in player["titles"]:
def __getPlayerIcon (cls, player, size=15): assert type(size) == int, "size not an int: %s" % str(size) computericon = load_icon(size, "stock_notebook", "computer") guesticon = load_icon(size, "stock_people", "system-users") if "C" in player["titles"]: icon = computericon elif "U" in player["titles"]: icon = guesticon...
elif "U" in player["titles"]: icon = guesticon
elif "*" in player["titles"]: icon = adminicon
def __getPlayerIcon (cls, player, size=15): assert type(size) == int, "size not an int: %s" % str(size) computericon = load_icon(size, "stock_notebook", "computer") guesticon = load_icon(size, "stock_people", "system-users") if "C" in player["titles"]: icon = computericon elif "U" in player["titles"]: icon = guesticon...
if worker.cancelled: return
if not result: return
def ondone (worker, result): if worker.cancelled: return self.board.applyMove(parseSAN(self.board,result)) print "move %s" % result
print "Warning: Releasing nonowned glock has no effect"
print "Warning: Releasing nonowned glock has no effect\n" + \ "Traceback was: %s" % traceback.extract_stack()
def release(): me = currentThread() # As it is the natural state for the MainThread to control the gdklock, we # only release it if _rlock has been released so many times that we don't # own it any more if me.getName() == "MainThread": if _rlock._RLock__owner != me: threads_leave() else: _rlock.release() # If this is t...
moves = listToMoves (self.board, mvstrs, type=None, validate=True, ignoreErrors=False)
try: moves = listToMoves (self.board, mvstrs, type=None, validate=True, ignoreErrors=False) except ParsingError, e: log.debug("Ignored line from analyzer due to error: %s" % e, repr(self)) return
def __parseLine (self, line): parts = whitespaces.split(line.strip()) if parts[0] == "pong": self.lastpong = int(parts[1]) return # Illegal Move if parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): print >> self.engine, "depth", parts[-1] return # A Move (Perhaps) if self.board: if...
newclamp = self.__clamp(rating) difference = newclamp - center if self.chainbox.active and difference is not self.lastdifference: newsliderval = (newclamp - self.lastdifference) / RATING_SLIDER_STEP self.widgets["ratingCenterSlider"].set_value(newsliderval)
rating = self.__clamp(rating) difference = rating - center if self.loading_seek_editor is False and self.chainbox.active and \ difference is not self.lastdifference: newcenter = rating - self.lastdifference self.widgets["ratingCenterSlider"].set_value(newcenter / RATING_SLIDER_STEP)
def __updateYourRatingHBox (self): if self.finger == None: return gametype, ratingtype = self.__getGameTypes() self.widgets["yourRatingNameLabel"].set_label("(" + gametype + ")") try: rating = self.finger.getRating(type=ratingtype) except KeyError: # the user doesn't have a rating for this game type self.widgets["you...
return " (" + s + ", ".join(panels) + ")"
return s + " (" + ", ".join(panels) + ")"
def __repr__ (self): s = DockLeaf.__repr__(self) panels = [] for widget, title, id in self.getPanels(): panels.append(id) return " (" + s + ", ".join(panels) + ")"
else: flag = NORMAL_MOVE
def parseAN (board, an): """ Parse an Algebraic Notation string """ if not 4 <= len(an) <= 6: raise ParsingError, (an, "the move must be 4 or 6 chars long", board.asFen()) try: fcord = cordDic[an[:2]] tcord = cordDic[an[2:4]] except KeyError, e: raise ParsingError, (an, "the cord (%s) is incorrect" % e.args[0], board...
but view.shown and BoardControl.lockedPly haven't been yet been updated """
but view.shown and BoardControl.lockedPly haven't been updated yet """
def isAPotentiallyLegalNextMove (self, cord0, cord1): """ Determines whether the given move is at all legally possible as the next move after the player who's turn it is makes their move Note: This doesn't always return the correct value, such as when BoardControl.setLocked() has been called and we've begun a drag, but...
'cp':False, 'rt':'1291', 'manual':False,
'cp':False, 'rt':'1291', 'manual':False, 'title': '',
def test1 (self): """ Seek add """ signal = 'addSeek' lines = ['<s> 10 w=warbly ti=00 rt=1291 t=3 i=0 r=r tp=blitz c=? rr=1200-1400 a=t f=t'] expectedResult = {'gameno':'10', 'tp':_("Blitz"), 'rmin':'1200', 'rmax':'1400', 'cp':False, 'rt':'1291', 'manual':False, 'w':'warbly', 'r':'r', 't':'3', 'i':'0'} self.runAndAs...
'cp':True, 'rt':'1637', 'manual':False,
'cp':True, 'rt':'1637', 'manual':False, 'title': '(C)',
def test1 (self): """ Seek add """ signal = 'addSeek' lines = ['<s> 10 w=warbly ti=00 rt=1291 t=3 i=0 r=r tp=blitz c=? rr=1200-1400 a=t f=t'] expectedResult = {'gameno':'10', 'tp':_("Blitz"), 'rmin':'1200', 'rmax':'1400', 'cp':False, 'rt':'1291', 'manual':False, 'w':'warbly', 'r':'r', 't':'3', 'i':'0'} self.runAndAs...
'cp':False, 'rt':'1294', 'manual':True,
'cp':False, 'rt':'1294', 'manual':True, 'title': '',
def test1 (self): """ Seek add """ signal = 'addSeek' lines = ['<s> 10 w=warbly ti=00 rt=1291 t=3 i=0 r=r tp=blitz c=? rr=1200-1400 a=t f=t'] expectedResult = {'gameno':'10', 'tp':_("Blitz"), 'rmin':'1200', 'rmax':'1400', 'cp':False, 'rt':'1291', 'manual':False, 'w':'warbly', 'r':'r', 't':'3', 'i':'0'} self.runAndAs...
x= gamemodel.tags["Round"] print x, type(x)
def accept_new_properties(button, *args): gamemodel = gameDic[gamewidget.cur_gmwidg()] gamemodel.tags["Event"] = widgets["event_entry"].get_text() gamemodel.tags["Site"] = widgets["site_entry"].get_text() gamemodel.tags["Round"] = int(widgets["round_spinbutton"].get_value()) x= gamemodel.tags["Round"] print x, type(x) ...
self.lvm.setVariable("interface", NAME+" "+VERSION)
self.lvm.setVariable("interface", NAME+" "+pychess.VERSION)
def _connect (self): self.connecting = True self.emit("connecting") try: self.client = TimeSeal() self.emit('connectingMsg', _("Connecting to server")) for i, port in enumerate(self.ports): log.debug("Trying port %d\n" % port, (self.host, "raw")) try: self.client.open(self.host, port) except socket.error, e: if e.args...
return self.players[self.getBoardAtPly(self.ply).color]
try: return self.players[self.getBoardAtPly(self.ply).color] except IndexError: log.error("%s %s" % (self.players, self.getBoardAtPly(self.ply).color)) raise
def _get_curplayer (self): return self.players[self.getBoardAtPly(self.ply).color]
errstr1 = _("The game can't be read to end, because of an error parsing move %s '%s'.") % (moveno, notation)
errstr1 = _("The game can't be read to end, because of an error parsing move %(moveno)s '%(notation)s'.") % { 'moveno': moveno, 'notation': notation}
def parse_string(string, model, board, position, parent=None, variation=False): boards = [] board = board.clone() board.parent = parent last_board = board boards.append(board) error = None parenthesis = 0 v_string = "" for i, m in enumerate(re.finditer(pattern, string)): group, text = m.lastindex, m.group(m.lastindex...
if self.variant == FISCHERRANDOMCHESS: if r == 0: rank8 = rank elif r == 7: rank1 = rank
def applyFen (self, fenstr): """ Applies the fenstring to the board. If the string is not properly written a SyntaxError will be raised, having its message ending in Pos(%d) specifying the string index of the problem. if an error is found, no changes will be made to the board. """ # Get information parts = fenstr.spl...
elif move.flag == KING_CASTLE:
else:
def paintBoxAround(self, move): paintBox = self.cord2RectRelative(move.cord0) paintBox = join(paintBox, self.cord2RectRelative(move.cord1)) if move.flag in (KING_CASTLE, QUEEN_CASTLE): y = move.cord0.cy color = (y == 1) rsqs = self.model.boards[-1].board.ini_rooks[color] if move.flag == KING_CASTLE: paintBox = join(pai...
if (wn, wb, wr, 0, bn, wb, wr, 0) in drawSet:
if (wn, wb, wr, 0, bn, bb, br, 0) in drawSet:
def testMaterial (board): """ Tests if no players are able to win the game from the current position """ whiteBoards = board.boards[WHITE] blackBoards = board.boards[BLACK] if bitLength(whiteBoards[PAWN]) or bitLength(blackBoards[PAWN]): return False if bitLength(whiteBoards[QUEEN]) or bitLength(blackBoards[QUEEN]):...
color = board.color
def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) elif len(san) < 2: raise ParsingError, (san, _("the move is too short"), board.asFen()) notat = san color = board.color if notat[-1] in ("+", "#...
if color == WHITE:
if board.color == WHITE:
def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) elif len(san) < 2: raise ParsingError, (san, _("the move is too short"), board.asFen()) notat = san color = board.color if notat[-1] in ("+", "#...
tcord = G1
if board.variant == FISCHERRANDOMCHESS: tcord = board.ini_rooks[0][1] else: tcord = G1
def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) elif len(san) < 2: raise ParsingError, (san, _("the move is too short"), board.asFen()) notat = san color = board.color if notat[-1] in ("+", "#...
tcord = C1
if board.variant == FISCHERRANDOMCHESS: tcord = board.ini_rooks[0][0] else: tcord = C1
def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) elif len(san) < 2: raise ParsingError, (san, _("the move is too short"), board.asFen()) notat = san color = board.color if notat[-1] in ("+", "#...
tcord = G8
if board.variant == FISCHERRANDOMCHESS: tcord = board.ini_rooks[1][1] else: tcord = G8
def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) elif len(san) < 2: raise ParsingError, (san, _("the move is too short"), board.asFen()) notat = san color = board.color if notat[-1] in ("+", "#...
tcord = C8
if board.variant == FISCHERRANDOMCHESS: tcord = board.ini_rooks[1][0] else: tcord = C8
def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) elif len(san) < 2: raise ParsingError, (san, _("the move is too short"), board.asFen()) notat = san color = board.color if notat[-1] in ("+", "#...
self.widgets["acceptButton"].connect("clicked", self.onAccept) self.tv.connect("row-activated", self.onAccept)
self.widgets["acceptButton"].connect("clicked", self.onAcceptClicked) self.tv.connect("row-activated", self.row_activated)
def __init__ (self, widgets, connection): ParrentListSection.__init__(self)
def onAccept (self, treeview, path, view_column):
def onAcceptClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return gameno = model.get_value(iter, 0) if gameno.startswith("C"): self.connection.om.acceptIndex(gameno[1:]) else: self.connection.om.playIndex(gameno) def row_activated (self, treeview, path, view_column):
def onAccept (self, treeview, path, view_column): model, iter = self.tv.get_selection().get_selected() if iter == None: return gameno = model.get_value(iter, 0) if gameno != self.lastSeekSelected: return if path != model.get_path(iter): return if gameno.startswith("C"): self.connection.om.acceptIndex(gameno[1:]) else: ...
if gameno.startswith("C"): self.connection.om.acceptIndex(gameno[1:]) else: self.connection.om.playIndex(gameno)
self.onAcceptClicked(None)
def onAccept (self, treeview, path, view_column): model, iter = self.tv.get_selection().get_selected() if iter == None: return gameno = model.get_value(iter, 0) if gameno != self.lastSeekSelected: return if path != model.get_path(iter): return if gameno.startswith("C"): self.connection.om.acceptIndex(gameno[1:]) else: ...
if not engine: engine = anaengines[0]
if engine == None: engine = anaengines[0]
def workfunc (worker, gamemodel, player0tup, player1tup, loaddata=None): log.debug("ionest.workfunc: %s\n %s\n %s\n" % (gamemodel, player0tup, player1tup)) gmwidg = gamewidget.GameWidget(gamemodel) player0 = {} player1 = {} for player, playertup in ((player0, player0tup), (player1, player1tup)): player["name"] = playe...
print "sel changed. updating shown"
def on_selection_changed (self, selection, tree, col): iter = selection.get_selected()[1] if iter == None: return if self.frozen.on: return print "sel changed. updating shown" row = tree.get_model().get_path(iter)[0] if self.board.model.lowply & 1: self.board.shown = self.board.model.lowply + row*2 + col else: self.boa...
print "Am I doing anything?"
def __addMove(self, game, ply): print "Am I doing anything?" row, view, other = self._ply_to_row_col_other(ply) if conf.get("figuresInNotation", False): notat = toFAN(game.getBoardAtPly(ply-1), game.getMoveAtPly(ply-1)) else: notat = toSAN(game.getBoardAtPly(ply-1), game.getMoveAtPly(ply-1), localRepr=True) # Test if...
print "Or is it me?"
def shown_changed (self, board, shown): if shown <= board.model.lowply: print "Or is it me?" self.left.get_selection().unselect_all() self.right.get_selection().unselect_all() return print "shown changed", shown row, col, other = self._ply_to_row_col_other(shown) with self.frozen: other.get_selection().unselect_all() ...
print "shown changed", shown
def shown_changed (self, board, shown): if shown <= board.model.lowply: print "Or is it me?" self.left.get_selection().unselect_all() self.right.get_selection().unselect_all() return print "shown changed", shown row, col, other = self._ply_to_row_col_other(shown) with self.frozen: other.get_selection().unselect_all() ...
ChallengeTabSection(w,c),
def on_autoLogout (alm): self.close() self.emit("autoLogout")
count = len(self.seeks) self.widgets["activeSeeksLabel"].set_text(_("Active seeks: %d") % count)
self.__updateActiveSeeksLabel()
def onAddSeek (self, seek): time = _("%(min)s min") % {'min': seek["t"]} if seek["i"] != "0": time += _(" + %(sec)s sec") % {'sec': seek["i"]} rated = seek["r"] == "u" and _("Unrated") or _("Rated") pix = seek["manual"] and self.manSeekPix or self.seekPix textcolor = "grey" if seek["w"] == self.connection.getUsername()...
count = len(self.seeks) self.widgets["activeSeeksLabel"].set_text(_("Active seeks: %d") % count) def onClearSeeks (self): self.store.clear() self.seeks = {} self.widgets["activeSeeksLabel"].set_text(_("Active seeks: 0")) def onAcceptClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter ...
self.__updateActiveSeeksLabel()
def onRemoveSeek (self, gameno): if not gameno in self.seeks: # We ignore removes we haven't added, as it seams fics sends a # lot of removes for games it has never told us about return treeiter = self.seeks [gameno] if not self.store.iter_is_valid(treeiter): return self.store.remove (treeiter) del self.seeks[gameno] c...
self.challenges [index] = ti count = int(self.widgets["activeSeeksLabel"].get_text().split()[0])+1 self.widgets["activeSeeksLabel"].set_text(_("Active seeks: %d") % count)
self.challenges[index] = ti self.__updateActiveSeeksLabel()
def onChallengeAdd (self, index, match): time = _("%(min)s min") % {'min': match["t"]} if match["i"] != "0": time += _(" + %(sec)s sec") % {'sec': match["i"]} rated = match["r"] == "u" and _("Unrated") or _("Rated") ti = self.store.prepend (["C"+index, self.chaPix, match["w"], int(match["rt"]), rated, match["tp"], time...
self.store.remove (ti) del self.challenges [index] count = int(self.widgets["activeSeeksLabel"].get_text().split()[0])-1 self.widgets["activeSeeksLabel"].set_text(_("Active seeks: %d") % count)
self.store.remove(ti) del self.challenges[index] self.__updateActiveSeeksLabel() def onClearSeeks (self): self.store.clear() self.seeks = {} self.__updateActiveSeeksLabel() def onAcceptClicked (self, button): model, iter = self.tv.get_selection().get_selected() if iter == None: return gameno = model.get_value(iter, 0...
def onChallengeRemove (self, index): if not index in self.challenges: return ti = self.challenges [index] if not self.store.iter_is_valid(ti): return self.store.remove (ti) del self.challenges [index] count = int(self.widgets["activeSeeksLabel"].get_text().split()[0])-1 self.widgets["activeSeeksLabel"].set_text(_("Acti...
self.board = board.switchColor()
self.board = self.board.switchColor()
def putMove (self, board1, move, board2): """ For spectactors """ self.board = board1 if not board2: self.__go() self.gonext = False return if self.mode == INVERSE_ANALYZING: self.board = board.switchColor() self.__printColor() self.__usermove(board2, move) if self.mode == INVERSE_ANALYZING: if self.board.board.op...
self.board = board.switchColor()
self.board = self.board.switchColor()
def undoMoves (self, moves, gamemodel): if self.mode not in (ANALYZING, INVERSE_ANALYZING): if gamemodel.curplayer != self and moves % 2 == 1: # Interrupt if we were searching, but should no longer do so self.returnQueue.put("int") self.__force() if self.board and gamemodel.status in UNFINISHED_STATES: self.__hurry() ...
gameno0 = model.get_value(iter0, 0) gameno1 = model.get_value(iter1, 0) textcolor0 = model.get_value(iter0, 8) textcolor1 = model.get_value(iter1, 8)
row0 = list(model[model.get_path(iter0)]) row1 = list(model[model.get_path(iter1)])
def compareFunction (self, model, iter0, iter1, column): gameno0 = model.get_value(iter0, 0) gameno1 = model.get_value(iter1, 0) textcolor0 = model.get_value(iter0, 8) textcolor1 = model.get_value(iter1, 8) is_ascending = True if self.tv.get_column(column-1).get_sort_order() is \ gtk.SORT_ASCENDING else False if (gamen...
if (gameno0 is not None and gameno0.startswith("C")) or (textcolor0 == "grey"):
if self.__isAChallengeOrOurSeek(row0) and not self.__isAChallengeOrOurSeek(row1):
def compareFunction (self, model, iter0, iter1, column): gameno0 = model.get_value(iter0, 0) gameno1 = model.get_value(iter1, 0) textcolor0 = model.get_value(iter0, 8) textcolor1 = model.get_value(iter1, 8) is_ascending = True if self.tv.get_column(column-1).get_sort_order() is \ gtk.SORT_ASCENDING else False if (gamen...
elif (gameno1 is not None and gameno1.startswith("C")) or (textcolor1 == "grey"):
elif self.__isAChallengeOrOurSeek(row1) and not self.__isAChallengeOrOurSeek(row0):
def compareFunction (self, model, iter0, iter1, column): gameno0 = model.get_value(iter0, 0) gameno1 = model.get_value(iter1, 0) textcolor0 = model.get_value(iter0, 8) textcolor1 = model.get_value(iter1, 8) is_ascending = True if self.tv.get_column(column-1).get_sort_order() is \ gtk.SORT_ASCENDING else False if (gamen...
value0 = model.get_value(iter0, column)
value0 = row0[column]
def compareFunction (self, model, iter0, iter1, column): gameno0 = model.get_value(iter0, 0) gameno1 = model.get_value(iter1, 0) textcolor0 = model.get_value(iter0, 8) textcolor1 = model.get_value(iter1, 8) is_ascending = True if self.tv.get_column(column-1).get_sort_order() is \ gtk.SORT_ASCENDING else False if (gamen...
value1 = model.get_value(iter1, column)
value1 = row1[column]
def compareFunction (self, model, iter0, iter1, column): gameno0 = model.get_value(iter0, 0) gameno1 = model.get_value(iter1, 0) textcolor0 = model.get_value(iter0, 8) textcolor1 = model.get_value(iter1, 8) is_ascending = True if self.tv.get_column(column-1).get_sort_order() is \ gtk.SORT_ASCENDING else False if (gamen...
ti = self.store.append ([seek["gameno"], pix, seek["w"], int(seek["rt"]), rated, seek["tp"], time, float(seek["t"] + "." + seek["i"]), textcolor])
seek_ = [seek["gameno"], pix, seek["w"], int(seek["rt"]), rated, seek["tp"], time, float(seek["t"] + "." + seek["i"]), textcolor]
def onAddSeek (self, seek): time = _("%(min)s min") % {'min': seek["t"]} if seek["i"] != "0": time += _(" + %(sec)s sec") % {'sec': seek["i"]} rated = seek["r"] == "u" and _("Unrated") or _("Rated") pix = seek["manual"] and self.manSeekPix or self.seekPix textcolor = "grey" if seek["w"] == self.connection.getUsername()...
if not connection.isRegistred(): self.widgets["ratedGameCheck"].set_active(False) self.widgets["ratedGameCheck"].hide() else: self.widgets["ratedGameCheck"].show()
if not self.connection.isRegistred(): self.chainbox.active = False self.widgets["chainAlignment"].set_sensitive(False) self.widgets["chainAlignment"].set_tooltip_text( _("You can't play rated games because you are logged in as a guest, ") + _("and therefore, the chain button is not applicable"))
def chainboxSetter (widget, is_active): self.chainbox.active = is_active
def __showSeekEditor (self, seeknumber, challengemode=False):
def __updateSeekEditor (self, seeknumber, challengemode=False): self.in_challenge_mode = challengemode
def __showSeekEditor (self, seeknumber, challengemode=False): self.seeknumber = seeknumber if not challengemode: self.widgets["strengthFrame"].set_sensitive(True) self.widgets["manualAcceptCheck"].set_sensitive(True) else: self.widgets["strengthFrame"].set_sensitive(False) self.widgets["manualAcceptCheck"].set_sensitiv...
if isAnythingSelected: playerTitle = model.get_value(iter, 0) isGuestPlayer = playerTitle == PlayerTabSection.peoplepix self.widgets["ratedGameCheck"].set_sensitive(not isAnythingSelected or not isGuestPlayer)
def onPlayerSelectionChanged (self, selection): model, iter = selection.get_selected() # You can't press challengebutton when nobody is selected isAnythingSelected = iter != None self.widgets["challengeButton"].set_sensitive(isAnythingSelected) if isAnythingSelected: # You can't challenge a guest to a rated game play...
if key in ("time", "variant", "color", "rated"):
if key in ("time", "variant", "color") or \ (key == "rated" and not self.challengee_is_guest):
def __writeSavedSeeks (self, seeknumber): """ Writes saved seek strings for both the Seek Panel and the Challenge Panel """ min, gain, variant, ratingrange, color, rated, manual = self.__getSeekEditorDialogValues() isUntimedGame = True if min is 0 else False radioText = self.__getNameOfTimeControl(min, gain) self.saved...
self.widgets["ratedGameCheck"].set_sensitive(not is_untimed_game)
if is_untimed_game: self.widgets["variantFrame"].set_tooltip_text( _("You can't select a variant because \"Untimed\" is checked, ") + _("and on FICS, untimed games have to be normal chess rules")) else: self.widgets["variantFrame"].set_tooltip_text("") self.__updateRatedGameCheck()
def onUntimedCheckToggled (self, check): is_untimed_game = check.get_active() self.widgets["timeControlConfigVBox"].set_sensitive(not is_untimed_game) # on FICS, untimed games can't be rated and can't be a chess variant self.widgets["variantFrame"].set_sensitive(not is_untimed_game) self.widgets["ratedGameCheck"].set_s...
if conf.get("numberOfTimesLoggedInAsRegisteredUser", 0) is 1:
numfingers = conf.get("numberOfFingers", 0) + 1 conf.set("numberOfFingers", numfingers) if conf.get("numberOfTimesLoggedInAsRegisteredUser", 0) is 1 and numfingers is 1:
def onFinger (self, fm, finger): if not finger.getName() == self.connection.getUsername(): return self.finger = finger if conf.get("numberOfTimesLoggedInAsRegisteredUser", 0) is 1: standard = self.__getRating(TYPE_STANDARD) blitz = self.__getRating(TYPE_BLITZ) lightning = self.__getRating(TYPE_LIGHTNING) if standard ...
if cord == self.view.active == self.view.selected: self.view.hover = cord self.view.selected = None self.view.active = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal()
def release (self, x, y): cord = self.point2Cord(x,y) if not cord: self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() # When in the mixed active/selected state elif self.view.selected: # Unselect when releasing on an already selected ...
elif self.validate(self.view.selected, cord):
if self.validate(self.view.selected, cord):
def release (self, x, y): cord = self.point2Cord(x,y) if not cord: self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() # When in the mixed active/selected state elif self.view.selected: # Unselect when releasing on an already selected ...
elif self.getBoard()[cord] and \ self.getBoard()[cord].color == self.getBoard().color: self.view.selected = cord
elif cord == self.view.active == self.view.selected == self.parent.selected_last: self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() else:
def release (self, x, y): cord = self.point2Cord(x,y) if not cord: self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() # When in the mixed active/selected state elif self.view.selected: # Unselect when releasing on an already selected ...
else: self.view.selected = None self.view.active = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal()
def release (self, x, y): cord = self.point2Cord(x,y) if not cord: self.view.active = None self.view.selected = None self.view.draggedPiece = None self.view.startAnimation() self.parent.setStateNormal() # When in the mixed active/selected state elif self.view.selected: # Unselect when releasing on an already selected ...
if len(san) < 2: if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen())
if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) elif len(san) < 2:
def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ if len(san) < 2: if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) raise ParsingError, (san, _("the move is too short"), board.asFen()) notat = san color = board.color if notat[-1] in ("+", "#")...
_("Do you can call flag when the clock is with you, <b>Actions</b> > <b>Call Flag</b>."),
_("Do you know that you can call flag when the clock is with you, <b>Actions</b> > <b>Call Flag</b>."),
def set_currentIndex (cls, value): if len(tips) == 0: return if value < 0: value = len(tips)-1 elif value >= len(tips): value = 0 cls.currentIndex = value cls.widgets["tipfield"].set_markup(tips[value])
_("Do you can help translate Pychess in your language, <b>Help</b> > <b>Translate Pychess</b>."),
_("Do you know that you can help translate Pychess in your language, <b>Help</b> > <b>Translate Pychess</b>."),
def set_currentIndex (cls, value): if len(tips) == 0: return if value < 0: value = len(tips)-1 elif value >= len(tips): value = 0 cls.currentIndex = value cls.widgets["tipfield"].set_markup(tips[value])
^ \s* \d+ \.? \s+ (-?Mat\d+ | [-\d\.]+) \s+ [\d\.]+ \s+ [\d\.]+ \s+ (.+) \s* $
^ \s* \d+ [+\-\.]? \s+ (-?Mat\s*\d+ | [-\d\.]+) \s+ [\d\.]+ \s+ [\d\.]+ \s+ (.+) \s* $
def isdigits (strings): for s in strings: s = s.replace(".","") if s.startswith("-"): if not s[1:].isdigit(): return False else: if not s.isdigit(): return False return True
score = MATE_VALUE - int("".join(c for c in score if c.isdigit())) if score.startswith('-'): score = -score
scoreval = MATE_VALUE - int("".join(c for c in score if c.isdigit())) if score.startswith('-'): scoreval = -scoreval
def __parseLine (self, line): parts = whitespaces.split(line.strip()) if parts[0] == "pong": self.lastpong = int(parts[1]) return # Illegal Move if parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): print >> self.engine, "depth", parts[-1] return # A Move (Perhaps) if self.board: if...
score = int(score)
scoreval = int(score)
def __parseLine (self, line): parts = whitespaces.split(line.strip()) if parts[0] == "pong": self.lastpong = int(parts[1]) return # Illegal Move if parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): print >> self.engine, "depth", parts[-1] return # A Move (Perhaps) if self.board: if...
self.emit("analyze", moves, score)
self.emit("analyze", moves, scoreval)
def __parseLine (self, line): parts = whitespaces.split(line.strip()) if parts[0] == "pong": self.lastpong = int(parts[1]) return # Illegal Move if parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): print >> self.engine, "depth", parts[-1] return # A Move (Perhaps) if self.board: if...
option = fromstring('<%s-option/>' % dic['type'])
option = fromstring('<%s-option name="%s"/>' % (dic.pop('type'), name))
def __fromUCIProcess (self, subprocess): ids = subprocess.ids options = subprocess.options engine = fromstring('<engine><meta/><options/></engine>') meta = engine.find('meta') if "name" in ids: meta.append(fromstring('<name>%s</name>' % ids['name'])) if 'author' in ids: meta.append(fromstring('<author>%s</author>' % i...
if key == 'type': continue if key != 'vars':
if key == 'vars': for valueoption in value: option.append(fromstring('<var name="%s" />' % valueoption)) else:
def __fromUCIProcess (self, subprocess): ids = subprocess.ids options = subprocess.options engine = fromstring('<engine><meta/><options/></engine>') meta = engine.find('meta') if "name" in ids: meta.append(fromstring('<name>%s</name>' % ids['name'])) if 'author' in ids: meta.append(fromstring('<author>%s</author>' % i...
else: for subvalue in value: option.append(fromstring('<var name="%s" />' % subvalue))
def __fromUCIProcess (self, subprocess): ids = subprocess.ids options = subprocess.options engine = fromstring('<engine><meta/><options/></engine>') meta = engine.find('meta') if "name" in ids: meta.append(fromstring('<name>%s</name>' % ids['name'])) if 'author' in ids: meta.append(fromstring('<author>%s</author>' % i...
self.connect("all_engines_discovered", cb)
def count(self_, binname, engine, wentwell): self.toBeRechecked[engine] = True if all(self.toBeRechecked.values()): self.emit("all_engines_discovered")
if variantClass.cecp_name == feature.get('value'):
if variantClass.cecp_name in feature.get('value'):
def getEngineVariants (self, engine): for variantClass in variants.values(): if variantClass.standard_rules: yield variantClass.board.variant else: for feature in engine.findall("cecp-features/feature"): if feature.get("name") == "variants": if variantClass.cecp_name == feature.get('value'): yield variantClass.board.va...
message, separator, hbuttonbox = messageDialog.child.get_children()
message = messageDialog.child.get_children()[0] hbuttonbox = messageDialog.child.get_children()[-1]
def showMessage (self, messageDialog, vertical=False): if self.messageSock.child: self.messageSock.remove(self.messageSock.child) message, separator, hbuttonbox = messageDialog.child.get_children() if vertical: buttonbox = gtk.VButtonBox() buttonbox.props.layout_style = gtk.BUTTONBOX_SPREAD for button in hbuttonbox.ge...
self.connect (self.rds_enc, (self.rate_enforcer, 0))
self.connect (self.rds_enc, self.diff_enc, self.nrz, self.c2f) self.connect (self.c2f, (self.rate_enforcer, 0))
def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv)
(usrp_dbid.TV_RX, usrp_dbid.TV_RX_REV_2, usrp_dbid.TV_RX_REV_3, usrp_dbid.BASIC_RX))
(usrp_dbid.TV_RX, usrp_dbid.TV_RX_REV_2, usrp_dbid.BASIC_RX))
def __init__(self,frame,panel,vbox,argv): stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv)
if 1:
if 0:
def _form_set_freq(kv): return self.set_freq(kv['freq'])
if 0:
if 1:
def _form_set_freq(kv): return self.set_freq(kv['freq'])
RecordData(self.gds_record, acls=data)
RecordData(self.gds_record, acls=data).save(stream)
def save(self, instance, stream): data = getattr(instance, self.priv_variable, None) if data: RecordData(self.gds_record, acls=data)
expected_results = self.data.values()
expected_results = list(self.data.values())
def test_parse(self): packed_data = struct.pack('>{0}Q'.format(len(self.data)), *self.data.keys()) unpacked = _parse_real8(packed_data) expected_results = self.data.values() self.assertEqual(len(unpacked), len(expected_results)) for i in range(len(unpacked)): self.assertAlmostEqual(unpacked[i], expected_results[i])
expected_results = self.data.values()
expected_results = list(self.data.values())
def test_pack(self): packed_data = _pack_real8(self.data.values()) unpacked = _parse_real8(packed_data) expected_results = self.data.values() self.assertEqual(len(unpacked), len(expected_results)) for i in range(len(unpacked)): self.assertAlmostEqual(unpacked[i], expected_results[i])
def __init__(self, tag, data):
def __init__(self, tag, data=None, points=None, times=None):
def __init__(self, tag, data): """Initialize with tag and parsed data.""" self._tag = tag self._data = data
self._data = data
if data is not None: self._data = data elif points is not None: new_data = [] for point in points: new_data.append(point[0]) new_data.append(point[1]) self._data = new_data elif times is not None: mod_time = times[0] acc_time = times[1] return [ mod_time.year - 1900, mod_time.month, mod_time.day, mod_time.hour, mod_ti...
def __init__(self, tag, data): """Initialize with tag and parsed data.""" self._tag = tag self._data = data
>>> rec = RecordData(GDSII.STRNAME, 'struct')
>>> rec = RecordData(GDSII.STRNAME, b'struct')
def check_tag(self, tag): """ Checks if current record has the same tag as the given one. Raises :exc:`MissingRecord` exception otherwise. For example::
Returns next record is ``lastrec`` has given tag, otherwise returns ``lastrec``.
Returns next record is `lastrec` has given tag, otherwise returns `lastrec`.
def _ignore_record(recs, lastrec, tag): """ Returns next record is ``lastrec`` has given tag, otherwise returns ``lastrec``. :param recs: :class:`RecordData` generator :type recs: iterable :param lastrec: last read record :type lastrec: :class:`RecordData` """ if lastrec.tag != tag: return lastrec return next(recs)
SimpleOptionalRecord.write(self, instance, stream)
SimpleOptionalRecord.save(self, instance, stream)
def write(self, instance, stream): fmt = getattr(instance, self.priv_variable, None) if fmt is not None: SimpleOptionalRecord.write(self, instance, stream) if fmt == 1 or fmt == 3: masks = getattr(instance, self.priv_variable2, []) for mask in masks: RecordData(tags.MASK, mask).save(stream) RecordData(tags.ENDMASKS).sa...
self.strans = None
self.properties = None
def _init_optional(self): self.elflags = None self.strans = None self.mag = None self.angle = None self.strans = None
def write(self, instance, stream):
def save(self, instance, stream):
def write(self, instance, stream): fmt = getattr(instance, self.priv_variable, None) if fmt is not None: SimpleOptionalRecord.save(self, instance, stream) if fmt == 1 or fmt == 3: masks = getattr(instance, self.priv_variable2, []) for mask in masks: RecordData(tags.MASK, mask).save(stream) RecordData(tags.ENDMASKS).sav...
def write(self, instance, stream):
def save(self, instance, stream):
def write(self, instance, stream): unit1 = getattr(instance, self.priv_variable) unit2 = getattr(instance, self.priv_variable2) RecordData(self.gds_record, [unit1, unit2]).write(stream)
RecordData(self.gds_record, [unit1, unit2]).write(stream)
RecordData(self.gds_record, (unit1, unit2)).save(stream)
def write(self, instance, stream): unit1 = getattr(instance, self.priv_variable) unit2 = getattr(instance, self.priv_variable2) RecordData(self.gds_record, [unit1, unit2]).write(stream)
setattr(obj, self.priv_variable)
setattr(obj, self.priv_variable, value)
def f(obj, value): setattr(obj, self.priv_variable)
setattr(obj, self.priv_variable2)
setattr(obj, self.priv_variable2, value)
def f(obj, value): setattr(obj, self.priv_variable2)
raise TypeErrror('at least one optional argument is required')
raise TypeError('at least one optional argument is required')
def __init__(self, tag, data=None, points=None, times=None): """Initialize with tag and parsed data.""" self._tag = tag if data is not None: self._data = data elif points is not None: new_data = [] # TODO make it faster for point in points: new_data.append(point[0]) new_data.append(point[1]) self._data = new_data elif ...
return '0x%02x' % typ
return '0x%02x' % tag_type
def tag_type_name(self): """Tag data type name, if known, and formatted number otherwise.""" tag_type = type_of_tag(self._tag) if tag_type in _TYPE_TO_NAME_MAP: return _TYPE_TO_NAME_MAP[tag_type] return '0x%02x' % typ
def create_plot(tempo_results, xkey, ykey, postfit=True, prefit=False, \ interactive=True, mark_peri=False, show_legend=True):
def create_plot():
def create_plot(tempo_results, xkey, ykey, postfit=True, prefit=False, \ interactive=True, mark_peri=False, show_legend=True): # Set up the plot fig = plt.figure(figsize=(11,8.5)) plot_data(tempo_results, xkey, ykey, postfit, prefit, \ interactive, mark_peri, show_legend) # Register event callbacks function and show ...
plot_data(tempo_results, xkey, ykey, postfit, prefit, \ interactive, mark_peri, show_legend) cid_keypress = fig.canvas.mpl_connect('key_press_event', keypress) cid_pick = fig.canvas.mpl_connect('pick_event', pick) if interactive: plt.ion() plt.show() else: savefigure() quit()
def create_plot(tempo_results, xkey, ykey, postfit=True, prefit=False, \ interactive=True, mark_peri=False, show_legend=True): # Set up the plot fig = plt.figure(figsize=(11,8.5)) plot_data(tempo_results, xkey, ykey, postfit, prefit, \ interactive, mark_peri, show_legend) # Register event callbacks function and show ...
print "Saving plot to %s" % savefn plt.savefig(savefn, orientation='landscape', papertype='letter')
print "Saving plot to %s" % savefn plt.savefig(savefn, orientation='landscape', papertype='letter') def reloadplot(): print "Reloading..." print "options.legend:", options.legend plt.clf() tempo_results = TempoResults(options.freqbands) plot_data(tempo_results, options.xaxis, options.yaxis, postfit=options.postfit, ...
def savefigure(savefn='./resid2.tmp.ps'): print "Saving plot to %s" % savefn plt.savefig(savefn, orientation='landscape', papertype='letter')