1667066940
Class for logging excessive blocking on the main thread. It watches the main thread and checks if it doesn’t get blocked for more than defined threshold.
👮 Main thread was blocked for 1.25s 👮
You can also inspect which part of your code is blocking the main thread.
Simply, just instantiate Watchdog with number of seconds that must pass to consider the main thread blocked. Additionally you can enable strictMode
that stops the execution whenever the threshold is reached. This way, you can inspect which part of your code is blocking the main thread.
let watchdog = Watchdog(threshold: 0.4, strictMode: true)
Don't forget to retain Watchdog somewhere or it will get released when it goes out of scope.
Add the following to your Cartfile:
github "wojteklu/Watchdog"
Then run carthage update
.
Follow the current instructions in Carthage's README for up to date installation instructions.
Add the following to your Podfile:
pod 'Watchdog'
You will also need to make sure you're opting into using frameworks:
use_frameworks!
Manually add the file into your Xcode project. Slightly simpler, but updates are also manual.
Author: Wojteklu
Source Code: https://github.com/wojteklu/Watchdog
License: MIT license
1675381680
Do you want to make a Simple Tic-Tac-Toe game using JavaScript?
In this article you will learn how to create tic tac toe game using html css and javascript. If you are a beginner in JavaScript then Tic Tac Toe Game is perfect for you. This simple javascript game will help you improve your knowledge of javascript.
Earlier I shared another Simple Tic-Tac-Toe JavaScript game for beginners. So I made this design in a very advanced way. Here basically we will play with the computer that is we will play with the computer.
To create this tic-tac-toe javascript first I created the basic structure by html. Then I designed it with css and finally activated this project (tic tac toe javascript code against computer) with javascript.
JavaScript Tic Tac Toe is a simple game where two players take turns marking a grid of 3×3 squares, typically using X and O symbols. JavaScript is a programming language that can be used to create interactive websites and games, such as a Tic Tac Toe game.
A JavaScript implementation of Tic Tac Toe would involve creating a grid of squares using HTML and CSS, and then using JavaScript to handle the logic of the game, including determining the winner and allowing players to take turns.
As you can see above this is an advanced Tic Tac Toe game that I made with javascript. Like a normal JavaScript Tic Tac Toe game, there are 9 cells and two symbols.
Here I have defined symbol “0” for user and “X” for computer. But you can change it if you want. When you click in any one of those 9 cells, another cell will automatically be filled by the computer.
Besides, I have added different types of color FF in the project (tic tac toe javascript code against computer) to make this design more modern.
Now if you want to build it then you can follow the tutorial below. I have explained the complete codes step by step keeping the beginners in mind.
Hope you know the rules of this game. It is a simple javascript game where two players take turns marking the spaces in a 3×3 grid with X’s and O’s, with the goal of getting three of their marks in a row, either horizontally, vertically, or diagonally. The player who succeeds in placing three of their marks in a row is the winner.
First I created a basic structure of this project using the following HTML and CSS codes. Besides, I have added a heading here mainly to enhance the beauty. This heading is created by H1 tag in HTML.
<div class="container">
<h1>Tic-Tac-Toe</h1>
</div>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
.container {
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #eee;
}
h1 {
font-size: 4rem;
margin-bottom: 0.5em;
}
Now create a small area for this tic tac toe javascript. Within this box are nine smaller boxes into which players can input their symbols. Also we designed this area by some css.
<div class="play-area">
</div>
.play-area {
display: grid;
box-shadow: 0 0 20px rgba(0,139,253,0.25);
grid-template-columns: auto auto auto;
background-color: #fff;
padding: 20px;
}
Now another heading we need to create is within this project(How to Build Tic Tac Toe with JavaScript, HTML and CSS). This heading is mainly for showing results.
Although this heading is currently not visible to us because there is no information in the heading. We will add this information via javascript. Results will be available automatically after Tic Tac Toe game is over.
<h2 id="winner"></h2>
h2 {
margin-top: 1em;
font-size: 2rem;
margin-bottom: 0.5em;
}
Now we have to create a button in this simple Tic-Tac-Toe game. This button will basically work as a reset button. When you click on this button, the game will restart from a new state.
<button onclick="reset_board()">RESET</button>
button {
outline: none;
background: rgb(8, 88, 208);
padding: 12px 40px;
font-size: 1rem;
font-weight: bold;
color: #fff;
border: none;
transition: all 0.2s ease-in-out;
}
button:hover {
cursor: pointer;
background: green;
color: white;
}
Above we have designed this project(How to create a tic tac toe grid in JavaScript?). Now it’s time to make it work using JavaScript. We have used quite a bit of JavaScript code to make this game work. But don’t worry I will tell you all the codes step by step.
const player = "O";
const computer = "X";
let board_full = false;
let play_board = ["", "", "", "", "", "", "", "", ""];
const board_container = document.querySelector(".play-area");
const winner_statement = document.getElementById("winner");
With these variables, you’ve defined the player and computer as “O” and “X” respectively, and created an empty board to play on. The board_full
variable will be used to check if the board is full and the game is over, and the play_board
array will hold the state of the game.
The board_container
variable is used to select the element on the page where the Tic Tac Toe board will be rendered, and the winner_statement
variable is used to select the element where the winner statement will be displayed.
check_board_complete = () => {
let flag = true;
play_board.forEach(element => {
if (element != player && element != computer) {
flag = false;
}
});
board_full = flag;
};
The function is using the forEach()
method to iterate over the play_board
array, and it checks if each element is not equal to the player or computer. If any element is not equal to the player or computer, it sets the flag variable to false and breaks out of the loop.
If the loop completes and the flag variable is still true, it means that all the elements are equal to the player or computer, and the board is full. Then the board_full
variable is updated to reflect that the board is full.
You can use this function at the end of the player’s turn and computer’s turn, to check if the board is full and the game is over.
const check_line = (a, b, c) => {
return (
play_board[a] == play_board[b] &&
play_board[b] == play_board[c] &&
(play_board[a] == player || play_board[a] == computer)
);
};
The function takes in 3 arguments, a
, b
, c
, which represent the indices of the 3 cells on the board that need to be checked for a winning line.
The function uses the ternary operator to check if the values at the indices a
, b
, c
in the play_board
array are the same and not empty. If the values are the same and not empty, the function returns true, otherwise it returns false.
You can use this function in a larger function that checks for all the possible winning combinations on the board.
const check_match = () => {
for (i = 0; i < 9; i += 3) {
if (check_line(i, i + 1, i + 2)) {
document.querySelector(`#block_${i}`).classList.add("win");
document.querySelector(`#block_${i + 1}`).classList.add("win");
document.querySelector(`#block_${i + 2}`).classList.add("win");
return play_board[i];
}
}
for (i = 0; i < 3; i++) {
if (check_line(i, i + 3, i + 6)) {
document.querySelector(`#block_${i}`).classList.add("win");
document.querySelector(`#block_${i + 3}`).classList.add("win");
document.querySelector(`#block_${i + 6}`).classList.add("win");
return play_board[i];
}
}
if (check_line(0, 4, 8)) {
document.querySelector("#block_0").classList.add("win");
document.querySelector("#block_4").classList.add("win");
document.querySelector("#block_8").classList.add("win");
return play_board[0];
}
if (check_line(2, 4, 6)) {
document.querySelector("#block_2").classList.add("win");
document.querySelector("#block_4").classList.add("win");
document.querySelector("#block_6").classList.add("win");
return play_board[2];
}
return "";
};
The check_match()
function uses two for loops to check for all the possible winning combinations on the board, both horizontally and vertically. It also includes two if statements to check for the two diagonal winning combinations.
The function uses the check_line
function you created earlier to check if a line is a winning line. If a winning line is found, the function highlights the winning cells by adding the “win” class to them. This class can be used in your CSS to change the appearance of the winning cells, for example by adding a different background color.
The function also returns the value of the first cell in the winning line, which should be either “X” or “O” depending on who won the game.
You can use this function in another function that checks for a win or a draw and updates the UI accordingly.
const check_for_winner = () => {
let res = check_match()
if (res == player) {
winner.innerText = "Winner is player!!";
winner.classList.add("playerWin");
board_full = true
} else if (res == computer) {
winner.innerText = "Winner is computer";
winner.classList.add("computerWin");
board_full = true
} else if (board_full) {
winner.innerText = "Draw!";
winner.classList.add("draw");
}
};
This code looks like it’s checking for a winner in a javascript Tic Tac Toe game. The check_line
function takes in 3 indices of the play_board array and checks if the values at those indices are equal to each other and if they are equal to either the player or computer.
The check_match
function uses the check_line
function to check for a winner across the rows, columns, and diagonals of the Tic Tac Toe board. If a winning line is found, the check_match
function adds a “win” class to the corresponding HTML elements of the Tic Tac Toe board and returns the winning player.
The check_for_winner
function calls the check_match
function and checks the returned value. If the returned value is the player, it sets the winner statement to “Winner is player!!” and adds playerWin class.
const render_board = () => {
board_container.innerHTML = ""
play_board.forEach((e, i) => {
board_container.innerHTML += `<div id="block_${i}" class="block" onclick="addPlayerMove(${i})">${play_board[i]}</div>`
if (e == player || e == computer) {
document.querySelector(`#block_${i}`).classList.add("occupied");
}
});
};
The render_board()
function creates a grid of divs in the HTML, each one representing a cell in the Tic-Tac-Toe board. The addPlayerMove()
function allows the player to make a move by clicking on a cell in the grid.
The check_board_complete()
function checks if the board is full and the check_for_winner()
function checks for a winner or draw. It also uses the check_match()
function to check if any winning combination is formed.
const game_loop = () => {
render_board();
check_board_complete();
check_for_winner();
}
The game_loop
function combines all of these functions together to create the game loop that updates the game state and renders the game board to the user.
It calls the render_board
function to render the current state of the game board to the user, check_board_complete
to check if the board is full and check_for_winner
which checks if there is a winner or a draw, and updates the UI accordingly.
const addPlayerMove = e => {
if (!board_full && play_board[e] == "") {
play_board[e] = player;
game_loop();
addComputerMove();
}
};
The above code defines a Tic Tac Toe game in JavaScript that uses HTML and CSS for the game board and styling. The game’s state is maintained in the play_board
array, and the game_loop
function updates the state of the game, renders the board, and checks for a winner.
The addPlayerMove
function allows players to make a move by clicking on a block on the board, and the addComputerMove
function allows the computer to make a move. The check_match
, check_for_winner
, render_board
functions are also defined and used in the game loop to check for a winner or a draw, render the board and check if the game is complete.
const addComputerMove = () => {
if (!board_full) {
do {
selected = Math.floor(Math.random() * 9);
} while (play_board[selected] != "");
play_board[selected] = computer;
game_loop();
}
};
Great! Your code is now complete and should be able to run a game of javascript Tic-Tac-Toe between a player and the computer. The player can make moves by clicking on the blocks on the game board, and the computer will randomly select an available space to make its move. The code also checks for a winner or a draw after each move, and updates the game board and the winner statement accordingly.
const reset_board = () => {
play_board = ["", "", "", "", "", "", "", "", ""];
board_full = false;
winner.classList.remove("playerWin");
winner.classList.remove("computerWin");
winner.classList.remove("draw");
winner.innerText = "";
render_board();
};
This code defines a function called “reset_board” that sets the play_board array back to an empty array, sets the board_full variable to false, removes any classes related to winning or drawing from the winner element, sets the inner text of the winner element to an empty string, and then calls the render_board function to update the display. This function is likely intended to be used as a way to clear the game board and start a new game.
//initial render
render_board();
That’s it, you have created a complete Tic-Tac-Toe game using JavaScript. To start the game, the player can click on any of the empty blocks on the board and the computer will automatically make its move.
The game checks for a winner or a draw after each move and updates the board accordingly. The game can also be reset by calling the reset_board()
function.
Above we enabled Tic-tac-toe in JavaScript by JavaScript. Now we need to design it with some more CSS. We know there are 9 small boxes in this game that are currently too small for us to see. So a fixed size must be defined for each box.
.block {
display: flex;
width: 100px;
height: 100px;
align-items: center;
justify-content: center;
font-size: 3rem;
font-weight: bold;
border: 3px solid black;
transition: background 0.2s ease-in-out;
}
.block:hover {
cursor: pointer;
background: #0ff30f;
}
.occupied:hover {
background: #ff3a3a;
}
.win {
background: #0ff30f;
}
.win:hover {
background: #0ff30f;
}
As we can see in the above image there are 9 boxes created. But we want to hide some borders here. We will use the following CSS to hide those borders.
#block_0,
#block_1,
#block_2 {
border-top: none;
}
#block_0,
#block_3,
#block_6 {
border-left: none;
}
#block_6,
#block_7,
#block_8 {
border-bottom: none;
}
#block_2,
#block_5,
#block_8 {
border-right: none;
}
.playerWin {
color: green;
}
.computerWin {
color: red;
}
.draw {
color: orangered;
}
We’ll make this project(Create a Tic-Tac-Toe with HTML and JavaScript) responsive using a small amount of our own code. Here for Responsive only headings have been resized or reduced.
@media only screen and (max-width: 600px) {
h1 {
font-size: 3rem;
margin-bottom: 0.5em;
}
h2 {
margin-top: 1em;
font-size: 1.3rem;
}
}
Hope from this tutorial you got to know how I made this Simple Tic-Tac-Toe JavaScript game.
Not only this but earlier I have shared more advanced game tutorials. Earlier I shared another JavaScript Tic-Tac-Toe which is basically made by Simple Code. Where you can play with two users rather than with the computer. Be sure to comment how you like this project(How to Recreate Tic-Tac-Toe in Vanilla JavaScript).
Original article source at: https://foolishdeveloper.com/
1649463840
DISCLAIMER: This is not an official google project, this is just something I wrote while at Google.
Pyringe
Pyringe is a python debugger capable of attaching to running processes, inspecting their state and even of injecting python code into them while they're running. With pyringe, you can list threads, get tracebacks, inspect locals/globals/builtins of running functions, all without having to prepare your program for it.
A "Google project". It's my internship project that got open-sourced. Sorry for the confusion.
Pyringe internally uses gdb to do a lot of its heavy lifting, so you will need a fairly recent build of gdb (version 7.4 onwards, and only if gdb was configured with --with-python
). You will also need the symbols for whatever build of python you're running.
On Fedora, the package you're looking for is python-debuginfo
, on Debian it's called python2.7-dbg
(adjust according to version). Arch Linux users: see issue #5, Ubuntu users can only debug the python-dbg
binary (see issue #19).
Having Colorama will get you output in boldface, but it's optional.
Get it from the Github repo, PyPI, or via pip (pip install pyringe
).
Short answer: No, sorry. Long answer:
There's three potentially different versions of python in play here:
libpythonXX.so
your build of gdb was linked against2
Is currently the dealbreaker here. Cpython has changed a bit in the meantime[1], and making all features work while debugging python3 will have to take a back seat for now until the more glaring issues have been taken care of.
As for 1
and 3
, the 2to3
tool may be able to handle it automatically. But then, as long as 2
hasn't been taken care of, this isn't really a use case in the first place.
[1] - For example, pendingbusy
(which is used for injection) has been renamed to busy
and been given a function-local scope, making it harder to interact with via gdb.
Unfortunately, no. Since this makes use of some CPython internals and implementation details, only CPython is supported. If you don't know what PyPy or CPython are, you'll probably be fine.
PDB is great. Use it where applicable! But sometimes it isn't.
Like when python itself crashes, gets stuck in some C extension, or you want to inspect data without stopping a program. In such cases, PDB (and all other debuggers that run within the interpreter itself) are next to useless, and without pyringe you'd be left with having to debug using print
statements. Pyringe is just quite convenient in these cases.
This is a known limitation. Things like inject('var = 2')
won't work, but inject('var[1] = 1337')
should. This is because most of the time, python internally uses a fast path for looking up local variables that doesn't actually perform the dictionary lookup in locals()
. In general, code you inject into processes with pyringe is very different from a normal python function call.
You can start the debugger by executing python -m pyringe
. Alternatively:
import pyringe
pyringe.interact()
If that reminds you of the code module, good; this is intentional.
After starting the debugger, you'll be greeted by what behaves almost like a regular python REPL.
Try the following:
==> pid:[None] #threads:[0] current thread:[None]
>>> help()
Available commands:
attach: Attach to the process with the given pid.
bt: Get a backtrace of the current position.
[...]
==> pid:[None] #threads:[0] current thread:[None]
>>> attach(12679)
==> pid:[12679] #threads:[11] current thread:[140108099462912]
>>> threads()
[140108099462912, 140108107855616, 140108116248323, 140108124641024, 140108133033728, 140108224739072, 140108233131776, 140108141426432, 140108241524480, 140108249917184, 140108269324032]
The IDs you see here correspond to what threading.current_thread().ident
would tell you.
All debugger functions are just regular python functions that have been exposed to the REPL, so you can do things like the following.
==> pid:[12679] #threads:[11] current thread:[140108099462912]
>>> for tid in threads():
... if not tid % 10:
... thread(tid)
... bt()
...
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 524, in __bootstrap
self.__bootstrap_inner()
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "./test.py", line 46, in Idle
Thread_2_Func(1)
File "./test.py", line 40, in Wait
time.sleep(n)
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>>
You can access the inferior's locals and inspect them like so:
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>> inflocals()
{'a': <proxy of A object at remote 0x1d9b290>, 'LOL': 'success!', 'b': <proxy of B object at remote 0x1d988c0>, 'n': 1}
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>> p('a')
<proxy of A object at remote 0x1d9b290>
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>> p('a').attr
'Some_magic_string'
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>>
And sure enough, the definition of a
's class reads:
class Example(object):
cl_attr = False
def __init__(self):
self.attr = 'Some_magic_string'
There's limits to how far this proxying of objects goes, and everything that isn't trivial data will show up as strings (like '<function at remote 0x1d957d0>'
).
You can inject python code into running programs. Of course, there are caveats but... see for yourself:
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>> inject('import threading')
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>> inject('print threading.current_thread().ident')
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>>
The output of my program in this case reads:
140108241524480
If you need additional pointers, just try using python's help (pyhelp()
in the debugger) on debugger commands.
Author: google
Source Code: https://github.com/google/pyringe
License: Apache-2.0 License
1663644300
In this Python article, let's learn about Debugging Tools: Libraries for Debugging Code in Popular Python
A debugger is a software tool that can help the software development process by identifying coding errors at various stages of the operating system or application development. Some debuggers will analyze a test run to see what lines of code were not executed.
Debugger for Python programs with a graphical user interface. It uses bdb (part of stdlib) but adds a GUI and has some powerful features like object browser, windows for variables, classes, functions, exceptions, stack, conditional breakpoints, etc.
ipdb exports functions to access the IPython debugger, which features tab completion, syntax highlighting, better tracebacks, better introspection with the same interface as the pdb module.
Example usage:
import ipdb
ipdb.set_trace()
ipdb.set_trace(context=5) # will show five lines of code
# instead of the default three lines
# or you can set it via IPDB_CONTEXT_SIZE env variable
# or setup.cfg file
ipdb.pm()
ipdb.run('x[0] = 3')
result = ipdb.runcall(function, arg0, arg1, kwarg='foo')
result = ipdb.runeval('f(1,2) - 3')
The set_trace function accepts context which will show as many lines of code as defined, and cond, which accepts boolean values (such as abc == 17) and will start ipdb's interface whenever cond equals to True.
It's possible to set up context using a .ipdb file on your home folder, setup.cfg or pyproject.toml on your project folder. You can also set your file location via env var $IPDB_CONFIG. Your environment variable has priority over the home configuration file, which in turn has priority over the setup config file. Currently, only context setting is available.
A valid setup.cfg is as follows
[ipdb]
context=5
A valid .ipdb is as follows
context=5
A valid pyproject.toml is as follows
[tool.ipdb]
context=5
The post-mortem function, ipdb.pm()
, is equivalent to the magic function %debug
.
pdb++, a drop-in replacement for pdb (the Python debugger)
This module is an extension of the pdb module of the standard library. It is meant to be fully compatible with its predecessor, yet it introduces a number of new features to make your debugging experience as nice as possible.
pdb++
features include:
- colorful TAB completion of Python expressions (through fancycompleter)
- optional syntax highlighting of code listings (through Pygments)
- sticky mode
- several new commands to be used from the interactive
(Pdb++)
prompt- smart command parsing (hint: have you ever typed
r
orc
at the prompt to print the value of some variable?)- additional convenience functions in the
pdb
module, to be used from your program
pdb++
is meant to be a drop-in replacement for pdb
. If you find some unexpected behavior, please report it as a bug.
Since pdb++
is not a valid package name the package is named pdbpp
:
$ pip install pdbpp
pdb++
is also available via conda:
$ conda install -c conda-forge pdbpp
Alternatively, you can just put pdb.py
somewhere inside your PYTHONPATH
.
Its goal is to provide all the niceties of modern GUI-based debuggers in a more lightweight and keyboard-friendly package. PuDB allows you to debug code right where you write and test it--in a terminal.
Here are some screenshots:
Light theme
Dark theme
An improbable web debugger through WebSockets
wdb is a full featured web debugger based on a client-server architecture.
The wdb server which is responsible of managing debugging instances along with browser connections (through websockets) is based on Tornado. The wdb clients allow step by step debugging, in-program python code execution, code edition (based on CodeMirror) setting breakpoints...
Due to this architecture, all of this is fully compatible with multithread and multiprocess programs.
wdb works with python 2 (2.6, 2.7), python 3 (3.2, 3.3, 3.4, 3.5) and pypy. Even better, it is possible to debug a python 2 program with a wdb server running on python 3 and vice-versa or debug a program running on a computer with a debugging server running on another computer inside a web page on a third computer!
Even betterer, it is now possible to pause a currently running python process/thread using code injection from the web interface. (This requires gdb and ptrace enabled)
In other words it's a very enhanced version of pdb directly in your browser with nice features.
Global installation:
$ pip install wdb.server
In virtualenv or with a different python installation:
$ pip install wdb
(You must have the server installed and running)
lptrace is strace for Python programs. It lets you see in real-time what functions a Python program is running. It's particularly useful to debug weird issues on production.
For example, let's debug a non-trivial program, the Python SimpleHTTPServer. First, let's run the server:
vagrant@precise32:/vagrant$ python -m SimpleHTTPServer 8080 &
[1] 1818
vagrant@precise32:/vagrant$ Serving HTTP on 0.0.0.0 port 8080 ...
Now let's connect lptrace to it:
vagrant@precise32:/vagrant$ sudo python lptrace -p 1818
...
fileno (/usr/lib/python2.7/SocketServer.py:438)
meth (/usr/lib/python2.7/socket.py:223)
fileno (/usr/lib/python2.7/SocketServer.py:438)
meth (/usr/lib/python2.7/socket.py:223)
_handle_request_noblock (/usr/lib/python2.7/SocketServer.py:271)
get_request (/usr/lib/python2.7/SocketServer.py:446)
accept (/usr/lib/python2.7/socket.py:201)
__init__ (/usr/lib/python2.7/socket.py:185)
verify_request (/usr/lib/python2.7/SocketServer.py:296)
process_request (/usr/lib/python2.7/SocketServer.py:304)
finish_request (/usr/lib/python2.7/SocketServer.py:321)
__init__ (/usr/lib/python2.7/SocketServer.py:632)
setup (/usr/lib/python2.7/SocketServer.py:681)
makefile (/usr/lib/python2.7/socket.py:212)
__init__ (/usr/lib/python2.7/socket.py:246)
makefile (/usr/lib/python2.7/socket.py:212)
__init__ (/usr/lib/python2.7/socket.py:246)
handle (/usr/lib/python2.7/BaseHTTPServer.py:336)
handle_one_request (/usr/lib/python2.7/BaseHTTPServer.py:301)
^CReceived Ctrl-C, quitting
vagrant@precise32:/vagrant$
You can see that the server is handling the request in real time! After pressing Ctrl-C, the trace is removed and the program execution resumes normally.
Debugging manhole for python applications.
Manhole is in-process service that will accept unix domain socket connections and present the stacktraces for all threads and an interactive prompt. It can either work as a python daemon thread waiting for connections at all times or a signal handler (stopping your application and waiting for a connection).
Access to the socket is restricted to the application's effective user id or root.
This is just like Twisted's manhole. It's simpler (no dependencies), it only runs on Unix domain sockets (in contrast to Twisted's manhole which can run on telnet or ssh) and it integrates well with various types of applications.
Install it:
pip install manhole
You can put this in your django settings, wsgi app file, some module that's always imported early etc:
import manhole
manhole.install() # this will start the daemon thread
# and now you start your app, eg: server.serve_forever()
Now in a shell you can do either of these:
netcat -U /tmp/manhole-1234
socat - unix-connect:/tmp/manhole-1234
socat readline unix-connect:/tmp/manhole-1234
Socat with readline is best (history, editing etc). If your socat doesn't have readline try this.
Sample output:
$ nc -U /tmp/manhole-1234
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dir()
['__builtins__', 'dump_stacktraces', 'os', 'socket', 'sys', 'traceback']
>>> print 'foobar'
foobar
Pyringe is a python debugger capable of attaching to running processes, inspecting their state and even of injecting python code into them while they're running. With pyringe, you can list threads, get tracebacks, inspect locals/globals/builtins of running functions, all without having to prepare your program for it.
You can start the debugger by executing python -m pyringe
. Alternatively:
import pyringe
pyringe.interact()
If that reminds you of the code module, good; this is intentional.
After starting the debugger, you'll be greeted by what behaves almost like a regular python REPL.
Try the following:
==> pid:[None] #threads:[0] current thread:[None]
>>> help()
Available commands:
attach: Attach to the process with the given pid.
bt: Get a backtrace of the current position.
[...]
==> pid:[None] #threads:[0] current thread:[None]
>>> attach(12679)
==> pid:[12679] #threads:[11] current thread:[140108099462912]
>>> threads()
[140108099462912, 140108107855616, 140108116248323, 140108124641024, 140108133033728, 140108224739072, 140108233131776, 140108141426432, 140108241524480, 140108249917184, 140108269324032]
The IDs you see here correspond to what threading.current_thread().ident
would tell you.
All debugger functions are just regular python functions that have been exposed to the REPL, so you can do things like the following.
==> pid:[12679] #threads:[11] current thread:[140108099462912]
>>> for tid in threads():
... if not tid % 10:
... thread(tid)
... bt()
...
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 524, in __bootstrap
self.__bootstrap_inner()
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "./test.py", line 46, in Idle
Thread_2_Func(1)
File "./test.py", line 40, in Wait
time.sleep(n)
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>>
You can access the inferior's locals and inspect them like so:
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>> inflocals()
{'a': <proxy of A object at remote 0x1d9b290>, 'LOL': 'success!', 'b': <proxy of B object at remote 0x1d988c0>, 'n': 1}
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>> p('a')
<proxy of A object at remote 0x1d9b290>
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>> p('a').attr
'Some_magic_string'
==> pid:[12679] #threads:[11] current thread:[140108241524480]
>>>
And sure enough, the definition of a
's class reads:
class Example(object):
cl_attr = False
def __init__(self):
self.attr = 'Some_magic_string'
There's limits to how far this proxying of objects goes, and everything that isn't trivial data will show up as strings (like '<function at remote 0x1d957d0>'
).
Hunter is a flexible code tracing toolkit, not for measuring coverage, but for debugging, logging, inspection and other nefarious purposes. It has a simple Python API, a convenient terminal API and a CLI tool to attach to processes.
pip install hunter
https://python-hunter.readthedocs.io/
Basic use involves passing various filters to the trace
option. An example:
import hunter
hunter.trace(module='posixpath', action=hunter.CallPrinter)
import os
os.path.join('a', 'b')
That would result in:
>>> os.path.join('a', 'b')
/usr/lib/python3.6/posixpath.py:75 call => join(a='a')
/usr/lib/python3.6/posixpath.py:80 line a = os.fspath(a)
/usr/lib/python3.6/posixpath.py:81 line sep = _get_sep(a)
/usr/lib/python3.6/posixpath.py:41 call => _get_sep(path='a')
/usr/lib/python3.6/posixpath.py:42 line if isinstance(path, bytes):
/usr/lib/python3.6/posixpath.py:45 line return '/'
/usr/lib/python3.6/posixpath.py:45 return <= _get_sep: '/'
/usr/lib/python3.6/posixpath.py:82 line path = a
/usr/lib/python3.6/posixpath.py:83 line try:
/usr/lib/python3.6/posixpath.py:84 line if not p:
/usr/lib/python3.6/posixpath.py:86 line for b in map(os.fspath, p):
/usr/lib/python3.6/posixpath.py:87 line if b.startswith(sep):
/usr/lib/python3.6/posixpath.py:89 line elif not path or path.endswith(sep):
/usr/lib/python3.6/posixpath.py:92 line path += sep + b
/usr/lib/python3.6/posixpath.py:86 line for b in map(os.fspath, p):
/usr/lib/python3.6/posixpath.py:96 line return path
/usr/lib/python3.6/posixpath.py:96 return <= join: 'a/b'
'a/b'
In a terminal it would look like:
Another useful scenario is to ignore all standard modules and force colors to make them stay even if the output is redirected to a file.
import hunter
hunter.trace(stdlib=False, action=hunter.CallPrinter(force_colors=True))
line_profiler is a module for doing line-by-line profiling of functions. kernprof is a convenient script for running either line_profiler or the Python standard library's cProfile or profile modules, depending on what is available.
Note: As of version 2.1.2, pip install line_profiler does not work. Please install as follows until it is fixed in the next release:
git clone https://github.com/rkern/line_profiler.git
find line_profiler -name '*.pyx' -exec cython {} \;
cd line_profiler
pip install . --user
Releases of line_profiler can be installed using pip:
$ pip install line_profiler
Source releases and any binaries can be downloaded from the PyPI link.
To check out the development sources, you can use Git:
$ git clone https://github.com/rkern/line_profiler.git
You may also download source tarballs of any snapshot from that URL.
Source releases will require a C compiler in order to build line_profiler. In addition, git checkouts will also require Cython >= 0.10. Source releases on PyPI should contain the pregenerated C sources, so Cython should not be required in that case.
kernprof is a single-file pure Python script and does not require a compiler. If you wish to use it to run cProfile and not line-by-line profiling, you may copy it to a directory on your PATH manually and avoid trying to build any C extensions.
This is a python module for monitoring memory consumption of a process as well as line-by-line analysis of memory consumption for python programs. It is a pure python module which depends on the psutil module.
To install through easy_install or pip:
$ easy_install -U memory_profiler # pip install -U memory_profiler
To install from source, download the package, extract and type:
$ python setup.py install
The line-by-line memory usage mode is used much in the same way of the line_profiler: first decorate the function you would like to profile with @profile
and then run the script with a special script (in this case with specific arguments to the Python interpreter).
In the following example, we create a simple function my_func
that allocates lists a
, b
and then deletes b
:
@profile
def my_func():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a
if __name__ == '__main__':
my_func()
Execute the code passing the option -m memory_profiler
to the python interpreter to load the memory_profiler module and print to stdout the line-by-line analysis. If the file name was example.py, this would result in:
$ python -m memory_profiler example.py
Output will follow:
Line # Mem usage Increment Line Contents
==============================================
3 @profile
4 5.97 MB 0.00 MB def my_func():
5 13.61 MB 7.64 MB a = [1] * (10 ** 6)
6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7)
7 13.61 MB -152.59 MB del b
8 13.61 MB 0.00 MB return a
The first column represents the line number of the code that has been profiled, the second column (Mem usage) the memory usage of the Python interpreter after that line has been executed. The third column (Increment) represents the difference in memory of the current line with respect to the last one. The last column (Line Contents) prints the code that has been profiled.
py-spy is a sampling profiler for Python programs. It lets you visualize what your Python program is spending time on without restarting the program or modifying the code in any way. py-spy is extremely low overhead: it is written in Rust for speed and doesn't run in the same process as the profiled Python program. This means py-spy is safe to use against production Python code.
py-spy works on Linux, OSX, Windows and FreeBSD, and supports profiling all recent versions of the CPython interpreter (versions 2.3-2.7 and 3.3-3.10).
Prebuilt binary wheels can be installed from PyPI with:
pip install py-spy
You can also download prebuilt binaries from the GitHub Releases Page.
If you're a Rust user, py-spy can also be installed with: cargo install py-spy
.
On macOS, py-spy is in Homebrew and can be installed with brew install py-spy
.
On Arch Linux, py-spy is in AUR and can be installed with yay -S py-spy
.
On Alpine Linux, py-spy is in testing repository and can be installed with apk add py-spy --update-cache --repository http://dl-3.alpinelinux.org/alpine/edge/testing/ --allow-untrusted
.
py-spy works from the command line and takes either the PID of the program you want to sample from or the command line of the python program you want to run. py-spy has three subcommands record
, top
and dump
:
py-spy supports recording profiles to a file using the record
command. For example, you can generate a flame graph of your python process by going:
py-spy record -o profile.svg --pid 12345
# OR
py-spy record -o profile.svg -- python myprogram.py
Pyflame is a high performance profiling tool that generates flame graphs for Python. Pyflame is implemented in C++, and uses the Linux ptrace(2) system call to collect profiling information. It can take snapshots of the Python call stack without explicit instrumentation, meaning you can profile a program without modifying its source code. Pyflame is capable of profiling embedded Python interpreters like uWSGI. It fully supports profiling multi-threaded Python programs.
Pyflame usually introduces significantly less overhead than the builtin profile
(or cProfile
) modules, and emits richer profiling data. The profiling overhead is low enough that you can use it to profile live processes in production.
For Debian/Ubuntu, install the following:
# Install build dependencies on Debian or Ubuntu.
sudo apt-get install autoconf automake autotools-dev g++ pkg-config python-dev python3-dev libtool make
Once you have the build dependencies installed:
./autogen.sh
./configure
make
The make
command will produce an executable at src/pyflame
that you can run and use.
Optionally, if you have virtualenv
installed, you can test the executable you produced using make check
.
The full documentation for using Pyflame is here. But here's a quick guide:
# Attach to PID 12345 and profile it for 1 second
pyflame -p 12345
# Attach to PID 768 and profile it for 5 seconds, sampling every 0.01 seconds
pyflame -s 5 -r 0.01 -p 768
# Run py.test against tests/, emitting sample data to prof.txt
pyflame -o prof.txt -t py.test tests/
In all of these cases you will get flame graph data on stdout (or to a file if you used -o
). This data is in the format expected by flamegraph.pl
, which you can find here.
vprof is a Python package providing rich and interactive visualizations for various Python program characteristics such as running time and memory usage. It supports Python 3.4+ and distributed under BSD license.
The project is in active development and some of its features might not work as expected.
vprof
can be installed from PyPI
pip install vprof
To build vprof
from sources, clone this repository and execute
python3 setup.py deps_install && python3 setup.py build_ui && python3 setup.py install
To install just vprof
dependencies, run
python3 setup.py deps_install
vprof -c <config> <src>
<config>
is a combination of supported modes:
c
- CPU flame graph ⚠️ Not available for windows #62Shows CPU flame graph for <src>
.
p
- profilerRuns built-in Python profiler on <src>
and displays results.
m
- memory graphShows objects that are tracked by CPython GC and left in memory after code execution. Also shows process memory usage after execution of each line of <src>
.
h
- code heatmapDisplays all executed code of <src>
with line run times and execution counts.
The Django Debug Toolbar is a configurable set of panels that display various debug information about the current request/response and when clicked, display more details about the panel's content.
Here's a screenshot of the toolbar in action:
In addition to the built-in panels, a number of third-party panels are contributed by the community.
The current stable version of the Debug Toolbar is 3.6.0. It works on Django ≥ 3.2.4.
A drop in replacement for Django's built-in runserver command. Features include:
Note
django-devserver works on Django 1.3 and newer
To install the latest stable version:
pip install git+git://github.com/dcramer/django-devserver#egg=django-devserver
django-devserver has some optional dependancies, which we highly recommend installing.
pip install sqlparse
-- pretty SQL formattingpip install werkzeug
-- interactive debuggerpip install guppy
-- tracks memory usage (required for MemoryUseModule)pip install line_profiler
-- does line-by-line profiling (required for LineProfilerModule)You will need to include devserver
in your INSTALLED_APPS
:
INSTALLED_APPS = (
...
'devserver',
)
If you're using django.contrib.staticfiles
or any other apps with management command runserver
, make sure to put devserver
above any of them (or below, for Django<1.7
). Otherwise devserver
will log an error, but it will fail to work properly.
This is a port of the excellent django-debug-toolbar for Flask applications.
Installing is simple with pip:
$ pip install flask-debugtoolbar
Setting up the debug toolbar is simple:
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
# the toolbar is only enabled in debug mode:
app.debug = True
# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'
toolbar = DebugToolbarExtension(app)
The toolbar will automatically be injected into Jinja templates when debug mode is on. In production, setting app.debug = False
will disable the toolbar.
Do you ever use print()
or log()
to debug your code? Of course you do. IceCream, or ic
for short, makes print debugging a little sweeter.
ic()
is like print()
, but better:
IceCream is well tested, permissively licensed, and supports Python 2, Python 3, PyPy2, and PyPy3. (Python 3.11 support is forthcoming.)
Have you ever printed variables or expressions to debug your program? If you've ever typed something like
print(foo('123'))
or the more thorough
print("foo('123')", foo('123'))
then ic()
will put a smile on your face. With arguments, ic()
inspects itself and prints both its own arguments and the values of those arguments.
from icecream import ic
def foo(i):
return i + 333
ic(foo(123))
Prints
ic| foo(123): 456
Similarly,
d = {'key': {1: 'one'}}
ic(d['key'][1])
class klass():
attr = 'yep'
ic(klass.attr)
Prints
ic| d['key'][1]: 'one'
ic| klass.attr: 'yep'
Just give ic()
a variable or expression and you're done. Easy.
pyelftools is a pure-Python library for parsing and analyzing ELF files and DWARF debugging information. See the User's guide for more details.
As a user of pyelftools, one only needs Python 3 to run. For hacking on pyelftools the requirements are a bit more strict, please see the hacking guide.
pyelftools can be installed from PyPI (Python package index):
> pip install pyelftools
Alternatively, you can download the source distribution for the most recent and historic versions from the Downloads tab on the pyelftools project page (by going to Tags). Then, you can install from source, as usual:
> python setup.py install
Since pyelftools is a work in progress, it's recommended to have the most recent version of the code. This can be done by downloading the master zip file or just cloning the Git repository.
Since pyelftools has no external dependencies, it's also easy to use it without installing, by locally adjusting PYTHONPATH
.
Debugging in any programming language typically involves two types of errors: syntax or logical. Syntax errors are those where the programming language commands are not interpreted by the compiler or interpreter because of a problem with how the program is written.
Chrome DevTools, Progress Telerik Fiddler, GDB (GNU Debugger), Data Display Debugger, SonarLint, Froglogic Squish, and TotalView HPC Debugging Software.
The terms "bug" and "debugging" are popularly attributed to Admiral Grace Hopper in the 1940s. While she was working on a Mark II computer at Harvard University, her associates discovered a moth stuck in a relay and thereby impeding operation, whereupon she remarked that they were "debugging" the system.
Debugging is important because it allows software engineers and developers to fix errors in a program before releasing it to the public. It's a complementary process to testing, which involves learning how an error affects a program overall.
Python Tutorial - Introduction to DEBUGGING
1662107520
Superdom
You have dom
. It has all the DOM virtually within it. Use that power:
// Fetch all the page links
let links = dom.a.href;
// Links open in a new tab
dom.a.target = '_blank';
Only for modern browsers
Simply use the CDN via unpkg.com:
<script src="https://unpkg.com/superdom@1"></script>
Or use npm or bower:
npm|bower install superdom --save
It always returns an array with the matched elements. Get all the elements that match the selector:
// Simple element selector into an array
let allLinks = dom.a;
// Loop straight on the selection
dom.a.forEach(link => { ... });
// Combined selector
let importantLinks = dom['a.important'];
There are also some predetermined elements, such as id
, class
and attr
:
// Select HTML Elements by id:
let main = dom.id.main;
// by class:
let buttons = dom.class.button;
// or by attribute:
let targeted = dom.attr.target;
let targeted = dom.attr['target="_blank"'];
Use it as a function or a tagged template literal to generate DOM fragments:
// Not a typo; tagged template literals
let link = dom`<a href="https://google.com/">Google</a>`;
// It is the same as
let link = dom('<a href="https://google.com/">Google</a>');
Delete a piece of the DOM
// Delete all of the elements with the class .google
delete dom.class.google; // Is this an ad-block rule?
You can easily manipulate attributes right from the dom
node. There are some aliases that share the syntax of the attributes such as html
and text
(aliases for innerHTML
and textContent
). There are others that travel through the dom such as parent
(alias for parentNode) and children
. Finally, class
behaves differently as explained below.
The fetching will always return an array with the element for each of the matched nodes (or undefined if not there):
// Retrieve all the urls from the page
let urls = dom.a.href; // #attr-list
// ['https://google.com', 'https://facebook.com/', ...]
// Get an array of the h2 contents (alias of innerHTML)
let h2s = dom.h2.html; // #attr-alias
// ['Level 2 header', 'Another level 2 header', ...]
// Get whether any of the attributes has the value "_blank"
let hasBlank = dom.class.cta.target._blank; // #attr-value
// true/false
You also use these:
innerHTML
): retrieve a list of the htmlstextContent
): retrieve a list of the htmlsparentNode
): travel up one level// Set target="_blank" to all links
dom.a.target = '_blank'; // #attr-set
dom.class.tableofcontents.html = `
<ul class="tableofcontents">
${dom.h2.map(h2 => `
<li>
<a href="#${h2.id}">
${h2.innerHTML}
</a>
</li>
`).join('')}
</ul>
`;
To delete an attribute use the delete
keyword:
// Remove all urls from the page
delete dom.a.href;
// Remove all ids
delete dom.a.id;
It provides an easy way to manipulate the classes.
To retrieve whether a particular class is present or not:
// Get an array with true/false for a single class
let isTest = dom.a.class.test; // #class-one
For a general method to retrieve all classes you can do:
// Get a list of the classes of each matched element
let arrays = dom.a.class; // #class-arrays
// [['important'], ['button', 'cta'], ...]
// If you want a plain list with all of the classes:
let flatten = dom.a.class._flat; // #class-flat
// ['important', 'button', 'cta', ...]
// And if you just want an string with space-separated classes:
let text = dom.a.class._text; // #class-text
// 'important button cta ...'
// Add the class 'test' (different ways)
dom.a.class.test = true; // #class-make-true
dom.a.class = 'test'; // #class-push
// Remove the class 'test'
dom.a.class.test = false; // #class-make-false
Did we say it returns a simple array?
dom.a.forEach(link => link.innerHTML = 'I am a link');
But what an interesting array it is; indeed we are also proxy'ing it so you can manipulate its sub-elements straight from the selector:
// Replace all of the link's html with 'I am a link'
dom.a.html = 'I am a link';
Of course we might want to manipulate them dynamically depending on the current value. Just pass it a function:
// Append ' ^_^' to all of the links in the page
dom.a.html = html => html + ' ^_^';
// Same as this:
dom.a.forEach(link => link.innerHTML = link.innerHTML + ' ^_^');
Note: this won't work
dom.a.html += ' ^_^';
for more than 1 match (for reasons)
Or get into genetics to manipulate the attributes:
dom.a.attr.target = '_blank';
// Only to external sites:
let isOwnPage = el => /^https?\:\/\/mypage\.com/.test(el.getAttribute('href'));
dom.a.attr.target = (prev, i, element) => isOwnPage(element) ? '' : '_blank';
You can also handle and trigger events:
// Handle click events for all <a>
dom.a.on.click = e => ...;
// Trigger click event for all <a>
dom.a.trigger.click;
We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:
grunt watch
Author: franciscop
Source Code: https://github.com/franciscop/superdom
License: MIT license
1617449307
Chartered Accountancy course requires mental focus & discipline, coaching for CA Foundation, CA Inter and CA Finals are omnipresent, and some of the best faculty’s classes have moved online, in this blog, we are going to give the best way to find online videos lectures, various online websites provide the CA lectures, Smartnstudy one of the best site to CA preparation, here all faculty’s video lecture available.
check here : ca classes
#ca classes online #ca classes in delhi #ca classes app #ca pendrive classes #ca google drive classes #best ca classes online